diff --git a/.gitignore b/.gitignore index 548f1e3979..8fc575c216 100644 --- a/.gitignore +++ b/.gitignore @@ -29,8 +29,9 @@ Properties !_infrastructure/tests/*/*.js !_infrastructure/tests/*/*/*.js !_infrastructure/tests/*/*/*/*.js - -.idea -*.iml - -node_modules + +.idea +*.iml +*.js.map + +node_modules diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..13053ce7ff --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1 @@ +Please see the [contribution guide](https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute) for information on how to contribute to this project. diff --git a/README.md b/README.md index d2affa36db..29c94b8042 100755 --- a/README.md +++ b/README.md @@ -21,8 +21,7 @@ See the section: [How to contribute](https://github.com/borisyankov/DefinitelyTy Other means to get the definitions ---------------------------------- * [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped) -* [TypeScript definition package manager](https://github.com/Diullei/tsd) -* [tsdpm](http://www.tsdpm.com/) - Online search +* [TypeScript Definition package manager](https://github.com/DefinitelyTyped/tsd) List of Definitions ------------------- @@ -30,14 +29,18 @@ List of Definitions * [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei)) * [Add To Home Screen] (http://cubiq.org/add-to-home-screen) (by [James Wilkins] (http://www.codeplex.com/site/users/view/jamesnw)) * [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/)) +* [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft)) * [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) * [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib)) +* [Angular Protractor](https://github.com/angular/protractor) (by [Bill Armstrong](https://github.com/BillArmstrong)) +* [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib)) * [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted)) * [AppFramework](http://app-framework-software.intel.com/) (by [Kyo Ago](https://github.com/kyo-ago)) * [Arbiter](http://arbiterjs.com/) (by [Arash Shakery](https://github.com/arash16)) * [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov)) * [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm)) +* [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg)) * [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds)) * [Bootbox](https://github.com/makeusabrew/bootbox) (by [Vincent Bortone](https://github.com/vbortone/)) * [Bootstrap](http://twitter.github.com/bootstrap/) (by [Boris Yankov](https://github.com/borisyankov)) @@ -61,8 +64,10 @@ List of Definitions * [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) (by [Maksim Kozhukh](http://github.com/mkozhukh)) * [docCookies](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie) (by [Jon Egerton](https://github.com/jonegerton)) * [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton)) +* [doT](https://github.com/olado/doT) (by [ZombieHunter](https://github.com/ZombieHunter)) * [dust](http://linkedin.github.com/dustjs) (by [Marcelo Dezem](https://github.com/mdezem)) * [EaselJS](http://www.createjs.com/#!/EaselJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [EasyStar](http://easystarjs.com/) (by [Magnus Gustafsson](https://github.com/Borundin)) * [ember.js](http://emberjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) * [EpicEditor](http://epiceditor.com/) (by [Boris Yankov](https://github.com/borisyankov)) * [ES6-Promises](https://github.com/jakearchibald/ES6-Promises) (by [François de Campredon](https://github.com/fdecampredon/)) @@ -92,6 +97,7 @@ List of Definitions * [Google API Client](https://code.google.com/p/google-api-javascript-client/) (by [Frank M](https://github.com/sgtfrankieboy)) * [Google App Engine Channel API](https://developers.google.com/appengine/docs/java/channel/javascript) (by [vvakame](https://github.com/vvakame)) * [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper)) +* [GoogleMaps InfoBubble](http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/) (by [Johan Nilsson](https://github.com/dashue)) * [Google Geolocation](https://code.google.com/p/geo-location-javascript/) (by [Vincent Bortone](https://github.com/vbortone)) * [Google Page Speed Online API](https://developers.google.com/speed/pagespeed/) (by [Frank M](https://github.com/sgtfrankieboy)) * [Google Translate API](https://developers.google.com/translate/) (by [Frank M](https://github.com/sgtfrankieboy)) @@ -101,6 +107,7 @@ List of Definitions * [HashSet](http://www.timdown.co.uk/jshashtable/jshashset.html) (by [Sergey Gerasimov](https://github.com/gerich-home)) * [Hashtable](http://www.timdown.co.uk/jshashtable/) (by [Sergey Gerasimov](https://github.com/gerich-home)) * [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog)) +* [Highland](http://highlandjs.org/) (by [Bart van der Schoor](https://github.com/Bartvds/)) * [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) @@ -128,6 +135,7 @@ List of Definitions * [jQuery.contextMenu](http://medialize.github.com/jQuery-contextMenu/) (by [Natan Vivo](https://github.com/nvivo/)) * [jQuery.Cookie](https://github.com/carhartl/jquery-cookie) (by [Roy Goode](https://github.com/RoyGoode)) * [jQuery.Cycle](http://jquery.malsup.com/cycle/) (by [François Guillot](http://fguillot.developpez.com/)) +* [jQuery.Cycle2](http://jquery.malsup.com/cycle2/) (by [Donny Nadolny](https://github.com/dnadolny)) * [jQuery.dataTables](http://www.datatables.net) (by [Armin Sander](https://github.com/pragmatrix)) * [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [François de Campredon](https://github.com/fdecampredon)) * [jQuery.Flot](http://www.flotcharts.org/) (by [Matt Burland](https://github.com/burlandm)) @@ -177,11 +185,13 @@ List of Definitions * [Levelup](https://github.com/rvagg/node-levelup) (by [Bret Little](https://github.com/blittle)) * [linq.js](http://linqjs.codeplex.com/) (by [Marcin Najder](https://github.com/marcinnajder)) * [Livestamp.js](https://github.com/mattbradley/livestampjs) (by [Vincent Bortone](https://github.com/vbortone)) +* [localForage](https://github.com/mozilla/localForage) (by [david pichsenmeister](https://github.com/3x14159265)) * [Lodash](http://lodash.com/) (by [Brian Zengel](https://github.com/bczengel)) * [Logg](https://github.com/dpup/node-logg) (by [Bret Little](https://github.com/blittle)) * [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr)) -* [mCustomScrollbar](https://github.com/malihu/malihu-custom-scrollbar-plugin) (by [Sarah Williams] (https://github.com/flurg)) +* [mCustomScrollbar](https://github.com/malihu/malihu-custom-scrollbar-plugin) (by [Sarah Williams](https://github.com/flurg)) * [Meteor](https://www.meteor.com) (by [Dave Allen](https://github.com/fullflavedave)) +* [Microsoft Live Connect](http://msdn.microsoft.com/en-us/library/live/hh243643.aspx) (by [John Vilk](https://github.com/jvilk)) * [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov) and [Theodore Brown](https://github.com/theodorejb/)) * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) * [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee)) @@ -196,7 +206,7 @@ List of Definitions * [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) * [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) * [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) -* [OpenLayers] (https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) +* [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) * [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) * [PDF.js](https://github.com/mozilla/pdf.js) (by [Josh Baldwin](https://github.com/jbaldwin)) * [Persona](http://www.mozilla.org/en-US/persona) (by [James Frasca](https://github.com/Nycto)) @@ -206,6 +216,8 @@ List of Definitions * [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH)) * [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/)) * [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar) +* [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) * [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo)) * [Rickshaw](http://code.shutterstock.com/rickshaw/) (by [Blake Niemyjski](https://github.com/niemyjski)) @@ -218,6 +230,8 @@ List of Definitions * [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Selenium WebDriverJS](https://code.google.com/p/selenium/) (by [Bill Armstrong](https://github.com/BillArmstrong)) +* [Semver](https://github.com/isaacs/node-semver) (by [Bart van der Schoor](https://github.com/Bartvds)) * [Sencha Touch](http://www.sencha.com/products/touch/) (by [Brian Kotek](https://github.com/brian428)) * [SharePoint](http://sptypescript.codeplex.com) (by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru) and [Andrey Markeev](http://markeev.com)) * [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov)) @@ -226,6 +240,7 @@ List of Definitions * [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin)) * [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley)) * [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) +* [socket.io-client](http://socket.io) (by [Maido Kaara](https://github.com/v3rm0n)) * [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev)) * [SoundJS](http://www.createjs.com/#!/SoundJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) * [Spin](http://fgnass.github.com/spin.js/) (by [Boris Yankov](https://github.com/borisyankov)) @@ -234,6 +249,7 @@ List of Definitions * [Sugar](http://sugarjs.com/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Swiper](http://www.idangero.us/sliders/swiper) (by [Sebastián Galiano](https://github.com/sgaliano)) * [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov)) +* [TV4](https://github.com/geraintluff/tv4) (by [Bart van der Schoor](https://github.com/Bartvds)) * [Tags Manager](http://welldonethings.com/tags/manager) (by [Vincent Bortone](https://github.com/vbortone)) * [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com)) * [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/)) @@ -247,6 +263,7 @@ List of Definitions * [Underscore.js](http://underscorejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Underscore.js (Typed)](http://underscorejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Underscore-ko.js](https://github.com/kamranayub/UnderscoreKO) (by [Maurits Elbers](https://github.com/MagicMau)) +* [universal-analytics](https://github.com/peaksandpies/universal-analytics) (by [Bart van der Schoor](https://github.com/Bartvds)) * [UUID.js](https://github.com/LiosK/UUID.js) (by [Jason Jarrett](https://github.com/staxmanade)) * [Valerie](https://github.com/davewatts/valerie) (by [Howard Richards](https://github.com/conficient)) * [Viewporter](https://github.com/zynga/viewporter) (by [Boris Yankov](https://github.com/borisyankov)) diff --git a/_infrastructure/tests/_ref.d.ts b/_infrastructure/tests/_ref.d.ts new file mode 100644 index 0000000000..5a0809f3b8 --- /dev/null +++ b/_infrastructure/tests/_ref.d.ts @@ -0,0 +1 @@ +/// diff --git a/_infrastructure/tests/runner.js b/_infrastructure/tests/runner.js index 2721d83ab3..6495699236 100644 --- a/_infrastructure/tests/runner.js +++ b/_infrastructure/tests/runner.js @@ -1,1168 +1,1317 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -var ExecResult = (function () { - function ExecResult() { - this.stdout = ""; - this.stderr = ""; - } - return ExecResult; -})(); +var DT; +(function (DT) { + 'use strict'; -var WindowsScriptHostExec = (function () { - function WindowsScriptHostExec() { - } - WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var result = new ExecResult(); - var shell = new ActiveXObject('WScript.Shell'); - try { - var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); - } catch (e) { - result.stderr = e.message; - result.exitCode = 1; - handleResult(result); - return; + var Promise = require('bluebird'); + var nodeExec = require('child_process').exec; + + var ExecResult = (function () { + function ExecResult() { + this.stdout = ''; + this.stderr = ''; } + return ExecResult; + })(); + DT.ExecResult = ExecResult; - while (process.Status != 0) { - } + function exec(filename, cmdLineArgs) { + return new Promise(function (resolve) { + var result = new ExecResult(); + result.exitCode = null; - result.exitCode = process.ExitCode; - if (!process.StdOut.AtEndOfStream) - result.stdout = process.StdOut.ReadAll(); - if (!process.StdErr.AtEndOfStream) - result.stderr = process.StdErr.ReadAll(); + var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - handleResult(result); - }; - return WindowsScriptHostExec; -})(); - -var NodeExec = (function () { - function NodeExec() { - } - NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var nodeExec = require('child_process').exec; - - var result = new ExecResult(); - result.exitCode = null; - var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - - var process = nodeExec(cmdLine, { maxBuffer: 1 * 1024 * 1024 }, function (error, stdout, stderr) { - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - handleResult(result); + nodeExec(cmdLine, { maxBuffer: 1 * 1024 * 1024 }, function (error, stdout, stderr) { + result.error = error; + result.stdout = stdout; + result.stderr = stderr; + result.exitCode = error ? error.code : 0; + resolve(result); + }); }); - }; - return NodeExec; -})(); - -var Exec = (function () { - var global = Function("return this;").call(null); - if (typeof global.ActiveXObject !== "undefined") { - return new WindowsScriptHostExec(); - } else { - return new NodeExec(); } -})(); -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -var IOUtils; -(function (IOUtils) { - // Creates the directory including its parent if not already present - function createDirectoryStructure(ioHost, dirName) { - if (ioHost.directoryExists(dirName)) { - return; + DT.exec = exec; +})(DT || (DT = {})); +/// +var DT; +(function (DT) { + 'use strict'; + + var path = require('path'); + + ///////////////////////////////// + // Given a document root + ts file pattern this class returns: + // all the TS files OR just tests OR just definition files + ///////////////////////////////// + var File = (function () { + function File(baseDir, filePathWithName) { + this.references = []; + // why choose? + this.baseDir = baseDir; + this.filePathWithName = filePathWithName; + this.ext = path.extname(this.filePathWithName); + this.file = path.basename(this.filePathWithName, this.ext); + this.dir = path.dirname(this.filePathWithName); + this.fullPath = path.join(this.baseDir, this.dir, this.file + this.ext); + // lock it (shallow) (needs `use strict` in each file to work) + // Object.freeze(this); } - - var parentDirectory = ioHost.dirName(dirName); - if (parentDirectory != "") { - createDirectoryStructure(ioHost, parentDirectory); - } - ioHost.createDirectory(dirName); - } - - // Creates a file including its directory structure if not already present - function createFileAndFolderStructure(ioHost, fileName, useUTF8) { - var path = ioHost.resolvePath(fileName); - var dirName = ioHost.dirName(path); - createDirectoryStructure(ioHost, dirName); - return ioHost.createFile(path, useUTF8); - } - IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; - - function throwIOError(message, error) { - var errorMessage = message; - if (error && error.message) { - errorMessage += (" " + error.message); - } - throw new Error(errorMessage); - } - IOUtils.throwIOError = throwIOError; -})(IOUtils || (IOUtils = {})); - -var IO = (function () { - // Create an IO object for use inside WindowsScriptHost hosts - // Depends on WSCript and FileSystemObject - function getWindowsScriptHostIO() { - var fso = new ActiveXObject("Scripting.FileSystemObject"); - var streamObjectPool = []; - - function getStreamObject() { - if (streamObjectPool.length > 0) { - return streamObjectPool.pop(); - } else { - return new ActiveXObject("ADODB.Stream"); - } - } - - function releaseStreamObject(obj) { - streamObjectPool.push(obj); - } - - var args = []; - for (var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - - return { - readFile: function (path) { - try { - var streamObj = getStreamObject(); - streamObj.Open(); - streamObj.Type = 2; - streamObj.Charset = 'x-ansi'; - streamObj.LoadFromFile(path); - var bomChar = streamObj.ReadText(2); - streamObj.Position = 0; - if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { - streamObj.Charset = 'unicode'; - } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { - streamObj.Charset = 'utf-8'; - } - - // Read the whole file - var str = streamObj.ReadText(-1); - streamObj.Close(); - releaseStreamObject(streamObj); - return str; - } catch (err) { - IOUtils.throwIOError("Error reading file \"" + path + "\".", err); - } - }, - writeFile: function (path, contents) { - var file = this.createFile(path); - file.Write(contents); - file.Close(); - }, - fileExists: function (path) { - return fso.FileExists(path); - }, - resolvePath: function (path) { - return fso.GetAbsolutePathName(path); - }, - dirName: function (path) { - return fso.GetParentFolderName(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; - - while (true) { - if (fso.FileExists(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } catch (err) { - //Tools.CompilerDiagnostics.debugPrint("Could not find " + path + ", trying parent"); - } - } else { - rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); - - if (rootPath == "") { - return null; - } else { - path = fso.BuildPath(rootPath, partialFilePath); - } - } - } - }, - deleteFile: function (path) { - try { - if (fso.FileExists(path)) { - fso.DeleteFile(path, true); - } - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - createFile: function (path, useUTF8) { - try { - var streamObj = getStreamObject(); - streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; - streamObj.Open(); - return { - Write: function (str) { - streamObj.WriteText(str, 0); - }, - WriteLine: function (str) { - streamObj.WriteText(str, 1); - }, - Close: function () { - try { - streamObj.SaveToFile(path, 2); - } catch (saveError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); - } finally { - if (streamObj.State != 0) { - streamObj.Close(); - } - releaseStreamObject(streamObj); - } - } - }; - } catch (creationError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); - } - }, - directoryExists: function (path) { - return fso.FolderExists(path); - }, - createDirectory: function (path) { - try { - if (!this.directoryExists(path)) { - fso.CreateFolder(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - dir: function (path, spec, options) { - options = options || {}; - function filesInFolder(folder, root) { - var paths = []; - var fc; - - if (options.recursive) { - fc = new Enumerator(folder.subfolders); - - for (; !fc.atEnd(); fc.moveNext()) { - paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); - } - } - - fc = new Enumerator(folder.files); - - for (; !fc.atEnd(); fc.moveNext()) { - if (!spec || fc.item().Name.match(spec)) { - paths.push(root + "/" + fc.item().Name); - } - } - - return paths; - } - - var folder = fso.GetFolder(path); - var paths = []; - - return filesInFolder(folder, path); - }, - print: function (str) { - WScript.StdOut.Write(str); - }, - printLine: function (str) { - WScript.Echo(str); - }, - arguments: args, - stderr: WScript.StdErr, - stdout: WScript.StdOut, - watchFile: null, - run: function (source, filename) { - try { - eval(source); - } catch (e) { - IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); - } - }, - getExecutingFilePath: function () { - return WScript.ScriptFullName; - }, - quit: function (exitCode) { - if (typeof exitCode === "undefined") { exitCode = 0; } - try { - WScript.Quit(exitCode); - } catch (e) { - } - } + File.prototype.toString = function () { + return '[File ' + this.filePathWithName + ']'; }; + return File; + })(); + DT.File = File; +})(DT || (DT = {})); +/// +/// +/// +var DT; +(function (DT) { + 'use strict'; + + var fs = require('fs'); + + var Promise = require('bluebird'); + + var Tsc = (function () { + function Tsc() { + } + Tsc.run = function (tsfile, options) { + var tscPath; + return new Promise.attempt(function () { + options = options || {}; + options.tscVersion = options.tscVersion || DT.DEFAULT_TSC_VERSION; + if (typeof options.checkNoImplicitAny === 'undefined') { + options.checkNoImplicitAny = true; + } + if (typeof options.useTscParams === 'undefined') { + options.useTscParams = true; + } + return DT.fileExists(tsfile); + }).then(function (exists) { + if (!exists) { + throw new Error(tsfile + ' not exists'); + } + tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js'; + return DT.fileExists(tscPath); + }).then(function (exists) { + if (!exists) { + throw new Error(tscPath + ' is not exists'); + } + return DT.fileExists(tsfile + '.tscparams'); + }).then(function (exists) { + var command = 'node ' + tscPath + ' --module commonjs '; + if (options.useTscParams && exists) { + command += '@' + tsfile + '.tscparams'; + } else if (options.checkNoImplicitAny) { + command += '--noImplicitAny'; + } + return DT.exec(command, [tsfile]); + }); + }; + return Tsc; + })(); + DT.Tsc = Tsc; +})(DT || (DT = {})); +/// +/// +var DT; +(function (DT) { + 'use strict'; + + ///////////////////////////////// + // Timer.start starts a timer + // Timer.end stops the timer and sets asString to the pretty print value + ///////////////////////////////// + var Timer = (function () { + function Timer() { + this.time = 0; + this.asString = ''; + } + Timer.prototype.start = function () { + this.time = 0; + this.startTime = this.now(); + this.asString = ''; + }; + + Timer.prototype.now = function () { + return Date.now(); + }; + + Timer.prototype.end = function () { + this.time = (this.now() - this.startTime) / 1000; + this.asString = Timer.prettyDate(this.startTime, this.now()); + }; + + Timer.prettyDate = function (date1, date2) { + var diff = ((date2 - date1) / 1000); + var day_diff = Math.floor(diff / 86400); + + if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) { + return null; + } + + return (day_diff == 0 && (diff < 60 && (diff + ' seconds') || diff < 120 && '1 minute' || diff < 3600 && Math.floor(diff / 60) + ' minutes' || diff < 7200 && '1 hour' || diff < 86400 && Math.floor(diff / 3600) + ' hours') || day_diff == 1 && 'Yesterday' || day_diff < 7 && day_diff + ' days' || day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks'); + }; + return Timer; + })(); + DT.Timer = Timer; +})(DT || (DT = {})); +/// +var DT; +(function (DT) { + 'use strict'; + + var fs = require('fs'); + var Lazy = require('lazy.js'); + var Promise = require('bluebird'); + + var referenceTagExp = //g; + + function endsWith(str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; } - ; + DT.endsWith = endsWith; - // Create an IO object for use inside Node.js hosts - // Depends on 'fs' and 'path' modules - function getNodeIO() { - var _fs = require('fs'); - var _path = require('path'); - var _module = require('module'); + function extractReferenceTags(source) { + var ret = []; + var match; - return { - readFile: function (file) { - try { - var buffer = _fs.readFileSync(file); - switch (buffer[0]) { - case 0xFE: - if (buffer[1] == 0xFF) { - // utf16-be. Reading the buffer as big endian is not supported, so convert it to - // Little Endian first - var i = 0; - while ((i + 1) < buffer.length) { - var temp = buffer[i]; - buffer[i] = buffer[i + 1]; - buffer[i + 1] = temp; - i += 2; - } - return buffer.toString("ucs2", 2); - } - break; - case 0xFF: - if (buffer[1] == 0xFE) { - // utf16-le - return buffer.toString("ucs2", 2); - } - break; - case 0xEF: - if (buffer[1] == 0xBB) { - // utf-8 - return buffer.toString("utf8", 3); - } + if (!referenceTagExp.global) { + throw new Error('referenceTagExp RegExp must have global flag'); + } + referenceTagExp.lastIndex = 0; + + while ((match = referenceTagExp.exec(source))) { + if (match.length > 0 && match[1].length > 0) { + ret.push(match[1]); + } + } + return ret; + } + DT.extractReferenceTags = extractReferenceTags; + + function fileExists(target) { + return new Promise(function (resolve, reject) { + fs.exists(target, function (bool) { + resolve(bool); + }); + }); + } + DT.fileExists = fileExists; +})(DT || (DT = {})); +/// +/// +/// +var DT; +(function (DT) { + 'use strict'; + + var fs = require('fs'); + var path = require('path'); + var glob = require('glob'); + var Lazy = require('lazy.js'); + var Promise = require('bluebird'); + + var readFile = Promise.promisify(fs.readFile); + + ///////////////////////////////// + // Track all files in the repo: map full path to File objects + ///////////////////////////////// + var FileIndex = (function () { + function FileIndex(runner, options) { + this.runner = runner; + this.options = options; + } + FileIndex.prototype.hasFile = function (target) { + return target in this.fileMap; + }; + + FileIndex.prototype.getFile = function (target) { + if (target in this.fileMap) { + return this.fileMap[target]; + } + return null; + }; + + FileIndex.prototype.setFile = function (file) { + if (file.fullPath in this.fileMap) { + throw new Error('cannot overwrite file'); + } + this.fileMap[file.fullPath] = file; + }; + + FileIndex.prototype.readIndex = function () { + var _this = this; + this.fileMap = Object.create(null); + + return Promise.promisify(glob).call(glob, '**/*.ts', { + cwd: this.runner.dtPath + }).then(function (filesNames) { + _this.files = Lazy(filesNames).filter(function (fileName) { + return _this.runner.checkAcceptFile(fileName); + }).map(function (fileName) { + var file = new DT.File(_this.runner.dtPath, fileName); + _this.fileMap[file.fullPath] = file; + return file; + }).toArray(); + }); + }; + + FileIndex.prototype.collectDiff = function (changes) { + var _this = this; + return new Promise(function (resolve) { + // filter changes and bake map for easy lookup + _this.changed = Object.create(null); + _this.removed = Object.create(null); + + Lazy(changes).filter(function (full) { + return _this.runner.checkAcceptFile(full); + }).uniq().each(function (local) { + var full = path.resolve(_this.runner.dtPath, local); + var file = _this.getFile(full); + if (!file) { + // TODO figure out what to do here + // what does it mean? deleted?ss + file = new DT.File(_this.runner.dtPath, local); + _this.setFile(file); + _this.removed[full] = file; + // console.log('not in index? %', file.fullPath); + } else { + _this.changed[full] = file; } + }); - // Default behaviour - return buffer.toString(); - } catch (e) { - IOUtils.throwIOError("Error reading file \"" + file + "\".", e); - } - }, - writeFile: _fs.writeFileSync, - deleteFile: function (path) { - try { - _fs.unlinkSync(path); - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - createFile: function (path, useUTF8) { - function mkdirRecursiveSync(path) { - var stats = _fs.statSync(path); - if (stats.isFile()) { - IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); - } else if (stats.isDirectory()) { + // console.log('changed:\n' + Object.keys(this.changed).join('\n')); + // console.log('removed:\n' + Object.keys(this.removed).join('\n')); + resolve(); + }); + }; + + FileIndex.prototype.parseFiles = function () { + var _this = this; + return this.loadReferences(this.files).then(function () { + return _this.getMissingReferences(); + }); + }; + + FileIndex.prototype.getMissingReferences = function () { + var _this = this; + return Promise.attempt(function () { + _this.missing = Object.create(null); + Lazy(_this.removed).keys().each(function (removed) { + if (removed in _this.refMap) { + _this.missing[removed] = _this.refMap[removed]; + } + }); + }); + }; + + FileIndex.prototype.loadReferences = function (files) { + var _this = this; + return new Promise(function (resolve, reject) { + var queue = files.slice(0); + var active = []; + var max = 50; + var next = function () { + if (queue.length === 0 && active.length === 0) { + resolve(); return; - } else { - mkdirRecursiveSync(_path.dirname(path)); - _fs.mkdirSync(path, 0775); } - } - mkdirRecursiveSync(_path.dirname(path)); - - try { - var fd = _fs.openSync(path, 'w'); - } catch (e) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); - } - return { - Write: function (str) { - _fs.writeSync(fd, str); - }, - WriteLine: function (str) { - _fs.writeSync(fd, str + '\r\n'); - }, - Close: function () { - _fs.closeSync(fd); - fd = null; + while (queue.length > 0 && active.length < max) { + var file = queue.pop(); + active.push(file); + _this.parseFile(file).then(function (file) { + active.splice(active.indexOf(file), 1); + next(); + }).catch(function (err) { + queue = []; + active = []; + reject(err); + }); } }; - }, - dir: function dir(path, spec, options) { - options = options || {}; + next(); + }).then(function () { + // bake reverse reference map (referenced to referrers) + _this.refMap = Object.create(null); - function filesInFolder(folder, deep) { - var paths = []; - - var files = _fs.readdirSync(folder); - for (var i = 0; i < files.length; i++) { - var stat = _fs.statSync(folder + "/" + files[i]); - if (options.recursive && stat.isDirectory()) { - if (deep < (options.deep || 100)) { - paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); - } - } else if (stat.isFile() && (!spec || files[i].match(spec))) { - paths.push(folder + "/" + files[i]); - } - } - - return paths; - } - - return filesInFolder(path, 0); - }, - createDirectory: function (path) { - try { - if (!this.directoryExists(path)) { - _fs.mkdirSync(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); - }, - resolvePath: function (path) { - return _path.resolve(path); - }, - dirName: function (path) { - return _path.dirname(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = rootPath + "/" + partialFilePath; - - while (true) { - if (_fs.existsSync(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } catch (err) { - //Tools.CompilerDiagnostics.debugPrint(("Could not find " + path) + ", trying parent"); - } - } else { - var parentPath = _path.resolve(rootPath, ".."); - - if (rootPath === parentPath) { - return null; + Lazy(files).each(function (file) { + Lazy(file.references).each(function (ref) { + if (ref.fullPath in _this.refMap) { + _this.refMap[ref.fullPath].push(file); } else { - rootPath = parentPath; - path = _path.resolve(rootPath, partialFilePath); + _this.refMap[ref.fullPath] = [file]; } - } - } - }, - print: function (str) { - process.stdout.write(str); - }, - printLine: function (str) { - process.stdout.write(str + '\n'); - }, - arguments: process.argv.slice(2), - stderr: { - Write: function (str) { - process.stderr.write(str); - }, - WriteLine: function (str) { - process.stderr.write(str + '\n'); - }, - Close: function () { - } - }, - stdout: { - Write: function (str) { - process.stdout.write(str); - }, - WriteLine: function (str) { - process.stdout.write(str + '\n'); - }, - Close: function () { - } - }, - watchFile: function (filename, callback) { - var firstRun = true; - var processingChange = false; - - var fileChanged = function (curr, prev) { - if (!firstRun) { - if (curr.mtime < prev.mtime) { - return; - } - - _fs.unwatchFile(filename, fileChanged); - if (!processingChange) { - processingChange = true; - callback(filename); - setTimeout(function () { - processingChange = false; - }, 100); - } - } - firstRun = false; - _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); - }; - - fileChanged(); - return { - filename: filename, - close: function () { - _fs.unwatchFile(filename, fileChanged); - } - }; - }, - run: function (source, filename) { - require.main.filename = filename; - require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); - require.main._compile(source, filename); - }, - getExecutingFilePath: function () { - return process.mainModule.filename; - }, - quit: process.exit + }); + }); + }); }; - } - ; - if (typeof ActiveXObject === "function") - return getWindowsScriptHostIO(); -else if (typeof require === "function") - return getNodeIO(); -else - return null; -})(); + // TODO replace with a stream? + FileIndex.prototype.parseFile = function (file) { + var _this = this; + return readFile(file.filePathWithName, { + encoding: 'utf8', + flag: 'r' + }).then(function (content) { + file.references = Lazy(DT.extractReferenceTags(content)).map(function (ref) { + return path.resolve(path.dirname(file.fullPath), ref); + }).reduce(function (memo, ref) { + if (ref in _this.fileMap) { + memo.push(_this.fileMap[ref]); + } else { + console.log('not mapped? -> ' + ref); + } + return memo; + }, []); + + // return the object + return file; + }); + }; + + FileIndex.prototype.collectTargets = function () { + var _this = this; + return new Promise(function (resolve) { + // map out files linked to changes + // - queue holds files touched by a change + // - pre-fill with actually changed files + // - loop queue, if current not seen: + // - add to result + // - from refMap queue all files referring to current + var result = Object.create(null); + var queue = Lazy(_this.changed).values().toArray(); + + while (queue.length > 0) { + var next = queue.shift(); + var fp = next.fullPath; + if (result[fp]) { + continue; + } + result[fp] = next; + if (fp in _this.refMap) { + var arr = _this.refMap[fp]; + for (var i = 0, ii = arr.length; i < ii; i++) { + // just add it and skip expensive checks + queue.push(arr[i]); + } + } + } + resolve(Lazy(result).values().toArray()); + }); + }; + return FileIndex; + })(); + DT.FileIndex = FileIndex; +})(DT || (DT = {})); +/// +/// +var DT; +(function (DT) { + 'use strict'; + + var fs = require('fs'); + var path = require('path'); + var Git = require('git-wrapper'); + var Promise = require('bluebird'); + + var GitChanges = (function () { + function GitChanges(runner) { + this.runner = runner; + this.options = {}; + var dir = path.join(this.runner.dtPath, '.git'); + if (!fs.existsSync(dir)) { + throw new Error('cannot locate git-dir: ' + dir); + } + this.options['git-dir'] = dir; + + this.git = new Git(this.options); + this.git.exec = Promise.promisify(this.git.exec); + } + GitChanges.prototype.readChanges = function () { + var opts = {}; + var args = ['--name-only HEAD~1']; + return this.git.exec('diff', opts, args).then(function (msg) { + return msg.replace(/^\s+/, '').replace(/\s+$/, '').split(/\r?\n/g); + }); + }; + return GitChanges; + })(); + DT.GitChanges = GitChanges; +})(DT || (DT = {})); +/// +/// +var DT; +(function (DT) { + var os = require('os'); + + ///////////////////////////////// + // All the common things that we print are functions of this class + ///////////////////////////////// + var Print = (function () { + function Print(version) { + this.version = version; + this.WIDTH = 77; + } + Print.prototype.init = function (typings, tests, tsFiles) { + this.typings = typings; + this.tests = tests; + this.tsFiles = tsFiles; + }; + + Print.prototype.out = function (s) { + process.stdout.write(s); + return this; + }; + + Print.prototype.repeat = function (s, times) { + return new Array(times + 1).join(s); + }; + + Print.prototype.printChangeHeader = function () { + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mDefinitelyTyped Diff Detector 0.1.0\33[0m \n'); + this.out('=============================================================================\n'); + }; + + Print.prototype.printHeader = function (options) { + var totalMem = Math.round(os.totalmem() / 1024 / 1024) + ' mb'; + var freemem = Math.round(os.freemem() / 1024 / 1024) + ' mb'; + + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mDefinitelyTyped Test Runner 0.5.0\33[0m\n'); + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); + this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); + this.out(' \33[36m\33[1mTests :\33[0m ' + this.tests + '\n'); + this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); + this.out(' \33[36m\33[1mTotal Memory :\33[0m ' + totalMem + '\n'); + this.out(' \33[36m\33[1mFree Memory :\33[0m ' + freemem + '\n'); + this.out(' \33[36m\33[1mCores :\33[0m ' + os.cpus().length + '\n'); + this.out(' \33[36m\33[1mConcurrent :\33[0m ' + options.concurrent + '\n'); + }; + + Print.prototype.printSuiteHeader = function (title) { + var left = Math.floor((this.WIDTH - title.length) / 2) - 1; + var right = Math.ceil((this.WIDTH - title.length) / 2) - 1; + this.out(this.repeat('=', left)).out(' \33[34m\33[1m'); + this.out(title); + this.out('\33[0m ').out(this.repeat('=', right)).printBreak(); + }; + + Print.prototype.printDiv = function () { + this.out('-----------------------------------------------------------------------------\n'); + }; + + Print.prototype.printBoldDiv = function () { + this.out('=============================================================================\n'); + }; + + Print.prototype.printErrorsHeader = function () { + this.out('=============================================================================\n'); + this.out(' \33[34m\33[1mErrors in files\33[0m \n'); + this.out('=============================================================================\n'); + }; + + Print.prototype.printErrorsForFile = function (testResult) { + this.out('----------------- For file:' + testResult.targetFile.filePathWithName); + this.printBreak().out(testResult.stderr).printBreak(); + }; + + Print.prototype.printBreak = function () { + this.out('\n'); + return this; + }; + + Print.prototype.clearCurrentLine = function () { + this.out('\r\33[K'); + return this; + }; + + Print.prototype.printSuccessCount = function (current, total) { + var arb = (total === 0) ? 0 : (current / total); + this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printFailedCount = function (current, total) { + var arb = (total === 0) ? 0 : (current / total); + this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printTypingsWithoutTestsMessage = function () { + this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); + }; + + Print.prototype.printTotalMessage = function () { + this.out(' \33[36m\33[1mTotal\33[0m\n'); + }; + + Print.prototype.printElapsedTime = function (time, s) { + this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); + }; + + Print.prototype.printSuiteErrorCount = function (errorHeadline, current, total, warn) { + if (typeof warn === "undefined") { warn = false; } + var arb = (total === 0) ? 0 : (current / total); + this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length)); + if (warn) { + this.out(': \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } else { + this.out(': \33[33m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + }; + + Print.prototype.printSubHeader = function (file) { + this.out(' \33[36m\33[1m' + file + '\33[0m\n'); + }; + + Print.prototype.printWarnCode = function (str) { + this.out(' \33[31m\33[1m<' + str.toLowerCase().replace(/ +/g, '-') + '>\33[0m\n'); + }; + + Print.prototype.printLine = function (file) { + this.out(file + '\n'); + }; + + Print.prototype.printElement = function (file) { + this.out(' - ' + file + '\n'); + }; + + Print.prototype.printElement2 = function (file) { + this.out(' - ' + file + '\n'); + }; + + Print.prototype.printTypingsWithoutTestName = function (file) { + this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); + }; + + Print.prototype.printTypingsWithoutTest = function (withoutTestTypings) { + var _this = this; + if (withoutTestTypings.length > 0) { + this.printTypingsWithoutTestsMessage(); + + this.printDiv(); + withoutTestTypings.forEach(function (t) { + _this.printTypingsWithoutTestName(t); + }); + } + }; + + Print.prototype.printTestComplete = function (testResult) { + var reporter = testResult.hostedBy.testReporter; + if (testResult.success) { + reporter.printPositiveCharacter(testResult); + } else { + reporter.printNegativeCharacter(testResult); + } + }; + + Print.prototype.printSuiteComplete = function (suite) { + this.printBreak(); + + this.printDiv(); + this.printElapsedTime(suite.timer.asString, suite.timer.time); + this.printSuccessCount(suite.okTests.length, suite.testResults.length); + this.printFailedCount(suite.ngTests.length, suite.testResults.length); + }; + + Print.prototype.printTests = function (adding) { + var _this = this; + this.printDiv(); + this.printSubHeader('Testing'); + this.printDiv(); + + Object.keys(adding).sort().map(function (src) { + _this.printLine(adding[src].filePathWithName); + return adding[src]; + }); + }; + + Print.prototype.printQueue = function (files) { + var _this = this; + this.printDiv(); + this.printSubHeader('Queued for testing'); + this.printDiv(); + + files.forEach(function (file) { + _this.printLine(file.filePathWithName); + }); + }; + + Print.prototype.printTestAll = function () { + this.printDiv(); + this.printSubHeader('Ignoring changes, testing all files'); + }; + + Print.prototype.printFiles = function (files) { + var _this = this; + this.printDiv(); + this.printSubHeader('Files'); + this.printDiv(); + + files.forEach(function (file) { + _this.printLine(file.filePathWithName); + file.references.forEach(function (file) { + _this.printElement(file.filePathWithName); + }); + }); + }; + + Print.prototype.printMissing = function (index, refMap) { + var _this = this; + this.printDiv(); + this.printSubHeader('Missing references'); + this.printDiv(); + + Object.keys(refMap).sort().forEach(function (src) { + var ref = index.getFile(src); + _this.printLine('\33[31m\33[1m' + ref.filePathWithName + '\33[0m'); + refMap[src].forEach(function (file) { + _this.printElement(file.filePathWithName); + }); + }); + }; + + Print.prototype.printAllChanges = function (paths) { + var _this = this; + this.printSubHeader('All changes'); + this.printDiv(); + + paths.sort().forEach(function (line) { + _this.printLine(line); + }); + }; + + Print.prototype.printRelChanges = function (changeMap) { + var _this = this; + this.printDiv(); + this.printSubHeader('Interesting files'); + this.printDiv(); + + Object.keys(changeMap).sort().forEach(function (src) { + _this.printLine(changeMap[src].filePathWithName); + }); + }; + + Print.prototype.printRemovals = function (changeMap) { + var _this = this; + this.printDiv(); + this.printSubHeader('Removed files'); + this.printDiv(); + + Object.keys(changeMap).sort().forEach(function (src) { + _this.printLine(changeMap[src].filePathWithName); + }); + }; + + Print.prototype.printRefMap = function (index, refMap) { + var _this = this; + this.printDiv(); + this.printSubHeader('Referring'); + this.printDiv(); + + Object.keys(refMap).sort().forEach(function (src) { + var ref = index.getFile(src); + _this.printLine(ref.filePathWithName); + refMap[src].forEach(function (file) { + _this.printLine(' - ' + file.filePathWithName); + }); + }); + }; + return Print; + })(); + DT.Print = Print; +})(DT || (DT = {})); +/// +/// +var DT; +(function (DT) { + + + ///////////////////////////////// + // Default test reporter + ///////////////////////////////// + var DefaultTestReporter = (function () { + function DefaultTestReporter(print) { + this.print = print; + this.index = 0; + } + DefaultTestReporter.prototype.printPositiveCharacter = function (testResult) { + this.print.out('\33[36m\33[1m' + '.' + '\33[0m'); + this.index++; + this.printBreakIfNeeded(this.index); + }; + + DefaultTestReporter.prototype.printNegativeCharacter = function (testResult) { + this.print.out('x'); + this.index++; + this.printBreakIfNeeded(this.index); + }; + + DefaultTestReporter.prototype.printBreakIfNeeded = function (index) { + if (index % this.print.WIDTH === 0) { + this.print.printBreak(); + } + }; + return DefaultTestReporter; + })(); + DT.DefaultTestReporter = DefaultTestReporter; +})(DT || (DT = {})); +/// +var DT; +(function (DT) { + 'use strict'; + + var Promise = require('bluebird'); + + + + ///////////////////////////////// + // Base class for test suite + ///////////////////////////////// + var TestSuiteBase = (function () { + function TestSuiteBase(options, testSuiteName, errorHeadline) { + this.options = options; + this.testSuiteName = testSuiteName; + this.errorHeadline = errorHeadline; + this.timer = new DT.Timer(); + this.testResults = []; + this.printErrorCount = true; + this.queue = new DT.TestQueue(options.concurrent); + } + TestSuiteBase.prototype.filterTargetFiles = function (files) { + throw new Error('please implement this method'); + }; + + TestSuiteBase.prototype.start = function (targetFiles, testCallback) { + var _this = this; + this.timer.start(); + + return this.filterTargetFiles(targetFiles).then(function (targetFiles) { + // tests get queued for multi-threading + return Promise.all(targetFiles.map(function (targetFile) { + return _this.runTest(targetFile).then(function (result) { + testCallback(result); + }); + })); + }).then(function () { + _this.timer.end(); + return _this; + }); + }; + + TestSuiteBase.prototype.runTest = function (targetFile) { + var _this = this; + return this.queue.run(new DT.Test(this, targetFile, { + tscVersion: this.options.tscVersion + })).then(function (result) { + _this.testResults.push(result); + return result; + }); + }; + + Object.defineProperty(TestSuiteBase.prototype, "okTests", { + get: function () { + return this.testResults.filter(function (r) { + return r.success; + }); + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(TestSuiteBase.prototype, "ngTests", { + get: function () { + return this.testResults.filter(function (r) { + return !r.success; + }); + }, + enumerable: true, + configurable: true + }); + return TestSuiteBase; + })(); + DT.TestSuiteBase = TestSuiteBase; +})(DT || (DT = {})); +/// +/// var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; -var DefinitelyTyped; -(function (DefinitelyTyped) { - /// - /// - /// - (function (TestManager) { - var path = require('path'); +var DT; +(function (DT) { + 'use strict'; - TestManager.DEFAULT_TSC_VERSION = "0.9.1.1"; + var Promise = require('bluebird'); - function endsWith(str, suffix) { - return str.indexOf(suffix, str.length - suffix.length) !== -1; + var endDts = /\w\.ts$/i; + + ///////////////////////////////// + // .d.ts syntax inspection + ///////////////////////////////// + var SyntaxChecking = (function (_super) { + __extends(SyntaxChecking, _super); + function SyntaxChecking(options) { + _super.call(this, options, 'Syntax checking', 'Syntax error'); } + SyntaxChecking.prototype.filterTargetFiles = function (files) { + return Promise.cast(files.filter(function (file) { + return endDts.test(file.filePathWithName); + })); + }; + return SyntaxChecking; + })(DT.TestSuiteBase); + DT.SyntaxChecking = SyntaxChecking; +})(DT || (DT = {})); +/// +/// +var DT; +(function (DT) { + 'use strict'; - var Tsc = (function () { - function Tsc() { - } - Tsc.run = function (tsfile, options, callback) { - options = options || {}; - options.tscVersion = options.tscVersion || TestManager.DEFAULT_TSC_VERSION; - if (typeof options.checkNoImplicitAny === "undefined") { - options.checkNoImplicitAny = true; - } - if (typeof options.useTscParams === "undefined") { - options.useTscParams = true; - } + var Promise = require('bluebird'); - if (!IO.fileExists(tsfile)) { - throw new Error(tsfile + " not exists"); - } + var endTestDts = /\w-tests?\.ts$/i; - var tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js'; - if (!IO.fileExists(tscPath)) { - throw new Error(tscPath + ' is not exists'); - } - var command = 'node ' + tscPath + ' --module commonjs '; - if (options.useTscParams && IO.fileExists(tsfile + '.tscparams')) { - command += '@' + tsfile + '.tscparams'; - } else if (options.checkNoImplicitAny) { - command += '--noImplicitAny'; - } - Exec.exec(command, [tsfile], function (execResult) { - callback(execResult); - }); - }; - return Tsc; - })(); + ///////////////////////////////// + // Compile with *-tests.ts + ///////////////////////////////// + var TestEval = (function (_super) { + __extends(TestEval, _super); + function TestEval(options) { + _super.call(this, options, 'Typing tests', 'Failed tests'); + } + TestEval.prototype.filterTargetFiles = function (files) { + return Promise.cast(files.filter(function (file) { + return endTestDts.test(file.filePathWithName); + })); + }; + return TestEval; + })(DT.TestSuiteBase); + DT.TestEval = TestEval; +})(DT || (DT = {})); +/// +/// +var DT; +(function (DT) { + 'use strict'; - var Test = (function () { - function Test(suite, tsfile, options) { - this.suite = suite; - this.tsfile = tsfile; - this.options = options; - } - Test.prototype.run = function (callback) { - var _this = this; - Tsc.run(this.tsfile.filePathWithName, this.options, function (execResult) { - var testResult = new TestResult(); - testResult.hostedBy = _this.suite; - testResult.targetFile = _this.tsfile; - testResult.options = _this.options; + var fs = require('fs'); + var Promise = require('bluebird'); - testResult.stdout = execResult.stdout; - testResult.stderr = execResult.stderr; - testResult.exitCode = execResult.exitCode; + ///////////////////////////////// + // Try compile without .tscparams + // It may indicate that it is compatible with --noImplicitAny maybe... + ///////////////////////////////// + var FindNotRequiredTscparams = (function (_super) { + __extends(FindNotRequiredTscparams, _super); + function FindNotRequiredTscparams(options, print) { + var _this = this; + _super.call(this, options, 'Find not required .tscparams files', 'New arrival!'); + this.print = print; + this.printErrorCount = false; - callback(testResult); - }); - }; - return Test; - })(); - - ///////////////////////////////// - // Timer.start starts a timer - // Timer.end stops the timer and sets asString to the pretty print value - ///////////////////////////////// - var Timer = (function () { - function Timer() { - this.time = 0; - } - Timer.prototype.start = function () { - this.time = 0; - this.startTime = this.now(); - }; - - Timer.prototype.now = function () { - return Date.now(); - }; - - Timer.prototype.end = function () { - this.time = (this.now() - this.startTime) / 1000; - this.asString = Timer.prettyDate(this.startTime, this.now()); - }; - - Timer.prettyDate = function (date1, date2) { - var diff = ((date2 - date1) / 1000), day_diff = Math.floor(diff / 86400); - - if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) - return; - - return (day_diff == 0 && (diff < 60 && (diff + " seconds") || diff < 120 && "1 minute" || diff < 3600 && Math.floor(diff / 60) + " minutes" || diff < 7200 && "1 hour" || diff < 86400 && Math.floor(diff / 3600) + " hours") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks"); - }; - return Timer; - })(); - TestManager.Timer = Timer; - - ///////////////////////////////// - // Given a document root + ts file pattern this class returns: - // all the TS files OR just tests OR just definition files - ///////////////////////////////// - var File = (function () { - function File(baseDir, filePathWithName) { - this.baseDir = baseDir; - this.filePathWithName = filePathWithName; - var dirName = path.dirname(this.filePathWithName.substr(this.baseDir.length + 1)).replace('\\', '/'); - this.dir = dirName.split('/')[0]; - this.file = path.basename(this.filePathWithName, '.ts'); - this.ext = path.extname(this.filePathWithName); - } - Object.defineProperty(File.prototype, "formatName", { - get: // From '/complete/path/to/file' to 'specfolder/specfile.d.ts' - function () { - var dirName = path.dirname(this.filePathWithName.substr(this.baseDir.length + 1)).replace('\\', '/'); - return this.dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + this.file + this.ext; + this.testReporter = { + printPositiveCharacter: function (testResult) { + _this.print.clearCurrentLine().printTypingsWithoutTestName(testResult.targetFile.filePathWithName); }, - enumerable: true, - configurable: true - }); - return File; - })(); - TestManager.File = File; - - ///////////////////////////////// - // Test results - ///////////////////////////////// - var TestResult = (function () { - function TestResult() { - } - Object.defineProperty(TestResult.prototype, "success", { - get: function () { - return this.exitCode === 0; - }, - enumerable: true, - configurable: true - }); - return TestResult; - })(); - TestManager.TestResult = TestResult; - - ///////////////////////////////// - // Default test reporter - ///////////////////////////////// - var DefaultTestReporter = (function () { - function DefaultTestReporter(print) { - this.print = print; - } - DefaultTestReporter.prototype.printPositiveCharacter = function (index, testResult) { - this.print.out('\33[36m\33[1m' + '.' + '\33[0m'); - - this.printBreakIfNeeded(index); - }; - - DefaultTestReporter.prototype.printNegativeCharacter = function (index, testResult) { - this.print.out("x"); - - this.printBreakIfNeeded(index); - }; - - DefaultTestReporter.prototype.printBreakIfNeeded = function (index) { - if (index % this.print.WIDTH === 0) { - this.print.printBreak(); + printNegativeCharacter: function (testResult) { } }; - return DefaultTestReporter; - })(); + } + FindNotRequiredTscparams.prototype.filterTargetFiles = function (files) { + return Promise.filter(files, function (file) { + return new Promise(function (resolve) { + fs.exists(file.filePathWithName + '.tscparams', resolve); + }); + }); + }; - ///////////////////////////////// - // All the common things that we pring are functions of this class - ///////////////////////////////// - var Print = (function () { - function Print(version, typings, tests, tsFiles) { - this.version = version; - this.typings = typings; - this.tests = tests; - this.tsFiles = tsFiles; - this.WIDTH = 77; - } - Print.prototype.out = function (s) { - process.stdout.write(s); - return this; - }; + FindNotRequiredTscparams.prototype.runTest = function (targetFile) { + var _this = this; + this.print.clearCurrentLine().out(targetFile.filePathWithName); - Print.prototype.repeat = function (s, times) { - return new Array(times + 1).join(s); - }; + return this.queue.run(new DT.Test(this, targetFile, { + tscVersion: this.options.tscVersion, + useTscParams: false, + checkNoImplicitAny: true + })).then(function (result) { + _this.testResults.push(result); + _this.print.clearCurrentLine(); + return result; + }); + }; - Print.prototype.printHeader = function () { - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.4.0\33[0m\n'); - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); - this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); - this.out(' \33[36m\33[1mTests :\33[0m ' + this.tests + '\n'); - this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); - }; + Object.defineProperty(FindNotRequiredTscparams.prototype, "ngTests", { + get: function () { + // Do not show ng test results + return []; + }, + enumerable: true, + configurable: true + }); + return FindNotRequiredTscparams; + })(DT.TestSuiteBase); + DT.FindNotRequiredTscparams = FindNotRequiredTscparams; +})(DT || (DT = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +var DT; +(function (DT) { + require('source-map-support').install(); - Print.prototype.printSuiteHeader = function (title) { - var left = Math.floor((this.WIDTH - title.length) / 2) - 1; - var right = Math.ceil((this.WIDTH - title.length) / 2) - 1; - this.out(this.repeat("=", left)).out(" \33[34m\33[1m"); - this.out(title); - this.out("\33[0m ").out(this.repeat("=", right)).printBreak(); - }; + // hacky typing + var Lazy = require('lazy.js'); + var Promise = require('bluebird'); - Print.prototype.printDiv = function () { - this.out('-----------------------------------------------------------------------------\n'); - }; + var os = require('os'); + var fs = require('fs'); + var path = require('path'); + var assert = require('assert'); - Print.prototype.printBoldDiv = function () { - this.out('=============================================================================\n'); - }; + var tsExp = /\.ts$/; - Print.prototype.printErrorsHeader = function () { - this.out('=============================================================================\n'); - this.out(' \33[34m\33[1mErrors in files\33[0m \n'); - this.out('=============================================================================\n'); - }; + DT.DEFAULT_TSC_VERSION = '0.9.7'; - Print.prototype.printErrorsForFile = function (testResult) { - this.out('----------------- For file:' + testResult.targetFile.formatName); - this.printBreak().out(testResult.stderr).printBreak(); - }; + ///////////////////////////////// + // Single test + ///////////////////////////////// + var Test = (function () { + function Test(suite, tsfile, options) { + this.suite = suite; + this.tsfile = tsfile; + this.options = options; + } + Test.prototype.run = function () { + var _this = this; + return DT.Tsc.run(this.tsfile.filePathWithName, this.options).then(function (execResult) { + var testResult = new TestResult(); + testResult.hostedBy = _this.suite; + testResult.targetFile = _this.tsfile; + testResult.options = _this.options; - Print.prototype.printBreak = function () { - this.out('\n'); - return this; - }; + testResult.stdout = execResult.stdout; + testResult.stderr = execResult.stderr; + testResult.exitCode = execResult.exitCode; - Print.prototype.clearCurrentLine = function () { - this.out("\r\33[K"); - return this; - }; + return testResult; + }); + }; + return Test; + })(); + DT.Test = Test; - Print.prototype.printSuccessCount = function (current, total) { - this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - }; + ///////////////////////////////// + // Parallel execute Tests + ///////////////////////////////// + var TestQueue = (function () { + function TestQueue(concurrent) { + this.queue = []; + this.active = []; + this.concurrent = Math.max(1, concurrent); + } + // add to queue and return a promise + TestQueue.prototype.run = function (test) { + var _this = this; + var defer = Promise.defer(); - Print.prototype.printFailedCount = function (current, total) { - this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - }; + // add a closure to queue + this.queue.push(function () { + // when activate, add test to active list + _this.active.push(test); - Print.prototype.printTypingsWithoutTestsMessage = function () { - this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); - }; - - Print.prototype.printTotalMessage = function () { - this.out(' \33[36m\33[1mTotal\33[0m\n'); - }; - - Print.prototype.printElapsedTime = function (time, s) { - this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); - }; - - Print.prototype.printSuiteErrorCount = function (errorHeadline, current, total, valuesColor) { - if (typeof valuesColor === "undefined") { valuesColor = '\33[31m\33[1m'; } - this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length)); - this.out(':\33[0m ' + valuesColor + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - }; - - Print.prototype.printTypingsWithoutTestName = function (file) { - this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); - }; - - Print.prototype.printTypingsWithoutTest = function (withoutTestTypings) { - var _this = this; - if (withoutTestTypings.length > 0) { - this.printTypingsWithoutTestsMessage(); - - this.printDiv(); - withoutTestTypings.forEach(function (t) { - _this.printTypingsWithoutTestName(t); - }); - } - }; - return Print; - })(); - - ///////////////////////////////// - // Base class for test suite - ///////////////////////////////// - var TestSuiteBase = (function () { - function TestSuiteBase(options, testSuiteName, errorHeadline) { - this.options = options; - this.testSuiteName = testSuiteName; - this.errorHeadline = errorHeadline; - this.timer = new Timer(); - this.testResults = []; - this.printErrorCount = true; - } - TestSuiteBase.prototype.filterTargetFiles = function (files) { - throw new Error("please implement this method"); - }; - - TestSuiteBase.prototype.start = function (targetFiles, testCallback, suiteCallback) { - var _this = this; - targetFiles = this.filterTargetFiles(targetFiles); - this.timer.start(); - var count = 0; - - // exec test is async process. serialize. - var executor = function () { - var targetFile = targetFiles[count]; - if (targetFile) { - _this.runTest(targetFile, function (result) { - testCallback(result, count + 1); - count++; - executor(); - }); - } else { - _this.timer.end(); - _this.finish(suiteCallback); + // run it + var p = test.run(); + p.then(defer.resolve.bind(defer), defer.reject.bind(defer)); + p.finally(function () { + var i = _this.active.indexOf(test); + if (i > -1) { + _this.active.splice(i, 1); } - }; - executor(); - }; - - TestSuiteBase.prototype.runTest = function (targetFile, callback) { - var _this = this; - new Test(this, targetFile, { tscVersion: this.options.tscVersion }).run(function (result) { - _this.testResults.push(result); - callback(result); + _this.step(); }); - }; - - TestSuiteBase.prototype.finish = function (suiteCallback) { - suiteCallback(this); - }; - - Object.defineProperty(TestSuiteBase.prototype, "okTests", { - get: function () { - return this.testResults.filter(function (r) { - return r.success; - }); - }, - enumerable: true, - configurable: true }); + this.step(); - Object.defineProperty(TestSuiteBase.prototype, "ngTests", { - get: function () { - return this.testResults.filter(function (r) { - return !r.success; - }); - }, - enumerable: true, - configurable: true - }); - return TestSuiteBase; - })(); + // defer it + return defer.promise; + }; - ///////////////////////////////// - // .d.ts syntax inspection - ///////////////////////////////// - var SyntaxChecking = (function (_super) { - __extends(SyntaxChecking, _super); - function SyntaxChecking(options) { - _super.call(this, options, "Syntax checking", "Syntax error"); - } - SyntaxChecking.prototype.filterTargetFiles = function (files) { - return files.filter(function (file) { - return endsWith(file.formatName.toUpperCase(), '.D.TS'); - }); - }; - return SyntaxChecking; - })(TestSuiteBase); - - ///////////////////////////////// - // Compile with *-tests.ts - ///////////////////////////////// - var TestEval = (function (_super) { - __extends(TestEval, _super); - function TestEval(options) { - _super.call(this, options, "Typing tests", "Failed tests"); - } - TestEval.prototype.filterTargetFiles = function (files) { - return files.filter(function (file) { - return endsWith(file.formatName.toUpperCase(), '-TESTS.TS'); - }); - }; - return TestEval; - })(TestSuiteBase); - - ///////////////////////////////// - // Try compile without .tscparams - // It may indicate that it is compatible with --noImplicitAny maybe... - ///////////////////////////////// - var FindNotRequiredTscparams = (function (_super) { - __extends(FindNotRequiredTscparams, _super); - function FindNotRequiredTscparams(options, print) { - var _this = this; - _super.call(this, options, "Find not required .tscparams files", "New arrival!"); - this.print = print; - this.printErrorCount = false; - - this.testReporter = { - printPositiveCharacter: function (index, testResult) { - _this.print.clearCurrentLine().printTypingsWithoutTestName(testResult.targetFile.formatName); - }, - printNegativeCharacter: function (index, testResult) { - } - }; - } - FindNotRequiredTscparams.prototype.filterTargetFiles = function (files) { - return files.filter(function (file) { - return IO.fileExists(file.filePathWithName + '.tscparams'); - }); - }; - - FindNotRequiredTscparams.prototype.runTest = function (targetFile, callback) { - var _this = this; - this.print.clearCurrentLine().out(targetFile.formatName); - new Test(this, targetFile, { tscVersion: this.options.tscVersion, useTscParams: false, checkNoImplicitAny: true }).run(function (result) { - _this.testResults.push(result); - callback(result); - }); - }; - - FindNotRequiredTscparams.prototype.finish = function (suiteCallback) { - this.print.clearCurrentLine(); - suiteCallback(this); - }; - - Object.defineProperty(FindNotRequiredTscparams.prototype, "ngTests", { - get: function () { - // Do not show ng test results - return []; - }, - enumerable: true, - configurable: true - }); - return FindNotRequiredTscparams; - })(TestSuiteBase); - - ///////////////////////////////// - // The main class to kick things off - ///////////////////////////////// - var TestRunner = (function () { - function TestRunner(dtPath, options) { - if (typeof options === "undefined") { options = { tscVersion: TestManager.DEFAULT_TSC_VERSION }; } - this.options = options; - this.suites = []; - this.options.findNotRequiredTscparams = !!this.options.findNotRequiredTscparams; - - var filesName = IO.dir(dtPath, /.\.ts/g, { recursive: true }).sort(); - - // only includes .d.ts or -tests.ts or -test.ts or .ts - filesName = filesName.filter(function (fileName) { - return fileName.indexOf('../_infrastructure') < 0; - }).filter(function (fileName) { - return !endsWith(fileName, ".tscparams"); - }); - this.files = filesName.map(function (fileName) { - return new File(dtPath, fileName); - }); - } - TestRunner.prototype.addSuite = function (suite) { - this.suites.push(suite); - }; - - TestRunner.prototype.run = function () { - var _this = this; - this.timer = new Timer(); - this.timer.start(); - - var syntaxChecking = new SyntaxChecking(this.options); - var testEval = new TestEval(this.options); - if (!this.options.findNotRequiredTscparams) { - this.addSuite(syntaxChecking); - this.addSuite(testEval); + TestQueue.prototype.step = function () { + var _this = this; + // setTimeout to make it flush + setTimeout(function () { + while (_this.queue.length > 0 && _this.active.length < _this.concurrent) { + _this.queue.pop().call(null); } + }, 1); + }; + return TestQueue; + })(); + DT.TestQueue = TestQueue; - var typings = syntaxChecking.filterTargetFiles(this.files).length; - var testFiles = testEval.filterTargetFiles(this.files).length; - this.print = new Print(this.options.tscVersion, typings, testFiles, this.files.length); - this.print.printHeader(); + ///////////////////////////////// + // Test results + ///////////////////////////////// + var TestResult = (function () { + function TestResult() { + } + Object.defineProperty(TestResult.prototype, "success", { + get: function () { + return this.exitCode === 0; + }, + enumerable: true, + configurable: true + }); + return TestResult; + })(); + DT.TestResult = TestResult; - if (this.options.findNotRequiredTscparams) { - this.addSuite(new FindNotRequiredTscparams(this.options, this.print)); + ///////////////////////////////// + // The main class to kick things off + ///////////////////////////////// + var TestRunner = (function () { + function TestRunner(dtPath, options) { + if (typeof options === "undefined") { options = { tscVersion: DT.DEFAULT_TSC_VERSION }; } + this.dtPath = dtPath; + this.options = options; + this.suites = []; + this.options.findNotRequiredTscparams = !!this.options.findNotRequiredTscparams; + + this.index = new DT.FileIndex(this, this.options); + this.changes = new DT.GitChanges(this); + + this.print = new DT.Print(this.options.tscVersion); + } + TestRunner.prototype.addSuite = function (suite) { + this.suites.push(suite); + }; + + TestRunner.prototype.checkAcceptFile = function (fileName) { + var ok = tsExp.test(fileName); + ok = ok && fileName.indexOf('_infrastructure') < 0; + ok = ok && fileName.indexOf('node_modules/') < 0; + ok = ok && /^[a-z]/i.test(fileName); + return ok; + }; + + TestRunner.prototype.run = function () { + var _this = this; + this.timer = new DT.Timer(); + this.timer.start(); + + this.print.printChangeHeader(); + + // only includes .d.ts or -tests.ts or -test.ts or .ts + return this.index.readIndex().then(function () { + return _this.changes.readChanges(); + }).then(function (changes) { + _this.print.printAllChanges(changes); + return _this.index.collectDiff(changes); + }).then(function () { + _this.print.printRemovals(_this.index.removed); + _this.print.printRelChanges(_this.index.changed); + return _this.index.parseFiles(); + }).then(function () { + if (_this.options.printRefMap) { + _this.print.printRefMap(_this.index, _this.index.refMap); } - - var count = 0; - var executor = function () { - var suite = _this.suites[count]; - if (suite) { - suite.testReporter = suite.testReporter || new DefaultTestReporter(_this.print); - - _this.print.printSuiteHeader(suite.testSuiteName); - var targetFiles = suite.filterTargetFiles(_this.files); - suite.start(targetFiles, function (testResult, index) { - _this.testCompleteCallback(testResult, index); - }, function (suite) { - _this.suiteCompleteCallback(suite); - count++; - executor(); - }); - } else { - _this.timer.end(); - _this.allTestCompleteCallback(); - } - }; - executor(); - }; - - TestRunner.prototype.testCompleteCallback = function (testResult, index) { - var reporter = testResult.hostedBy.testReporter; - if (testResult.success) { - reporter.printPositiveCharacter(index, testResult); - } else { - reporter.printNegativeCharacter(index, testResult); - } - }; - - TestRunner.prototype.suiteCompleteCallback = function (suite) { - this.print.printBreak(); - - this.print.printDiv(); - this.print.printElapsedTime(suite.timer.asString, suite.timer.time); - this.print.printSuccessCount(suite.okTests.length, suite.testResults.length); - this.print.printFailedCount(suite.ngTests.length, suite.testResults.length); - }; - - TestRunner.prototype.allTestCompleteCallback = function () { - var _this = this; - var testEval = this.suites.filter(function (suite) { - return suite instanceof TestEval; - })[0]; - if (testEval) { - var existsTestTypings = testEval.testResults.map(function (testResult) { - return testResult.targetFile.dir; - }).reduce(function (a, b) { - return a.indexOf(b) < 0 ? a.concat([b]) : a; - }, []); - var typings = this.files.map(function (file) { - return file.dir; - }).reduce(function (a, b) { - return a.indexOf(b) < 0 ? a.concat([b]) : a; - }, []); - var withoutTestTypings = typings.filter(function (typing) { - return existsTestTypings.indexOf(typing) < 0; - }); - this.print.printDiv(); - this.print.printTypingsWithoutTest(withoutTestTypings); - } - - this.print.printDiv(); - this.print.printTotalMessage(); - - this.print.printDiv(); - this.print.printElapsedTime(this.timer.asString, this.timer.time); - this.suites.filter(function (suite) { - return suite.printErrorCount; - }).forEach(function (suite) { - _this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length); - }); - if (testEval) { - this.print.printSuiteErrorCount("Without tests", withoutTestTypings.length, typings.length, '\33[33m\33[1m'); - } - - this.print.printDiv(); - if (this.suites.some(function (suite) { - return suite.ngTests.length !== 0; + if (Lazy(_this.index.missing).some(function (arr) { + return arr.length > 0; })) { - this.print.printErrorsHeader(); + _this.print.printMissing(_this.index, _this.index.missing); + _this.print.printBoldDiv(); - this.suites.filter(function (suite) { - return suite.ngTests.length !== 0; - }).forEach(function (suite) { - suite.ngTests.forEach(function (testResult) { - _this.print.printErrorsForFile(testResult); - }); - _this.print.printBoldDiv(); - }); - - process.exit(1); + // bail + return Promise.cast(false); } - }; - return TestRunner; - })(); - TestManager.TestRunner = TestRunner; - })(DefinitelyTyped.TestManager || (DefinitelyTyped.TestManager = {})); - var TestManager = DefinitelyTyped.TestManager; -})(DefinitelyTyped || (DefinitelyTyped = {})); + if (_this.options.printFiles) { + _this.print.printFiles(_this.index.files); + } + return _this.index.collectTargets().then(function (files) { + if (_this.options.testChanges) { + _this.print.printQueue(files); + return _this.runTests(files); + } else { + _this.print.printTestAll(); + return _this.runTests(_this.index.files); + } + }).then(function () { + return !_this.suites.some(function (suite) { + return suite.ngTests.length !== 0; + }); + }); + }); + }; -var dtPath = __dirname + '/../..'; -var findNotRequiredTscparams = process.argv.some(function (arg) { - return arg == "--try-without-tscparams"; -}); -var tscVersionIndex = process.argv.indexOf("--tsc-version"); -var tscVersion = DefinitelyTyped.TestManager.DEFAULT_TSC_VERSION; -if (-1 < tscVersionIndex) { - tscVersion = process.argv[tscVersionIndex + 1]; -} + TestRunner.prototype.runTests = function (files) { + var _this = this; + return Promise.attempt(function () { + assert(Array.isArray(files), 'files must be array'); -var runner = new DefinitelyTyped.TestManager.TestRunner(dtPath, { - tscVersion: tscVersion, - findNotRequiredTscparams: findNotRequiredTscparams -}); -runner.run(); + var syntaxChecking = new DT.SyntaxChecking(_this.options); + var testEval = new DT.TestEval(_this.options); + + if (!_this.options.findNotRequiredTscparams) { + _this.addSuite(syntaxChecking); + _this.addSuite(testEval); + } + + return Promise.all([ + syntaxChecking.filterTargetFiles(files), + testEval.filterTargetFiles(files) + ]); + }).spread(function (syntaxFiles, testFiles) { + _this.print.init(syntaxFiles.length, testFiles.length, files.length); + _this.print.printHeader(_this.options); + + if (_this.options.findNotRequiredTscparams) { + _this.addSuite(new DT.FindNotRequiredTscparams(_this.options, _this.print)); + } + + return Promise.reduce(_this.suites, function (count, suite) { + suite.testReporter = suite.testReporter || new DT.DefaultTestReporter(_this.print); + + _this.print.printSuiteHeader(suite.testSuiteName); + + if (_this.options.skipTests) { + _this.print.printWarnCode('skipped test'); + return Promise.cast(count++); + } + + return suite.start(files, function (testResult) { + _this.print.printTestComplete(testResult); + }).then(function (suite) { + _this.print.printSuiteComplete(suite); + return count++; + }); + }, 0); + }).then(function (count) { + _this.timer.end(); + _this.finaliseTests(files); + }); + }; + + TestRunner.prototype.finaliseTests = function (files) { + var _this = this; + var testEval = Lazy(this.suites).filter(function (suite) { + return suite instanceof DT.TestEval; + }).first(); + + if (testEval) { + var existsTestTypings = Lazy(testEval.testResults).map(function (testResult) { + return testResult.targetFile.dir; + }).reduce(function (a, b) { + return a.indexOf(b) < 0 ? a.concat([b]) : a; + }, []); + + var typings = Lazy(files).map(function (file) { + return file.dir; + }).reduce(function (a, b) { + return a.indexOf(b) < 0 ? a.concat([b]) : a; + }, []); + + var withoutTestTypings = typings.filter(function (typing) { + return existsTestTypings.indexOf(typing) < 0; + }); + + this.print.printDiv(); + this.print.printTypingsWithoutTest(withoutTestTypings); + } + + this.print.printDiv(); + this.print.printTotalMessage(); + + this.print.printDiv(); + this.print.printElapsedTime(this.timer.asString, this.timer.time); + + this.suites.filter(function (suite) { + return suite.printErrorCount; + }).forEach(function (suite) { + _this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length); + }); + if (testEval) { + this.print.printSuiteErrorCount('Without tests', withoutTestTypings.length, typings.length, true); + } + + this.print.printDiv(); + + if (this.suites.some(function (suite) { + return suite.ngTests.length !== 0; + })) { + this.print.printErrorsHeader(); + + this.suites.filter(function (suite) { + return suite.ngTests.length !== 0; + }).forEach(function (suite) { + suite.ngTests.forEach(function (testResult) { + _this.print.printErrorsForFile(testResult); + }); + _this.print.printBoldDiv(); + }); + } + }; + return TestRunner; + })(); + DT.TestRunner = TestRunner; + + var optimist = require('optimist')(process.argv); + optimist.default('try-without-tscparams', false); + optimist.default('single-thread', false); + optimist.default('tsc-version', DT.DEFAULT_TSC_VERSION); + + optimist.default('test-changes', false); + optimist.default('skip-tests', false); + optimist.default('print-files', false); + optimist.default('print-refmap', false); + + optimist.boolean('help'); + optimist.describe('help', 'print help'); + optimist.alias('h', 'help'); + + var argv = optimist.argv; + + var dtPath = path.resolve(path.dirname((module).filename), '..', '..'); + var cpuCores = os.cpus().length; + + if (argv.help) { + optimist.showHelp(); + process.exit(0); + } + + new TestRunner(dtPath, { + concurrent: argv['single-thread'] ? 1 : Math.max(cpuCores, 2), + tscVersion: argv['tsc-version'], + testChanges: argv['test-changes'], + skipTests: argv['skip-tests'], + printFiles: argv['print-files'], + printRefMap: argv['print-refmap'], + findNotRequiredTscparams: argv['try-without-tscparam'] + }).run().then(function (success) { + if (!success) { + process.exit(1); + } + }).catch(function (err) { + throw err; + process.exit(2); + }); +})(DT || (DT = {})); +//# sourceMappingURL=runner.js.map diff --git a/_infrastructure/tests/runner.ts b/_infrastructure/tests/runner.ts index f8746ab518..6e71d621a1 100644 --- a/_infrastructure/tests/runner.ts +++ b/_infrastructure/tests/runner.ts @@ -1,598 +1,358 @@ -/// - -/// -/// - -module DefinitelyTyped.TestManager { - var path = require('path'); - - export var DEFAULT_TSC_VERSION = "0.9.1.1"; - - function endsWith(str:string, suffix:string) { - return str.indexOf(suffix, str.length - suffix.length) !== -1; - } - - export interface TscExecOptions { - tscVersion?:string; - useTscParams?:boolean; - checkNoImplicitAny?:boolean; - } - - class Tsc { - public static run(tsfile:string, options:TscExecOptions, callback:(result:ExecResult)=>void) { - options = options || {}; - options.tscVersion = options.tscVersion || DEFAULT_TSC_VERSION; - if (typeof options.checkNoImplicitAny === "undefined") { - options.checkNoImplicitAny = true; - } - if (typeof options.useTscParams === "undefined") { - options.useTscParams = true; - } - - if (!IO.fileExists(tsfile)) { - throw new Error(tsfile + " not exists"); - } - - var tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js'; - if (!IO.fileExists(tscPath)) { - throw new Error(tscPath + ' is not exists'); - } - var command = 'node ' + tscPath + ' --module commonjs '; - if (options.useTscParams && IO.fileExists(tsfile + '.tscparams')) { - command += '@' + tsfile + '.tscparams'; - } else if (options.checkNoImplicitAny) { - command += '--noImplicitAny'; - } - Exec.exec(command, [tsfile], (execResult) => { - callback(execResult); - }); - } - } - - class Test { - constructor(public suite:ITestSuite, public tsfile:File, public options?:TscExecOptions) { - } - - public run(callback:(result:TestResult)=>void) { - Tsc.run(this.tsfile.filePathWithName, this.options, (execResult)=> { - var testResult = new TestResult(); - testResult.hostedBy = this.suite; - testResult.targetFile = this.tsfile; - testResult.options = this.options; - - testResult.stdout = execResult.stdout; - testResult.stderr = execResult.stderr; - testResult.exitCode = execResult.exitCode; - - callback(testResult); - }); - } - } - - ///////////////////////////////// - // Timer.start starts a timer - // Timer.end stops the timer and sets asString to the pretty print value - ///////////////////////////////// - export class Timer { - startTime:number; - time = 0; - asString:string; - - public start() { - this.time = 0; - this.startTime = this.now(); - } - - public now():number { - return Date.now(); - } - - public end() { - this.time = (this.now() - this.startTime) / 1000; - this.asString = Timer.prettyDate(this.startTime, this.now()); - } - - public static prettyDate(date1:number, date2:number):string { - var diff = ((date2 - date1) / 1000), - day_diff = Math.floor(diff / 86400); - - if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) - return; - - return (day_diff == 0 && ( - diff < 60 && (diff + " seconds") || - diff < 120 && "1 minute" || - diff < 3600 && Math.floor(diff / 60) + " minutes" || - diff < 7200 && "1 hour" || - diff < 86400 && Math.floor(diff / 3600) + " hours") || - day_diff == 1 && "Yesterday" || - day_diff < 7 && day_diff + " days" || - day_diff < 31 && Math.ceil(day_diff / 7) + " weeks"); - } - } - - ///////////////////////////////// - // Given a document root + ts file pattern this class returns: - // all the TS files OR just tests OR just definition files - ///////////////////////////////// - export class File { - dir:string; - file:string; - ext:string; - - constructor(public baseDir:string, public filePathWithName:string) { - var dirName = path.dirname(this.filePathWithName.substr(this.baseDir.length + 1)).replace('\\', '/'); - this.dir = dirName.split('/')[0]; - this.file = path.basename(this.filePathWithName, '.ts'); - this.ext = path.extname(this.filePathWithName); - } - - // From '/complete/path/to/file' to 'specfolder/specfile.d.ts' - public get formatName():string { - var dirName = path.dirname(this.filePathWithName.substr(this.baseDir.length + 1)).replace('\\', '/'); - return this.dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + this.file + this.ext; - } - } - - ///////////////////////////////// - // Test results - ///////////////////////////////// - export class TestResult { - hostedBy:ITestSuite; - targetFile:File; - options:TscExecOptions; - - stdout:string; - stderr:string; - exitCode:number; - - public get success():boolean { - return this.exitCode === 0; - } - } - - ///////////////////////////////// - // The interface for test suite - ///////////////////////////////// - export interface ITestSuite { - testSuiteName:string; - errorHeadline:string; - filterTargetFiles(files:File[]):File[]; - - start(targetFiles:File[], testCallback:(result:TestResult, index:number)=>void, suiteCallback:(suite:ITestSuite)=>void):void; - - testResults:TestResult[]; - okTests:TestResult[]; - ngTests:TestResult[]; - timer:Timer; - - testReporter:ITestReporter; - printErrorCount:boolean; - } - - ///////////////////////////////// - // Test reporter interface - // for example, . and x - ///////////////////////////////// - export interface ITestReporter { - printPositiveCharacter(index:number, testResult:TestResult):void; - printNegativeCharacter(index:number, testResult:TestResult):void; - } - - ///////////////////////////////// - // Default test reporter - ///////////////////////////////// - class DefaultTestReporter implements ITestReporter { - constructor(public print:Print) { - } - - public printPositiveCharacter(index:number, testResult:TestResult) { - this.print.out('\33[36m\33[1m' + '.' + '\33[0m'); - - this.printBreakIfNeeded(index); - } - - public printNegativeCharacter(index:number, testResult:TestResult) { - this.print.out("x"); - - this.printBreakIfNeeded(index); - } - - private printBreakIfNeeded(index:number) { - if (index % this.print.WIDTH === 0) { - this.print.printBreak(); - } - } - } - - ///////////////////////////////// - // All the common things that we pring are functions of this class - ///////////////////////////////// - class Print { - - WIDTH = 77; - - constructor(public version:string, public typings:number, public tests:number, public tsFiles:number) { - } - - public out(s:any):Print { - process.stdout.write(s); - return this; - } - - public repeat(s:string, times:number):string { - return new Array(times + 1).join(s); - } - - public printHeader() { - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.4.0\33[0m\n'); - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); - this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); - this.out(' \33[36m\33[1mTests :\33[0m ' + this.tests + '\n'); - this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); - } - - public printSuiteHeader(title:string) { - var left = Math.floor((this.WIDTH - title.length ) / 2) - 1; - var right = Math.ceil((this.WIDTH - title.length ) / 2) - 1; - this.out(this.repeat("=", left)).out(" \33[34m\33[1m"); - this.out(title); - this.out("\33[0m ").out(this.repeat("=", right)).printBreak(); - } - - public printDiv() { - this.out('-----------------------------------------------------------------------------\n'); - } - - public printBoldDiv() { - this.out('=============================================================================\n'); - } - - public printErrorsHeader() { - this.out('=============================================================================\n'); - this.out(' \33[34m\33[1mErrors in files\33[0m \n'); - this.out('=============================================================================\n'); - } - - public printErrorsForFile(testResult:TestResult) { - this.out('----------------- For file:' + testResult.targetFile.formatName); - this.printBreak().out(testResult.stderr).printBreak(); - } - - public printBreak():Print { - this.out('\n'); - return this; - } - - public clearCurrentLine():Print { - this.out("\r\33[K"); - return this; - } - - public printSuccessCount(current:number, total:number) { - this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - - public printFailedCount(current:number, total:number) { - this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - - public printTypingsWithoutTestsMessage() { - this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); - } - - public printTotalMessage() { - this.out(' \33[36m\33[1mTotal\33[0m\n'); - } - - public printElapsedTime(time:string, s:number) { - this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); - } - - public printSuiteErrorCount(errorHeadline:string, current:number, total:number, valuesColor = '\33[31m\33[1m') { - this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length)); - this.out(':\33[0m ' + valuesColor + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - - public printTypingsWithoutTestName(file:string) { - this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); - } - - public printTypingsWithoutTest(withoutTestTypings:string[]) { - if (withoutTestTypings.length > 0) { - this.printTypingsWithoutTestsMessage(); - - this.printDiv(); - withoutTestTypings.forEach(t=> { - this.printTypingsWithoutTestName(t); - }); - } - } - } - - ///////////////////////////////// - // Base class for test suite - ///////////////////////////////// - class TestSuiteBase implements ITestSuite { - timer:Timer = new Timer(); - testResults:TestResult[] = []; - testReporter:ITestReporter; - printErrorCount = true; - - constructor(public options:ITestRunnerOptions, public testSuiteName:string, public errorHeadline:string) { - } - - public filterTargetFiles(files:File[]):File[] { - throw new Error("please implement this method"); - } - - public start(targetFiles:File[], testCallback:(result:TestResult, index:number)=>void, suiteCallback:(suite:ITestSuite)=>void):void { - targetFiles = this.filterTargetFiles(targetFiles); - this.timer.start(); - var count = 0; - // exec test is async process. serialize. - var executor = () => { - var targetFile = targetFiles[count]; - if (targetFile) { - this.runTest(targetFile, (result)=> { - testCallback(result, count + 1); - count++; - executor(); - }); - } else { - this.timer.end(); - this.finish(suiteCallback); - } - }; - executor(); - } - - public runTest(targetFile:File, callback:(result:TestResult)=>void):void { - new Test(this, targetFile, {tscVersion: this.options.tscVersion}).run(result=> { - this.testResults.push(result); - callback(result); - }); - } - - public finish(suiteCallback:(suite:ITestSuite)=>void) { - suiteCallback(this); - } - - public get okTests():TestResult[] { - return this.testResults.filter(r=>r.success); - } - - public get ngTests():TestResult[] { - return this.testResults.filter(r=>!r.success); - } - } - - ///////////////////////////////// - // .d.ts syntax inspection - ///////////////////////////////// - class SyntaxChecking extends TestSuiteBase { - - constructor(options:ITestRunnerOptions) { - super(options, "Syntax checking", "Syntax error"); - } - - public filterTargetFiles(files:File[]):File[] { - return files.filter(file => endsWith(file.formatName.toUpperCase(), '.D.TS')); - } - } - - ///////////////////////////////// - // Compile with *-tests.ts - ///////////////////////////////// - class TestEval extends TestSuiteBase { - - constructor(options) { - super(options, "Typing tests", "Failed tests"); - } - - public filterTargetFiles(files:File[]):File[] { - return files.filter(file => endsWith(file.formatName.toUpperCase(), '-TESTS.TS')); - } - } - - ///////////////////////////////// - // Try compile without .tscparams - // It may indicate that it is compatible with --noImplicitAny maybe... - ///////////////////////////////// - class FindNotRequiredTscparams extends TestSuiteBase { - testReporter:ITestReporter; - printErrorCount = false; - - constructor(options:ITestRunnerOptions, private print:Print) { - super(options, "Find not required .tscparams files", "New arrival!"); - - this.testReporter = { - printPositiveCharacter: (index:number, testResult:TestResult)=> { - this.print - .clearCurrentLine() - .printTypingsWithoutTestName(testResult.targetFile.formatName); - }, - printNegativeCharacter: (index:number, testResult:TestResult)=> { - } - } - } - - public filterTargetFiles(files:File[]):File[] { - return files.filter(file=> IO.fileExists(file.filePathWithName + '.tscparams')); - } - - public runTest(targetFile:File, callback:(result:TestResult)=>void):void { - this.print.clearCurrentLine().out(targetFile.formatName); - new Test(this, targetFile, {tscVersion: this.options.tscVersion, useTscParams: false, checkNoImplicitAny: true}).run(result=> { - this.testResults.push(result); - callback(result); - }); - } - - public finish(suiteCallback:(suite:ITestSuite)=>void) { - this.print.clearCurrentLine(); - suiteCallback(this); - } - - public get ngTests():TestResult[] { - // Do not show ng test results - return []; - } - } - - export interface ITestRunnerOptions { - tscVersion:string; - findNotRequiredTscparams?:boolean; - } - - ///////////////////////////////// - // The main class to kick things off - ///////////////////////////////// - export class TestRunner { - files:File[]; - timer:Timer; - suites:ITestSuite[] = []; - private print:Print; - - constructor(dtPath:string, public options:ITestRunnerOptions = {tscVersion: DEFAULT_TSC_VERSION}) { - this.options.findNotRequiredTscparams = !!this.options.findNotRequiredTscparams; - - var filesName = IO.dir(dtPath, /.\.ts/g, { recursive: true }).sort(); - // only includes .d.ts or -tests.ts or -test.ts or .ts - filesName = filesName - .filter(fileName => fileName.indexOf('../_infrastructure') < 0) - .filter(fileName => !endsWith(fileName, ".tscparams")); - this.files = filesName.map(fileName => new File(dtPath, fileName)); - } - - public addSuite(suite:ITestSuite) { - this.suites.push(suite); - } - - public run() { - this.timer = new Timer(); - this.timer.start(); - - var syntaxChecking = new SyntaxChecking(this.options); - var testEval = new TestEval(this.options); - if (!this.options.findNotRequiredTscparams) { - this.addSuite(syntaxChecking); - this.addSuite(testEval); - } - - var typings = syntaxChecking.filterTargetFiles(this.files).length; - var testFiles = testEval.filterTargetFiles(this.files).length; - this.print = new Print(this.options.tscVersion, typings, testFiles, this.files.length); - this.print.printHeader(); - - if (this.options.findNotRequiredTscparams) { - this.addSuite(new FindNotRequiredTscparams(this.options, this.print)); - } - - var count = 0; - var executor = () => { - var suite = this.suites[count]; - if (suite) { - suite.testReporter = suite.testReporter || new DefaultTestReporter(this.print); - - this.print.printSuiteHeader(suite.testSuiteName); - var targetFiles = suite.filterTargetFiles(this.files); - suite.start( - targetFiles, - (testResult, index) => { - this.testCompleteCallback(testResult, index); - }, - suite=> { - this.suiteCompleteCallback(suite); - count++; - executor(); - }); - } else { - this.timer.end(); - this.allTestCompleteCallback(); - } - }; - executor(); - } - - private testCompleteCallback(testResult:TestResult, index:number) { - var reporter = testResult.hostedBy.testReporter; - if (testResult.success) { - reporter.printPositiveCharacter(index, testResult); - } else { - reporter.printNegativeCharacter(index, testResult); - } - } - - private suiteCompleteCallback(suite:ITestSuite) { - this.print.printBreak(); - - this.print.printDiv(); - this.print.printElapsedTime(suite.timer.asString, suite.timer.time); - this.print.printSuccessCount(suite.okTests.length, suite.testResults.length); - this.print.printFailedCount(suite.ngTests.length, suite.testResults.length); - } - - private allTestCompleteCallback() { - var testEval = this.suites.filter(suite=>suite instanceof TestEval)[0]; - if (testEval) { - var existsTestTypings:string[] = testEval.testResults - .map(testResult=>testResult.targetFile.dir) - .reduce((a, b)=> a.indexOf(b) < 0 ? a.concat([b]) : a, []); - var typings:string[] = this.files - .map(file=>file.dir) - .reduce((a, b)=> a.indexOf(b) < 0 ? a.concat([b]) : a, []); - var withoutTestTypings:string[] = typings - .filter(typing=>existsTestTypings.indexOf(typing) < 0); - this.print.printDiv(); - this.print.printTypingsWithoutTest(withoutTestTypings); - } - - this.print.printDiv(); - this.print.printTotalMessage(); - - this.print.printDiv(); - this.print.printElapsedTime(this.timer.asString, this.timer.time); - this.suites - .filter(suite=>suite.printErrorCount) - .forEach(suite=> { - this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length); - }); - if (testEval) { - this.print.printSuiteErrorCount("Without tests", withoutTestTypings.length, typings.length, '\33[33m\33[1m'); - } - - this.print.printDiv(); - if (this.suites.some(suite=>suite.ngTests.length !== 0)) { - this.print.printErrorsHeader(); - - this.suites - .filter(suite=>suite.ngTests.length !== 0) - .forEach(suite=> { - suite.ngTests.forEach(testResult => { - this.print.printErrorsForFile(testResult); - }); - this.print.printBoldDiv(); - }); - - process.exit(1); - } - } - } +/// + +/// + +/// +/// +/// +/// + +/// +/// + +/// +/// + +/// +/// +/// +/// + +module DT { + require('source-map-support').install(); + + // hacky typing + var Lazy: LazyJS.LazyStatic = require('lazy.js'); + var Promise: typeof Promise = require('bluebird'); + + var os = require('os'); + var fs = require('fs'); + var path = require('path'); + var assert = require('assert'); + + var tsExp = /\.ts$/; + + export var DEFAULT_TSC_VERSION = '0.9.7'; + + ///////////////////////////////// + // Single test + ///////////////////////////////// + export class Test { + constructor(public suite: ITestSuite, public tsfile: File, public options?: TscExecOptions) { + } + + public run(): Promise { + return Tsc.run(this.tsfile.filePathWithName, this.options).then((execResult: ExecResult) => { + var testResult = new TestResult(); + testResult.hostedBy = this.suite; + testResult.targetFile = this.tsfile; + testResult.options = this.options; + + testResult.stdout = execResult.stdout; + testResult.stderr = execResult.stderr; + testResult.exitCode = execResult.exitCode; + + return testResult; + }); + } + } + + ///////////////////////////////// + // Parallel execute Tests + ///////////////////////////////// + export class TestQueue { + + private queue: Function[] = []; + private active: Test[] = []; + private concurrent: number; + + constructor(concurrent: number) { + this.concurrent = Math.max(1, concurrent); + } + + // add to queue and return a promise + run(test: Test): Promise { + var defer = Promise.defer(); + // add a closure to queue + this.queue.push(() => { + // when activate, add test to active list + this.active.push(test); + // run it + var p = test.run(); + p.then(defer.resolve.bind(defer), defer.reject.bind(defer)); + p.finally(() => { + var i = this.active.indexOf(test); + if (i > -1) { + this.active.splice(i, 1); + } + this.step(); + }); + }); + this.step(); + // defer it + return defer.promise; + } + + private step(): void { + // setTimeout to make it flush + setTimeout(() => { + while (this.queue.length > 0 && this.active.length < this.concurrent) { + this.queue.pop().call(null); + } + }, 1); + } + } + + ///////////////////////////////// + // Test results + ///////////////////////////////// + export class TestResult { + hostedBy: ITestSuite; + targetFile: File; + options: TscExecOptions; + + stdout: string; + stderr: string; + exitCode: number; + + public get success(): boolean { + return this.exitCode === 0; + } + } + + export interface ITestRunnerOptions { + tscVersion:string; + concurrent?:number; + testChanges?:boolean; + skipTests?:boolean; + printFiles?:boolean; + printRefMap?:boolean; + findNotRequiredTscparams?:boolean; + } + + ///////////////////////////////// + // The main class to kick things off + ///////////////////////////////// + export class TestRunner { + private timer: Timer; + private suites: ITestSuite[] = []; + + public changes: GitChanges; + public index: FileIndex; + public print: Print; + + constructor(public dtPath: string, public options: ITestRunnerOptions = {tscVersion: DT.DEFAULT_TSC_VERSION}) { + this.options.findNotRequiredTscparams = !!this.options.findNotRequiredTscparams; + + this.index = new FileIndex(this, this.options); + this.changes = new GitChanges(this); + + this.print = new Print(this.options.tscVersion); + } + + public addSuite(suite: ITestSuite): void { + this.suites.push(suite); + } + + public checkAcceptFile(fileName: string): boolean { + var ok = tsExp.test(fileName); + ok = ok && fileName.indexOf('_infrastructure') < 0; + ok = ok && fileName.indexOf('node_modules/') < 0; + ok = ok && /^[a-z]/i.test(fileName); + return ok; + } + + public run(): Promise { + this.timer = new Timer(); + this.timer.start(); + + this.print.printChangeHeader(); + + // only includes .d.ts or -tests.ts or -test.ts or .ts + return this.index.readIndex().then(() => { + return this.changes.readChanges(); + }).then((changes: string[]) => { + this.print.printAllChanges(changes); + return this.index.collectDiff(changes); + }).then(() => { + this.print.printRemovals(this.index.removed); + this.print.printRelChanges(this.index.changed); + return this.index.parseFiles(); + }).then(() => { + if (this.options.printRefMap) { + this.print.printRefMap(this.index, this.index.refMap); + } + if (Lazy(this.index.missing).some((arr: any[]) => arr.length > 0)) { + this.print.printMissing(this.index, this.index.missing); + this.print.printBoldDiv(); + // bail + return Promise.cast(false); + } + if (this.options.printFiles) { + this.print.printFiles(this.index.files); + } + return this.index.collectTargets().then((files) => { + if (this.options.testChanges) { + this.print.printQueue(files); + return this.runTests(files); + } + else { + this.print.printTestAll(); + return this.runTests(this.index.files) + } + }).then(() => { + return !this.suites.some((suite) => { + return suite.ngTests.length !== 0 + }); + }); + }); + } + + private runTests(files: File[]): Promise { + return Promise.attempt(() => { + assert(Array.isArray(files), 'files must be array'); + + var syntaxChecking = new SyntaxChecking(this.options); + var testEval = new TestEval(this.options); + + if (!this.options.findNotRequiredTscparams) { + this.addSuite(syntaxChecking); + this.addSuite(testEval); + } + + return Promise.all([ + syntaxChecking.filterTargetFiles(files), + testEval.filterTargetFiles(files) + ]); + }).spread((syntaxFiles, testFiles) => { + this.print.init(syntaxFiles.length, testFiles.length, files.length); + this.print.printHeader(this.options); + + if (this.options.findNotRequiredTscparams) { + this.addSuite(new FindNotRequiredTscparams(this.options, this.print)); + } + + return Promise.reduce(this.suites, (count, suite: ITestSuite) => { + suite.testReporter = suite.testReporter || new DefaultTestReporter(this.print); + + this.print.printSuiteHeader(suite.testSuiteName); + + if (this.options.skipTests) { + this.print.printWarnCode('skipped test'); + return Promise.cast(count++); + } + + return suite.start(files, (testResult) => { + this.print.printTestComplete(testResult); + }).then((suite) => { + this.print.printSuiteComplete(suite); + return count++; + }); + }, 0); + }).then((count) => { + this.timer.end(); + this.finaliseTests(files); + }); + } + + private finaliseTests(files: File[]): void { + var testEval: TestEval = Lazy(this.suites).filter((suite) => { + return suite instanceof TestEval; + }).first(); + + if (testEval) { + var existsTestTypings: string[] = Lazy(testEval.testResults).map((testResult) => { + return testResult.targetFile.dir; + }).reduce((a: string[], b: string) => { + return a.indexOf(b) < 0 ? a.concat([b]) : a; + }, []); + + var typings: string[] = Lazy(files).map((file) => { + return file.dir; + }).reduce((a: string[], b: string) => { + return a.indexOf(b) < 0 ? a.concat([b]) : a; + }, []); + + var withoutTestTypings: string[] = typings.filter((typing) => { + return existsTestTypings.indexOf(typing) < 0; + }); + + this.print.printDiv(); + this.print.printTypingsWithoutTest(withoutTestTypings); + } + + this.print.printDiv(); + this.print.printTotalMessage(); + + this.print.printDiv(); + this.print.printElapsedTime(this.timer.asString, this.timer.time); + + this.suites.filter((suite: ITestSuite) => { + return suite.printErrorCount; + }).forEach((suite: ITestSuite) => { + this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length); + }); + if (testEval) { + this.print.printSuiteErrorCount('Without tests', withoutTestTypings.length, typings.length, true); + } + + this.print.printDiv(); + + if (this.suites.some((suite) => { + return suite.ngTests.length !== 0 + })) { + this.print.printErrorsHeader(); + + this.suites.filter((suite) => { + return suite.ngTests.length !== 0; + }).forEach((suite) => { + suite.ngTests.forEach((testResult) => { + this.print.printErrorsForFile(testResult); + }); + this.print.printBoldDiv(); + }); + } + } + } + + var optimist: Optimist = require('optimist')(process.argv); + optimist.default('try-without-tscparams', false); + optimist.default('single-thread', false); + optimist.default('tsc-version', DEFAULT_TSC_VERSION); + + optimist.default('test-changes', false); + optimist.default('skip-tests', false); + optimist.default('print-files', false); + optimist.default('print-refmap', false); + + optimist.boolean('help'); + optimist.describe('help', 'print help'); + optimist.alias('h', 'help'); + + var argv: any = optimist.argv; + + var dtPath = path.resolve(path.dirname((module).filename), '..', '..'); + var cpuCores = os.cpus().length; + + if (argv.help) { + optimist.showHelp(); + process.exit(0); + } + + new TestRunner(dtPath, { + concurrent: argv['single-thread'] ? 1 : Math.max(cpuCores, 2), + tscVersion: argv['tsc-version'], + testChanges: argv['test-changes'], + skipTests: argv['skip-tests'], + printFiles: argv['print-files'], + printRefMap: argv['print-refmap'], + findNotRequiredTscparams: argv['try-without-tscparam'] + }).run().then((success) => { + if (!success) { + process.exit(1); + } + }).catch((err) => { + throw err; + process.exit(2); + }); } - -var dtPath = __dirname + '/../..'; -var findNotRequiredTscparams = process.argv.some(arg=>arg == "--try-without-tscparams"); -var tscVersionIndex = process.argv.indexOf("--tsc-version"); -var tscVersion = DefinitelyTyped.TestManager.DEFAULT_TSC_VERSION; -if (-1 < tscVersionIndex) { - tscVersion = process.argv[tscVersionIndex + 1]; -} - -var runner = new DefinitelyTyped.TestManager.TestRunner(dtPath, { - tscVersion: tscVersion, - findNotRequiredTscparams: findNotRequiredTscparams -}); -runner.run(); diff --git a/_infrastructure/tests/src/changes.ts b/_infrastructure/tests/src/changes.ts new file mode 100644 index 0000000000..a56c4029eb --- /dev/null +++ b/_infrastructure/tests/src/changes.ts @@ -0,0 +1,36 @@ +/// +/// + +module DT { + 'use strict'; + + var fs = require('fs'); + var path = require('path'); + var Git = require('git-wrapper'); + var Promise: typeof Promise = require('bluebird'); + + export class GitChanges { + + git; + options = {}; + + constructor(private runner: TestRunner) { + var dir = path.join(this.runner.dtPath, '.git'); + if (!fs.existsSync(dir)) { + throw new Error('cannot locate git-dir: ' + dir); + } + this.options['git-dir'] = dir; + + this.git = new Git(this.options); + this.git.exec = Promise.promisify(this.git.exec); + } + + public readChanges(): Promise { + var opts = {}; + var args = ['--name-only HEAD~1']; + return this.git.exec('diff', opts, args).then((msg: string) => { + return msg.replace(/^\s+/, '').replace(/\s+$/, '').split(/\r?\n/g); + }); + } + } +} diff --git a/_infrastructure/tests/src/exec.js b/_infrastructure/tests/src/exec.js deleted file mode 100644 index 2b8ea5c597..0000000000 --- a/_infrastructure/tests/src/exec.js +++ /dev/null @@ -1,79 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -var ExecResult = (function () { - function ExecResult() { - this.stdout = ""; - this.stderr = ""; - } - return ExecResult; -})(); - -var WindowsScriptHostExec = (function () { - function WindowsScriptHostExec() { - } - WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var result = new ExecResult(); - var shell = new ActiveXObject('WScript.Shell'); - try { - var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); - } catch (e) { - result.stderr = e.message; - result.exitCode = 1; - handleResult(result); - return; - } - - while (process.Status != 0) { - } - - result.exitCode = process.ExitCode; - if (!process.StdOut.AtEndOfStream) - result.stdout = process.StdOut.ReadAll(); - if (!process.StdErr.AtEndOfStream) - result.stderr = process.StdErr.ReadAll(); - - handleResult(result); - }; - return WindowsScriptHostExec; -})(); - -var NodeExec = (function () { - function NodeExec() { - } - NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var nodeExec = require('child_process').exec; - - var result = new ExecResult(); - result.exitCode = null; - var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - - var process = nodeExec(cmdLine, function (error, stdout, stderr) { - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - handleResult(result); - }); - }; - return NodeExec; -})(); - -var Exec = (function () { - var global = Function("return this;").call(null); - if (typeof global.ActiveXObject !== "undefined") { - return new WindowsScriptHostExec(); - } else { - return new NodeExec(); - } -})(); diff --git a/_infrastructure/tests/src/exec.ts b/_infrastructure/tests/src/exec.ts index 5123d4cfc6..3c3f3c0e02 100644 --- a/_infrastructure/tests/src/exec.ts +++ b/_infrastructure/tests/src/exec.ts @@ -1,77 +1,30 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// +module DT { + 'use strict'; -// Allows for executing a program with command-line arguments and reading the result -interface IExec { - exec: (filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) => void; + var Promise: typeof Promise = require('bluebird'); + var nodeExec = require('child_process').exec; + + export class ExecResult { + error; + stdout = ''; + stderr = ''; + exitCode: number; + } + + export function exec(filename: string, cmdLineArgs: string[]): Promise { + return new Promise((resolve) => { + var result = new ExecResult(); + result.exitCode = null; + + var cmdLine = filename + ' ' + cmdLineArgs.join(' '); + + nodeExec(cmdLine, {maxBuffer: 1 * 1024 * 1024}, (error, stdout, stderr) => { + result.error = error; + result.stdout = stdout; + result.stderr = stderr; + result.exitCode = error ? error.code : 0; + resolve(result); + }); + }); + } } - -declare var require; - -class ExecResult { - public stdout = ""; - public stderr = ""; - public exitCode: number; -} - -class WindowsScriptHostExec implements IExec { - public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) : void { - var result = new ExecResult(); - var shell = new ActiveXObject('WScript.Shell'); - try { - var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); - } catch(e) { - result.stderr = e.message; - result.exitCode = 1 - handleResult(result); - return; - } - // Wait for it to finish running - while (process.Status != 0) { /* todo: sleep? */ } - - - result.exitCode = process.ExitCode; - if(!process.StdOut.AtEndOfStream) result.stdout = process.StdOut.ReadAll(); - if(!process.StdErr.AtEndOfStream) result.stderr = process.StdErr.ReadAll(); - - handleResult(result); - } -} - -class NodeExec implements IExec { - public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) : void { - var nodeExec = require('child_process').exec; - - var result = new ExecResult(); - result.exitCode = null; - var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - - var process = nodeExec(cmdLine, {maxBuffer: 1 * 1024 * 1024}, function (error, stdout, stderr) { - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - handleResult(result); - }); - } -} - -var Exec: IExec = function() : IExec { - var global = Function("return this;").call(null); - if(typeof global.ActiveXObject !== "undefined") { - return new WindowsScriptHostExec(); - } else { - return new NodeExec(); - } -}(); \ No newline at end of file diff --git a/_infrastructure/tests/src/file.ts b/_infrastructure/tests/src/file.ts new file mode 100644 index 0000000000..2c69f8f885 --- /dev/null +++ b/_infrastructure/tests/src/file.ts @@ -0,0 +1,46 @@ +/// + +module DT { + 'use strict'; + + var path = require('path'); + + export interface FileDict { + [fullPath:string]: File; + } + + export interface FileArrDict { + [fullPath:string]: File[]; + } + + ///////////////////////////////// + // Given a document root + ts file pattern this class returns: + // all the TS files OR just tests OR just definition files + ///////////////////////////////// + export class File { + baseDir: string; + filePathWithName: string; + dir: string; + file: string; + ext: string; + fullPath: string; + references: File[] = []; + + constructor(baseDir: string, filePathWithName: string) { + // why choose? + this.baseDir = baseDir; + this.filePathWithName = filePathWithName; + this.ext = path.extname(this.filePathWithName); + this.file = path.basename(this.filePathWithName, this.ext); + this.dir = path.dirname(this.filePathWithName); + this.fullPath = path.join(this.baseDir, this.dir, this.file + this.ext); + + // lock it (shallow) (needs `use strict` in each file to work) + // Object.freeze(this); + } + + toString(): string { + return '[File ' + this.filePathWithName + ']'; + } + } +} diff --git a/_infrastructure/tests/src/index.ts b/_infrastructure/tests/src/index.ts new file mode 100644 index 0000000000..7f5878dcb3 --- /dev/null +++ b/_infrastructure/tests/src/index.ts @@ -0,0 +1,208 @@ +/// +/// +/// + +module DT { + 'use strict'; + + var fs = require('fs'); + var path = require('path'); + var glob = require('glob'); + var Lazy: LazyJS.LazyStatic = require('lazy.js'); + var Promise: typeof Promise = require('bluebird'); + + var readFile = Promise.promisify(fs.readFile); + + ///////////////////////////////// + // Track all files in the repo: map full path to File objects + ///////////////////////////////// + export class FileIndex { + + files: File[]; + fileMap: FileDict; + refMap: FileArrDict; + options: ITestRunnerOptions; + changed: FileDict; + removed: FileDict; + missing: FileArrDict; + + constructor(private runner: TestRunner, options: ITestRunnerOptions) { + this.options = options; + } + + public hasFile(target: string): boolean { + return target in this.fileMap; + } + + public getFile(target: string): File { + if (target in this.fileMap) { + return this.fileMap[target]; + } + return null; + } + + public setFile(file: File): void { + if (file.fullPath in this.fileMap) { + throw new Error('cannot overwrite file'); + } + this.fileMap[file.fullPath] = file; + } + + public readIndex(): Promise { + this.fileMap = Object.create(null); + + return Promise.promisify(glob).call(glob, '**/*.ts', { + cwd: this.runner.dtPath + }).then((filesNames: string[]) => { + this.files = Lazy(filesNames).filter((fileName) => { + return this.runner.checkAcceptFile(fileName); + }).map((fileName: string) => { + var file = new File(this.runner.dtPath, fileName); + this.fileMap[file.fullPath] = file; + return file; + }).toArray(); + }); + } + + public collectDiff(changes: string[]): Promise { + return new Promise((resolve) => { + // filter changes and bake map for easy lookup + this.changed = Object.create(null); + this.removed = Object.create(null); + + Lazy(changes).filter((full) => { + return this.runner.checkAcceptFile(full); + }).uniq().each((local) => { + var full = path.resolve(this.runner.dtPath, local); + var file = this.getFile(full); + if (!file) { + // TODO figure out what to do here + // what does it mean? deleted?ss + file = new File(this.runner.dtPath, local); + this.setFile(file); + this.removed[full] = file; + // console.log('not in index? %', file.fullPath); + } + else { + this.changed[full] = file; + } + }); + // console.log('changed:\n' + Object.keys(this.changed).join('\n')); + // console.log('removed:\n' + Object.keys(this.removed).join('\n')); + resolve(); + }); + } + + public parseFiles(): Promise { + return this.loadReferences(this.files).then(() => { + return this.getMissingReferences(); + }); + } + + private getMissingReferences(): Promise { + return Promise.attempt(() => { + this.missing = Object.create(null); + Lazy(this.removed).keys().each((removed) => { + if (removed in this.refMap) { + this.missing[removed] = this.refMap[removed]; + } + }); + }); + } + + private loadReferences(files: File[]): Promise { + return new Promise((resolve, reject) => { + var queue = files.slice(0); + var active = []; + var max = 50; + var next = () => { + if (queue.length === 0 && active.length === 0) { + resolve(); + return; + } + // queue paralel + while (queue.length > 0 && active.length < max) { + var file = queue.pop(); + active.push(file); + this.parseFile(file).then((file) => { + active.splice(active.indexOf(file), 1); + next(); + }).catch((err) => { + queue = []; + active = []; + reject(err); + }); + } + }; + next(); + }).then(() => { + // bake reverse reference map (referenced to referrers) + this.refMap = Object.create(null); + + Lazy(files).each((file) => { + Lazy(file.references).each((ref) => { + if (ref.fullPath in this.refMap) { + this.refMap[ref.fullPath].push(file); + } + else { + this.refMap[ref.fullPath] = [file]; + } + }); + }); + }); + } + + // TODO replace with a stream? + private parseFile(file: File): Promise { + return readFile(file.filePathWithName, { + encoding: 'utf8', + flag: 'r' + }).then((content) => { + file.references = Lazy(extractReferenceTags(content)).map((ref) => { + return path.resolve(path.dirname(file.fullPath), ref); + }).reduce((memo: File[], ref) => { + if (ref in this.fileMap) { + memo.push(this.fileMap[ref]); + } + else { + console.log('not mapped? -> ' + ref); + } + return memo; + }, []); + // return the object + return file; + }); + } + + public collectTargets(): Promise { + return new Promise((resolve) => { + // map out files linked to changes + // - queue holds files touched by a change + // - pre-fill with actually changed files + // - loop queue, if current not seen: + // - add to result + // - from refMap queue all files referring to current + + var result: FileDict = Object.create(null); + var queue = Lazy(this.changed).values().toArray(); + + while (queue.length > 0) { + var next = queue.shift(); + var fp = next.fullPath; + if (result[fp]) { + continue; + } + result[fp] = next; + if (fp in this.refMap) { + var arr = this.refMap[fp]; + for (var i = 0, ii = arr.length; i < ii; i++) { + // just add it and skip expensive checks + queue.push(arr[i]); + } + } + } + resolve(Lazy(result).values().toArray()); + }); + } + } +} diff --git a/_infrastructure/tests/src/io.js b/_infrastructure/tests/src/io.js deleted file mode 100644 index 0f8b9516c8..0000000000 --- a/_infrastructure/tests/src/io.js +++ /dev/null @@ -1,475 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -var IOUtils; -(function (IOUtils) { - // Creates the directory including its parent if not already present - function createDirectoryStructure(ioHost, dirName) { - if (ioHost.directoryExists(dirName)) { - return; - } - - var parentDirectory = ioHost.dirName(dirName); - if (parentDirectory != "") { - createDirectoryStructure(ioHost, parentDirectory); - } - ioHost.createDirectory(dirName); - } - - // Creates a file including its directory structure if not already present - function createFileAndFolderStructure(ioHost, fileName, useUTF8) { - var path = ioHost.resolvePath(fileName); - var dirName = ioHost.dirName(path); - createDirectoryStructure(ioHost, dirName); - return ioHost.createFile(path, useUTF8); - } - IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; - - function throwIOError(message, error) { - var errorMessage = message; - if (error && error.message) { - errorMessage += (" " + error.message); - } - throw new Error(errorMessage); - } - IOUtils.throwIOError = throwIOError; -})(IOUtils || (IOUtils = {})); - -var IO = (function () { - // Create an IO object for use inside WindowsScriptHost hosts - // Depends on WSCript and FileSystemObject - function getWindowsScriptHostIO() { - var fso = new ActiveXObject("Scripting.FileSystemObject"); - var streamObjectPool = []; - - function getStreamObject() { - if (streamObjectPool.length > 0) { - return streamObjectPool.pop(); - } else { - return new ActiveXObject("ADODB.Stream"); - } - } - - function releaseStreamObject(obj) { - streamObjectPool.push(obj); - } - - var args = []; - for (var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - - return { - readFile: function (path) { - try { - var streamObj = getStreamObject(); - streamObj.Open(); - streamObj.Type = 2; - streamObj.Charset = 'x-ansi'; - streamObj.LoadFromFile(path); - var bomChar = streamObj.ReadText(2); - streamObj.Position = 0; - if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { - streamObj.Charset = 'unicode'; - } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { - streamObj.Charset = 'utf-8'; - } - - // Read the whole file - var str = streamObj.ReadText(-1); - streamObj.Close(); - releaseStreamObject(streamObj); - return str; - } catch (err) { - IOUtils.throwIOError("Error reading file \"" + path + "\".", err); - } - }, - writeFile: function (path, contents) { - var file = this.createFile(path); - file.Write(contents); - file.Close(); - }, - fileExists: function (path) { - return fso.FileExists(path); - }, - resolvePath: function (path) { - return fso.GetAbsolutePathName(path); - }, - dirName: function (path) { - return fso.GetParentFolderName(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; - - while (true) { - if (fso.FileExists(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } catch (err) { - //Tools.CompilerDiagnostics.debugPrint("Could not find " + path + ", trying parent"); - } - } else { - rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); - - if (rootPath == "") { - return null; - } else { - path = fso.BuildPath(rootPath, partialFilePath); - } - } - } - }, - deleteFile: function (path) { - try { - if (fso.FileExists(path)) { - fso.DeleteFile(path, true); - } - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - createFile: function (path, useUTF8) { - try { - var streamObj = getStreamObject(); - streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; - streamObj.Open(); - return { - Write: function (str) { - streamObj.WriteText(str, 0); - }, - WriteLine: function (str) { - streamObj.WriteText(str, 1); - }, - Close: function () { - try { - streamObj.SaveToFile(path, 2); - } catch (saveError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); - } finally { - if (streamObj.State != 0) { - streamObj.Close(); - } - releaseStreamObject(streamObj); - } - } - }; - } catch (creationError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); - } - }, - directoryExists: function (path) { - return fso.FolderExists(path); - }, - createDirectory: function (path) { - try { - if (!this.directoryExists(path)) { - fso.CreateFolder(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - dir: function (path, spec, options) { - options = options || {}; - function filesInFolder(folder, root) { - var paths = []; - var fc; - - if (options.recursive) { - fc = new Enumerator(folder.subfolders); - - for (; !fc.atEnd(); fc.moveNext()) { - paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); - } - } - - fc = new Enumerator(folder.files); - - for (; !fc.atEnd(); fc.moveNext()) { - if (!spec || fc.item().Name.match(spec)) { - paths.push(root + "/" + fc.item().Name); - } - } - - return paths; - } - - var folder = fso.GetFolder(path); - var paths = []; - - return filesInFolder(folder, path); - }, - print: function (str) { - WScript.StdOut.Write(str); - }, - printLine: function (str) { - WScript.Echo(str); - }, - arguments: args, - stderr: WScript.StdErr, - stdout: WScript.StdOut, - watchFile: null, - run: function (source, filename) { - try { - eval(source); - } catch (e) { - IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); - } - }, - getExecutingFilePath: function () { - return WScript.ScriptFullName; - }, - quit: function (exitCode) { - if (typeof exitCode === "undefined") { exitCode = 0; } - try { - WScript.Quit(exitCode); - } catch (e) { - } - } - }; - } - ; - - // Create an IO object for use inside Node.js hosts - // Depends on 'fs' and 'path' modules - function getNodeIO() { - var _fs = require('fs'); - var _path = require('path'); - var _module = require('module'); - - return { - readFile: function (file) { - try { - var buffer = _fs.readFileSync(file); - switch (buffer[0]) { - case 0xFE: - if (buffer[1] == 0xFF) { - // utf16-be. Reading the buffer as big endian is not supported, so convert it to - // Little Endian first - var i = 0; - while ((i + 1) < buffer.length) { - var temp = buffer[i]; - buffer[i] = buffer[i + 1]; - buffer[i + 1] = temp; - i += 2; - } - return buffer.toString("ucs2", 2); - } - break; - case 0xFF: - if (buffer[1] == 0xFE) { - // utf16-le - return buffer.toString("ucs2", 2); - } - break; - case 0xEF: - if (buffer[1] == 0xBB) { - // utf-8 - return buffer.toString("utf8", 3); - } - } - - // Default behaviour - return buffer.toString(); - } catch (e) { - IOUtils.throwIOError("Error reading file \"" + file + "\".", e); - } - }, - writeFile: _fs.writeFileSync, - deleteFile: function (path) { - try { - _fs.unlinkSync(path); - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - createFile: function (path, useUTF8) { - function mkdirRecursiveSync(path) { - var stats = _fs.statSync(path); - if (stats.isFile()) { - IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); - } else if (stats.isDirectory()) { - return; - } else { - mkdirRecursiveSync(_path.dirname(path)); - _fs.mkdirSync(path, 0775); - } - } - - mkdirRecursiveSync(_path.dirname(path)); - - try { - var fd = _fs.openSync(path, 'w'); - } catch (e) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); - } - return { - Write: function (str) { - _fs.writeSync(fd, str); - }, - WriteLine: function (str) { - _fs.writeSync(fd, str + '\r\n'); - }, - Close: function () { - _fs.closeSync(fd); - fd = null; - } - }; - }, - dir: function dir(path, spec, options) { - options = options || {}; - - function filesInFolder(folder, deep) { - var paths = []; - - var files = _fs.readdirSync(folder); - for (var i = 0; i < files.length; i++) { - var stat = _fs.statSync(folder + "/" + files[i]); - if (options.recursive && stat.isDirectory()) { - if (deep < (options.deep || 100)) { - paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); - } - } else if (stat.isFile() && (!spec || files[i].match(spec))) { - paths.push(folder + "/" + files[i]); - } - } - - return paths; - } - - return filesInFolder(path, 0); - }, - createDirectory: function (path) { - try { - if (!this.directoryExists(path)) { - _fs.mkdirSync(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); - }, - resolvePath: function (path) { - return _path.resolve(path); - }, - dirName: function (path) { - return _path.dirname(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = rootPath + "/" + partialFilePath; - - while (true) { - if (_fs.existsSync(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } catch (err) { - //Tools.CompilerDiagnostics.debugPrint(("Could not find " + path) + ", trying parent"); - } - } else { - var parentPath = _path.resolve(rootPath, ".."); - - if (rootPath === parentPath) { - return null; - } else { - rootPath = parentPath; - path = _path.resolve(rootPath, partialFilePath); - } - } - } - }, - print: function (str) { - process.stdout.write(str); - }, - printLine: function (str) { - process.stdout.write(str + '\n'); - }, - arguments: process.argv.slice(2), - stderr: { - Write: function (str) { - process.stderr.write(str); - }, - WriteLine: function (str) { - process.stderr.write(str + '\n'); - }, - Close: function () { - } - }, - stdout: { - Write: function (str) { - process.stdout.write(str); - }, - WriteLine: function (str) { - process.stdout.write(str + '\n'); - }, - Close: function () { - } - }, - watchFile: function (filename, callback) { - var firstRun = true; - var processingChange = false; - - var fileChanged = function (curr, prev) { - if (!firstRun) { - if (curr.mtime < prev.mtime) { - return; - } - - _fs.unwatchFile(filename, fileChanged); - if (!processingChange) { - processingChange = true; - callback(filename); - setTimeout(function () { - processingChange = false; - }, 100); - } - } - firstRun = false; - _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); - }; - - fileChanged(); - return { - filename: filename, - close: function () { - _fs.unwatchFile(filename, fileChanged); - } - }; - }, - run: function (source, filename) { - require.main.filename = filename; - require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); - require.main._compile(source, filename); - }, - getExecutingFilePath: function () { - return process.mainModule.filename; - }, - quit: process.exit - }; - } - ; - - if (typeof ActiveXObject === "function") - return getWindowsScriptHostIO(); -else if (typeof require === "function") - return getNodeIO(); -else - return null; -})(); diff --git a/_infrastructure/tests/src/io.ts b/_infrastructure/tests/src/io.ts deleted file mode 100644 index 2c7a81f4f3..0000000000 --- a/_infrastructure/tests/src/io.ts +++ /dev/null @@ -1,515 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -interface IResolvedFile { - content: string; - path: string; -} - -interface IFileWatcher { - close(): void; -} - -interface IIO { - readFile(path: string): string; - writeFile(path: string, contents: string): void; - createFile(path: string, useUTF8?: boolean): ITextWriter; - deleteFile(path: string): void; - dir(path: string, re?: RegExp, options?: { recursive?: boolean; deep?: number; }): string[]; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - resolvePath(path: string): string; - dirName(path: string): string; - findFile(rootPath: string, partialFilePath: string): IResolvedFile; - print(str: string): void; - printLine(str: string): void; - arguments: string[]; - stderr: ITextWriter; - stdout: ITextWriter; - watchFile(filename: string, callback: (string) => void ): IFileWatcher; - run(source: string, filename: string): void; - getExecutingFilePath(): string; - quit(exitCode?: number); -} - -module IOUtils { - // Creates the directory including its parent if not already present - function createDirectoryStructure(ioHost: IIO, dirName: string) { - if (ioHost.directoryExists(dirName)) { - return; - } - - var parentDirectory = ioHost.dirName(dirName); - if (parentDirectory != "") { - createDirectoryStructure(ioHost, parentDirectory); - } - ioHost.createDirectory(dirName); - } - - // Creates a file including its directory structure if not already present - export function createFileAndFolderStructure(ioHost: IIO, fileName: string, useUTF8?: boolean) { - var path = ioHost.resolvePath(fileName); - var dirName = ioHost.dirName(path); - createDirectoryStructure(ioHost, dirName); - return ioHost.createFile(path, useUTF8); - } - - export function throwIOError(message: string, error: Error) { - var errorMessage = message; - if (error && error.message) { - errorMessage += (" " + error.message); - } - throw new Error(errorMessage); - } -} - -// Declare dependencies needed for all supported hosts -declare class Enumerator { - public atEnd(): boolean; - public moveNext(); - public item(): any; - constructor (o: any); -} - -// Missing in node definitions, but called in code below. -interface NodeProcess { - mainModule: { - filename: string; - } -} - -var IO = (function() { - - // Create an IO object for use inside WindowsScriptHost hosts - // Depends on WSCript and FileSystemObject - function getWindowsScriptHostIO(): IIO { - var fso = new ActiveXObject("Scripting.FileSystemObject"); - var streamObjectPool = []; - - function getStreamObject(): any { - if (streamObjectPool.length > 0) { - return streamObjectPool.pop(); - } else { - return new ActiveXObject("ADODB.Stream"); - } - } - - function releaseStreamObject(obj: any) { - streamObjectPool.push(obj); - } - - var args = []; - for (var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - - return { - readFile: function(path) { - try { - var streamObj = getStreamObject(); - streamObj.Open(); - streamObj.Type = 2; // Text data - streamObj.Charset = 'x-ansi'; // Assume we are reading ansi text - streamObj.LoadFromFile(path); - var bomChar = streamObj.ReadText(2); // Read the BOM char - streamObj.Position = 0; // Position has to be at 0 before changing the encoding - if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) - || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { - streamObj.Charset = 'unicode'; - } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { - streamObj.Charset = 'utf-8'; - } - - // Read the whole file - var str = streamObj.ReadText(-1 /* read from the current position to EOS */); - streamObj.Close(); - releaseStreamObject(streamObj); - return str; - } - catch (err) { - IOUtils.throwIOError("Error reading file \"" + path + "\".", err); - } - }, - - writeFile: function(path, contents) { - var file = this.createFile(path); - file.Write(contents); - file.Close(); - }, - - fileExists: function(path: string): boolean { - return fso.FileExists(path); - }, - - resolvePath: function(path: string): string { - return fso.GetAbsolutePathName(path); - }, - - dirName: function(path: string): string { - return fso.GetParentFolderName(path); - }, - - findFile: function(rootPath: string, partialFilePath: string): IResolvedFile { - var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; - - while (true) { - if (fso.FileExists(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } - catch (err) { - //Tools.CompilerDiagnostics.debugPrint("Could not find " + path + ", trying parent"); - } - } - else { - rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); - - if (rootPath == "") { - return null; - } - else { - path = fso.BuildPath(rootPath, partialFilePath); - } - } - } - }, - - deleteFile: function(path: string): void { - try { - if (fso.FileExists(path)) { - fso.DeleteFile(path, true); // true: delete read-only files - } - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - - createFile: function (path, useUTF8?) { - try { - var streamObj = getStreamObject(); - streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; - streamObj.Open(); - return { - Write: function (str) { streamObj.WriteText(str, 0); }, - WriteLine: function (str) { streamObj.WriteText(str, 1); }, - Close: function() { - try { - streamObj.SaveToFile(path, 2); - } catch (saveError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); - } - finally { - if (streamObj.State != 0 /*adStateClosed*/) { - streamObj.Close(); - } - releaseStreamObject(streamObj); - } - } - }; - } catch (creationError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); - } - }, - - directoryExists: function(path) { - return fso.FolderExists(path); - }, - - createDirectory: function(path) { - try { - if (!this.directoryExists(path)) { - fso.CreateFolder(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - - dir: function(path, spec?, options?) { - options = options || <{ recursive?: boolean; deep?: number; }>{}; - function filesInFolder(folder, root): string[]{ - var paths = []; - var fc: Enumerator; - - if (options.recursive) { - fc = new Enumerator(folder.subfolders); - - for (; !fc.atEnd() ; fc.moveNext()) { - paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); - } - } - - fc = new Enumerator(folder.files); - - for (; !fc.atEnd() ; fc.moveNext()) { - if (!spec || fc.item().Name.match(spec)) { - paths.push(root + "/" + fc.item().Name); - } - } - - return paths; - } - - var folder = fso.GetFolder(path); - var paths = []; - - return filesInFolder(folder, path); - }, - - print: function(str) { - WScript.StdOut.Write(str); - }, - - printLine: function(str) { - WScript.Echo(str); - }, - - arguments: args, - stderr: WScript.StdErr, - stdout: WScript.StdOut, - watchFile: null, - run: function(source, filename) { - try { - eval(source); - } catch (e) { - IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); - } - }, - getExecutingFilePath: function () { - return WScript.ScriptFullName; - }, - quit: function (exitCode : number = 0) { - try { - WScript.Quit(exitCode); - } catch (e) { - } - } - } - - }; - - // Create an IO object for use inside Node.js hosts - // Depends on 'fs' and 'path' modules - function getNodeIO(): IIO { - - var _fs = require('fs'); - var _path = require('path'); - var _module = require('module'); - - return { - readFile: function(file) { - try { - var buffer = _fs.readFileSync(file); - switch (buffer[0]) { - case 0xFE: - if (buffer[1] == 0xFF) { - // utf16-be. Reading the buffer as big endian is not supported, so convert it to - // Little Endian first - var i = 0; - while ((i + 1) < buffer.length) { - var temp = buffer[i] - buffer[i] = buffer[i + 1]; - buffer[i + 1] = temp; - i += 2; - } - return buffer.toString("ucs2", 2); - } - break; - case 0xFF: - if (buffer[1] == 0xFE) { - // utf16-le - return buffer.toString("ucs2", 2); - } - break; - case 0xEF: - if (buffer[1] == 0xBB) { - // utf-8 - return buffer.toString("utf8", 3); - } - } - // Default behaviour - return buffer.toString(); - } catch (e) { - IOUtils.throwIOError("Error reading file \"" + file + "\".", e); - } - }, - writeFile: <(path: string, contents: string) => void >_fs.writeFileSync, - deleteFile: function(path) { - try { - _fs.unlinkSync(path); - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - fileExists: function(path): boolean { - return _fs.existsSync(path); - }, - createFile: function(path, useUTF8?) { - function mkdirRecursiveSync(path) { - var stats = _fs.statSync(path); - if (stats.isFile()) { - IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); - } else if (stats.isDirectory()) { - return; - } else { - mkdirRecursiveSync(_path.dirname(path)); - _fs.mkdirSync(path, 0775); - } - } - - mkdirRecursiveSync(_path.dirname(path)); - - try { - var fd = _fs.openSync(path, 'w'); - } catch (e) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); - } - return { - Write: function(str) { _fs.writeSync(fd, str); }, - WriteLine: function(str) { _fs.writeSync(fd, str + '\r\n'); }, - Close: function() { _fs.closeSync(fd); fd = null; } - }; - }, - dir: function dir(path, spec?, options?) { - options = options || <{ recursive?: boolean; deep?: number; }>{}; - - function filesInFolder(folder: string, deep?: number): string[]{ - var paths = []; - - var files = _fs.readdirSync(folder); - for (var i = 0; i < files.length; i++) { - var stat = _fs.statSync(folder + "/" + files[i]); - if (options.recursive && stat.isDirectory()) { - if (deep < (options.deep || 100)) { - paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); - } - } else if (stat.isFile() && (!spec || files[i].match(spec))) { - paths.push(folder + "/" + files[i]); - } - } - - return paths; - } - - return filesInFolder(path, 0); - }, - createDirectory: function(path: string): void { - try { - if (!this.directoryExists(path)) { - _fs.mkdirSync(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - - directoryExists: function(path: string): boolean { - return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); - }, - resolvePath: function(path: string): string { - return _path.resolve(path); - }, - dirName: function(path: string): string { - return _path.dirname(path); - }, - findFile: function(rootPath: string, partialFilePath): IResolvedFile { - var path = rootPath + "/" + partialFilePath; - - while (true) { - if (_fs.existsSync(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } catch (err) { - //Tools.CompilerDiagnostics.debugPrint(("Could not find " + path) + ", trying parent"); - } - } - else { - var parentPath = _path.resolve(rootPath, ".."); - - // Node will just continue to repeat the root path, rather than return null - if (rootPath === parentPath) { - return null; - } - else { - rootPath = parentPath; - path = _path.resolve(rootPath, partialFilePath); - } - } - } - }, - print: function(str) { process.stdout.write(str) }, - printLine: function(str) { process.stdout.write(str + '\n') }, - arguments: process.argv.slice(2), - stderr: { - Write: function(str) { process.stderr.write(str); }, - WriteLine: function(str) { process.stderr.write(str + '\n'); }, - Close: function() { } - }, - stdout: { - Write: function(str) { process.stdout.write(str); }, - WriteLine: function(str) { process.stdout.write(str + '\n'); }, - Close: function() { } - }, - watchFile: function(filename: string, callback: (string) => void ): IFileWatcher { - var firstRun = true; - var processingChange = false; - - var fileChanged: any = function(curr, prev) { - if (!firstRun) { - if (curr.mtime < prev.mtime) { - return; - } - - _fs.unwatchFile(filename, fileChanged); - if (!processingChange) { - processingChange = true; - callback(filename); - setTimeout(function() { processingChange = false; }, 100); - } - } - firstRun = false; - _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); - }; - - fileChanged(); - return { - filename: filename, - close: function() { - _fs.unwatchFile(filename, fileChanged); - } - }; - }, - run: function(source, filename) { - require.main.filename = filename; - require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); - require.main._compile(source, filename); - }, - getExecutingFilePath: function () { - return process.mainModule.filename; - }, - quit: process.exit - } - }; - - if (typeof ActiveXObject === "function") - return getWindowsScriptHostIO(); - else if (typeof require === "function") - return getNodeIO(); - else - return null; // Unsupported host -})(); diff --git a/_infrastructure/tests/src/printer.ts b/_infrastructure/tests/src/printer.ts new file mode 100644 index 0000000000..9ee01f3c6d --- /dev/null +++ b/_infrastructure/tests/src/printer.ts @@ -0,0 +1,281 @@ +/// +/// + +module DT { + + var os = require('os'); + + ///////////////////////////////// + // All the common things that we print are functions of this class + ///////////////////////////////// + export class Print { + + WIDTH = 77; + + typings: number; + tests: number; + tsFiles: number + + constructor(public version: string){ + + } + + public init(typings: number, tests: number, tsFiles: number) { + this.typings = typings; + this.tests = tests; + this.tsFiles = tsFiles; + } + + public out(s: any): Print { + process.stdout.write(s); + return this; + } + + public repeat(s: string, times: number): string { + return new Array(times + 1).join(s); + } + + public printChangeHeader() { + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mDefinitelyTyped Diff Detector 0.1.0\33[0m \n'); + this.out('=============================================================================\n'); + } + + public printHeader(options: ITestRunnerOptions) { + var totalMem = Math.round(os.totalmem() / 1024 / 1024) + ' mb'; + var freemem = Math.round(os.freemem() / 1024 / 1024) + ' mb'; + + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mDefinitelyTyped Test Runner 0.5.0\33[0m\n'); + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); + this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); + this.out(' \33[36m\33[1mTests :\33[0m ' + this.tests + '\n'); + this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); + this.out(' \33[36m\33[1mTotal Memory :\33[0m ' + totalMem + '\n'); + this.out(' \33[36m\33[1mFree Memory :\33[0m ' + freemem + '\n'); + this.out(' \33[36m\33[1mCores :\33[0m ' + os.cpus().length + '\n'); + this.out(' \33[36m\33[1mConcurrent :\33[0m ' + options.concurrent + '\n'); + } + + public printSuiteHeader(title: string) { + var left = Math.floor((this.WIDTH - title.length ) / 2) - 1; + var right = Math.ceil((this.WIDTH - title.length ) / 2) - 1; + this.out(this.repeat('=', left)).out(' \33[34m\33[1m'); + this.out(title); + this.out('\33[0m ').out(this.repeat('=', right)).printBreak(); + } + + public printDiv() { + this.out('-----------------------------------------------------------------------------\n'); + } + + public printBoldDiv() { + this.out('=============================================================================\n'); + } + + public printErrorsHeader() { + this.out('=============================================================================\n'); + this.out(' \33[34m\33[1mErrors in files\33[0m \n'); + this.out('=============================================================================\n'); + } + + public printErrorsForFile(testResult: TestResult) { + this.out('----------------- For file:' + testResult.targetFile.filePathWithName); + this.printBreak().out(testResult.stderr).printBreak(); + } + + public printBreak(): Print { + this.out('\n'); + return this; + } + + public clearCurrentLine(): Print { + this.out('\r\33[K'); + return this; + } + + public printSuccessCount(current: number, total: number) { + var arb = (total === 0) ? 0 : (current / total); + this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printFailedCount(current: number, total: number) { + var arb = (total === 0) ? 0 : (current / total); + this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printTypingsWithoutTestsMessage() { + this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); + } + + public printTotalMessage() { + this.out(' \33[36m\33[1mTotal\33[0m\n'); + } + + public printElapsedTime(time: string, s: number) { + this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); + } + + public printSuiteErrorCount(errorHeadline: string, current: number, total: number, warn: boolean = false) { + var arb = (total === 0) ? 0 : (current / total); + this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length)); + if (warn) { + this.out(': \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + else { + this.out(': \33[33m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + } + + public printSubHeader(file: string) { + this.out(' \33[36m\33[1m' + file + '\33[0m\n'); + } + + public printWarnCode(str: string) { + this.out(' \33[31m\33[1m<' + str.toLowerCase().replace(/ +/g, '-') + '>\33[0m\n'); + } + + public printLine(file: string) { + this.out(file + '\n'); + } + + public printElement(file: string) { + this.out(' - ' + file + '\n'); + } + + public printElement2(file: string) { + this.out(' - ' + file + '\n'); + } + + public printTypingsWithoutTestName(file: string) { + this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); + } + + public printTypingsWithoutTest(withoutTestTypings: string[]) { + if (withoutTestTypings.length > 0) { + this.printTypingsWithoutTestsMessage(); + + this.printDiv(); + withoutTestTypings.forEach((t) => { + this.printTypingsWithoutTestName(t); + }); + } + } + + public printTestComplete(testResult: TestResult): void { + var reporter = testResult.hostedBy.testReporter; + if (testResult.success) { + reporter.printPositiveCharacter(testResult); + } + else { + reporter.printNegativeCharacter(testResult); + } + } + + public printSuiteComplete(suite: ITestSuite): void { + this.printBreak(); + + this.printDiv(); + this.printElapsedTime(suite.timer.asString, suite.timer.time); + this.printSuccessCount(suite.okTests.length, suite.testResults.length); + this.printFailedCount(suite.ngTests.length, suite.testResults.length); + } + + public printTests(adding: FileDict): void { + this.printDiv(); + this.printSubHeader('Testing'); + this.printDiv(); + + Object.keys(adding).sort().map((src) => { + this.printLine(adding[src].filePathWithName); + return adding[src]; + }); + } + + public printQueue(files: File[]): void { + this.printDiv(); + this.printSubHeader('Queued for testing'); + this.printDiv(); + + files.forEach((file) => { + this.printLine(file.filePathWithName); + }); + } + + public printTestAll(): void { + this.printDiv(); + this.printSubHeader('Ignoring changes, testing all files'); + } + + public printFiles(files: File[]): void { + this.printDiv(); + this.printSubHeader('Files'); + this.printDiv(); + + files.forEach((file) => { + this.printLine(file.filePathWithName); + file.references.forEach((file) => { + this.printElement(file.filePathWithName); + }); + }); + } + + public printMissing(index: FileIndex, refMap: FileArrDict): void { + this.printDiv(); + this.printSubHeader('Missing references'); + this.printDiv(); + + Object.keys(refMap).sort().forEach((src) => { + var ref = index.getFile(src); + this.printLine('\33[31m\33[1m' + ref.filePathWithName + '\33[0m'); + refMap[src].forEach((file) => { + this.printElement(file.filePathWithName); + }); + }); + } + + public printAllChanges(paths: string[]): void { + this.printSubHeader('All changes'); + this.printDiv(); + + paths.sort().forEach((line) => { + this.printLine(line); + }); + } + + public printRelChanges(changeMap: FileDict): void { + this.printDiv(); + this.printSubHeader('Interesting files'); + this.printDiv(); + + Object.keys(changeMap).sort().forEach((src) => { + this.printLine(changeMap[src].filePathWithName); + }); + } + + public printRemovals(changeMap: FileDict): void { + this.printDiv(); + this.printSubHeader('Removed files'); + this.printDiv(); + + Object.keys(changeMap).sort().forEach((src) => { + this.printLine(changeMap[src].filePathWithName); + }); + } + + public printRefMap(index: FileIndex, refMap: FileArrDict): void { + this.printDiv(); + this.printSubHeader('Referring'); + this.printDiv(); + + Object.keys(refMap).sort().forEach((src) => { + var ref = index.getFile(src); + this.printLine(ref.filePathWithName); + refMap[src].forEach((file) => { + this.printLine(' - ' + file.filePathWithName); + }); + }); + } + } +} diff --git a/_infrastructure/tests/src/reporter/reporter.ts b/_infrastructure/tests/src/reporter/reporter.ts new file mode 100644 index 0000000000..736ac413cc --- /dev/null +++ b/_infrastructure/tests/src/reporter/reporter.ts @@ -0,0 +1,42 @@ +/// +/// + +module DT { + ///////////////////////////////// + // Test reporter interface + // for example, . and x + ///////////////////////////////// + export interface ITestReporter { + printPositiveCharacter(testResult: TestResult):void; + printNegativeCharacter(testResult: TestResult):void; + } + + ///////////////////////////////// + // Default test reporter + ///////////////////////////////// + export class DefaultTestReporter implements ITestReporter { + + index = 0; + + constructor(public print: Print) { + } + + public printPositiveCharacter(testResult: TestResult) { + this.print.out('\33[36m\33[1m' + '.' + '\33[0m'); + this.index++; + this.printBreakIfNeeded(this.index); + } + + public printNegativeCharacter( testResult: TestResult) { + this.print.out('x'); + this.index++; + this.printBreakIfNeeded(this.index); + } + + private printBreakIfNeeded(index: number) { + if (index % this.print.WIDTH === 0) { + this.print.printBreak(); + } + } + } +} diff --git a/_infrastructure/tests/src/suite/suite.ts b/_infrastructure/tests/src/suite/suite.ts new file mode 100644 index 0000000000..8624da0d37 --- /dev/null +++ b/_infrastructure/tests/src/suite/suite.ts @@ -0,0 +1,82 @@ +/// + +module DT { + 'use strict'; + + var Promise: typeof Promise = require('bluebird'); + + ///////////////////////////////// + // The interface for test suite + ///////////////////////////////// + export interface ITestSuite { + testSuiteName:string; + errorHeadline:string; + filterTargetFiles(files: File[]): Promise; + + start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void): Promise; + + testResults:TestResult[]; + okTests:TestResult[]; + ngTests:TestResult[]; + timer:Timer; + + testReporter:ITestReporter; + printErrorCount:boolean; + } + + ///////////////////////////////// + // Base class for test suite + ///////////////////////////////// + export class TestSuiteBase implements ITestSuite { + timer: Timer = new Timer(); + testResults: TestResult[] = []; + testReporter: ITestReporter; + printErrorCount = true; + queue: TestQueue; + + constructor(public options: ITestRunnerOptions, public testSuiteName: string, public errorHeadline: string) { + this.queue = new TestQueue(options.concurrent); + } + + public filterTargetFiles(files: File[]): Promise { + throw new Error('please implement this method'); + } + + public start(targetFiles: File[], testCallback: (result: TestResult) => void): Promise { + this.timer.start(); + + return this.filterTargetFiles(targetFiles).then((targetFiles) => { + // tests get queued for multi-threading + return Promise.all(targetFiles.map((targetFile) => { + return this.runTest(targetFile).then((result) => { + testCallback(result); + }); + })); + }).then(() => { + this.timer.end(); + return this; + }); + } + + public runTest(targetFile: File): Promise { + return this.queue.run(new Test(this, targetFile, { + tscVersion: this.options.tscVersion + })).then((result) => { + this.testResults.push(result); + return result; + }); + } + + public get okTests(): TestResult[] { + return this.testResults.filter((r) => { + return r.success; + }); + } + + public get ngTests(): TestResult[] { + return this.testResults.filter((r) => { + return !r.success + }); + } + } +} diff --git a/_infrastructure/tests/src/suite/syntax.ts b/_infrastructure/tests/src/suite/syntax.ts new file mode 100644 index 0000000000..9211c3fdef --- /dev/null +++ b/_infrastructure/tests/src/suite/syntax.ts @@ -0,0 +1,26 @@ +/// +/// + +module DT { + 'use strict'; + + var Promise: typeof Promise = require('bluebird'); + + var endDts = /\w\.ts$/i; + + ///////////////////////////////// + // .d.ts syntax inspection + ///////////////////////////////// + export class SyntaxChecking extends TestSuiteBase { + + constructor(options: ITestRunnerOptions) { + super(options, 'Syntax checking', 'Syntax error'); + } + + public filterTargetFiles(files: File[]): Promise { + return Promise.cast(files.filter((file) => { + return endDts.test(file.filePathWithName); + })); + } + } +} diff --git a/_infrastructure/tests/src/suite/testEval.ts b/_infrastructure/tests/src/suite/testEval.ts new file mode 100644 index 0000000000..abc4d50935 --- /dev/null +++ b/_infrastructure/tests/src/suite/testEval.ts @@ -0,0 +1,26 @@ +/// +/// + +module DT { + 'use strict'; + + var Promise: typeof Promise = require('bluebird'); + + var endTestDts = /\w-tests?\.ts$/i; + + ///////////////////////////////// + // Compile with *-tests.ts + ///////////////////////////////// + export class TestEval extends TestSuiteBase { + + constructor(options) { + super(options, 'Typing tests', 'Failed tests'); + } + + public filterTargetFiles(files: File[]): Promise { + return Promise.cast(files.filter((file) => { + return endTestDts.test(file.filePathWithName); + })); + } + } +} diff --git a/_infrastructure/tests/src/suite/tscParams.ts b/_infrastructure/tests/src/suite/tscParams.ts new file mode 100644 index 0000000000..12e3f46017 --- /dev/null +++ b/_infrastructure/tests/src/suite/tscParams.ts @@ -0,0 +1,59 @@ +/// +/// + +module DT { + 'use strict'; + + var fs = require('fs'); + var Promise: typeof Promise = require('bluebird'); + + ///////////////////////////////// + // Try compile without .tscparams + // It may indicate that it is compatible with --noImplicitAny maybe... + ///////////////////////////////// + export class FindNotRequiredTscparams extends TestSuiteBase { + testReporter: ITestReporter; + printErrorCount = false; + + constructor(options: ITestRunnerOptions, private print: Print) { + super(options, 'Find not required .tscparams files', 'New arrival!'); + + this.testReporter = { + printPositiveCharacter: (testResult: TestResult) => { + this.print + .clearCurrentLine() + .printTypingsWithoutTestName(testResult.targetFile.filePathWithName); + }, + printNegativeCharacter: (testResult: TestResult) => { + } + } + } + + public filterTargetFiles(files: File[]): Promise { + return Promise.filter(files, (file) => { + return new Promise((resolve) => { + fs.exists(file.filePathWithName + '.tscparams', resolve); + }); + }); + } + + public runTest(targetFile: File): Promise { + this.print.clearCurrentLine().out(targetFile.filePathWithName); + + return this.queue.run(new Test(this, targetFile, { + tscVersion: this.options.tscVersion, + useTscParams: false, + checkNoImplicitAny: true + })).then((result) => { + this.testResults.push(result); + this.print.clearCurrentLine(); + return result + }); + } + + public get ngTests(): TestResult[] { + // Do not show ng test results + return []; + } + } +} diff --git a/_infrastructure/tests/src/timer.ts b/_infrastructure/tests/src/timer.ts new file mode 100644 index 0000000000..0f74743471 --- /dev/null +++ b/_infrastructure/tests/src/timer.ts @@ -0,0 +1,50 @@ +/// +/// + +module DT { + 'use strict'; + + ///////////////////////////////// + // Timer.start starts a timer + // Timer.end stops the timer and sets asString to the pretty print value + ///////////////////////////////// + export class Timer { + startTime: number; + time = 0; + asString: string = '' + + public start() { + this.time = 0; + this.startTime = this.now(); + this.asString = ''; + } + + public now(): number { + return Date.now(); + } + + public end() { + this.time = (this.now() - this.startTime) / 1000; + this.asString = Timer.prettyDate(this.startTime, this.now()); + } + + public static prettyDate(date1: number, date2: number): string { + var diff = ((date2 - date1) / 1000); + var day_diff = Math.floor(diff / 86400); + + if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) { + return null; + } + + return ( (day_diff == 0 && ( + diff < 60 && (diff + ' seconds') || + diff < 120 && '1 minute' || + diff < 3600 && Math.floor(diff / 60) + ' minutes' || + diff < 7200 && '1 hour' || + diff < 86400 && Math.floor(diff / 3600) + ' hours') || + day_diff == 1 && 'Yesterday' || + day_diff < 7 && day_diff + ' days' || + day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks')); + } + } +} diff --git a/_infrastructure/tests/src/tsc.ts b/_infrastructure/tests/src/tsc.ts new file mode 100644 index 0000000000..9730a1394c --- /dev/null +++ b/_infrastructure/tests/src/tsc.ts @@ -0,0 +1,54 @@ +/// +/// +/// + +module DT { + 'use strict'; + + var fs = require('fs'); + + var Promise: typeof Promise = require('bluebird'); + + export interface TscExecOptions { + tscVersion?:string; + useTscParams?:boolean; + checkNoImplicitAny?:boolean; + } + + export class Tsc { + public static run(tsfile: string, options: TscExecOptions): Promise { + var tscPath; + return new Promise.attempt(() => { + options = options || {}; + options.tscVersion = options.tscVersion || DEFAULT_TSC_VERSION; + if (typeof options.checkNoImplicitAny === 'undefined') { + options.checkNoImplicitAny = true; + } + if (typeof options.useTscParams === 'undefined') { + options.useTscParams = true; + } + return fileExists(tsfile); + }).then((exists) => { + if (!exists) { + throw new Error(tsfile + ' not exists'); + } + tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js'; + return fileExists(tscPath); + }).then((exists) => { + if (!exists) { + throw new Error(tscPath + ' is not exists'); + } + return fileExists(tsfile + '.tscparams'); + }).then((exists) => { + var command = 'node ' + tscPath + ' --module commonjs '; + if (options.useTscParams && exists) { + command += '@' + tsfile + '.tscparams'; + } + else if (options.checkNoImplicitAny) { + command += '--noImplicitAny'; + } + return exec(command, [tsfile]); + }); + } + } +} diff --git a/_infrastructure/tests/src/util.ts b/_infrastructure/tests/src/util.ts new file mode 100644 index 0000000000..a712bb90cd --- /dev/null +++ b/_infrastructure/tests/src/util.ts @@ -0,0 +1,40 @@ +/// + +module DT { + 'use strict'; + + var fs = require('fs'); + var Lazy: LazyJS.LazyStatic = require('lazy.js'); + var Promise: typeof Promise = require('bluebird'); + + var referenceTagExp = //g; + + export function endsWith(str: string, suffix: string) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + export function extractReferenceTags(source: string): string[] { + var ret: string[] = []; + var match: RegExpExecArray; + + if (!referenceTagExp.global) { + throw new Error('referenceTagExp RegExp must have global flag'); + } + referenceTagExp.lastIndex = 0; + + while ((match = referenceTagExp.exec(source))) { + if (match.length > 0 && match[1].length > 0) { + ret.push(match[1]); + } + } + return ret; + } + + export function fileExists(target: string): Promise { + return new Promise((resolve, reject) => { + fs.exists(target, (bool: boolean) => { + resolve(bool); + }); + }); + } +} diff --git a/_infrastructure/tests/typescript/0.9.5-beta/lib.d.ts b/_infrastructure/tests/typescript/0.9.7/lib.d.ts similarity index 74% rename from _infrastructure/tests/typescript/0.9.5-beta/lib.d.ts rename to _infrastructure/tests/typescript/0.9.7/lib.d.ts index b0b5c96dd3..94c477fd4a 100644 --- a/_infrastructure/tests/typescript/0.9.5-beta/lib.d.ts +++ b/_infrastructure/tests/typescript/0.9.7/lib.d.ts @@ -70,7 +70,7 @@ declare function decodeURIComponent(encodedURIComponent: string): string; /** * Encodes a text string as a valid Uniform Resource Identifier (URI) * @param uri A value representing an encoded URI. - */ + */ declare function encodeURI(uri: string): string; /** @@ -93,9 +93,12 @@ interface PropertyDescriptorMap { } interface Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + /** Returns a string representation of an object. */ toString(): string; - + /** Returns a date converted to a string using the current locale. */ toLocaleString(): string; @@ -368,7 +371,7 @@ interface String { * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. * If this value is not specified, the substring continues to the end of stringObj. */ - slice(start: number, end?: number): string; + slice(start?: number, end?: number): string; /** * Split a string into substrings using the specified separator and return them as an array. @@ -461,7 +464,7 @@ interface Number { /** * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. - */ + */ toPrecision(precision?: number): string; } @@ -522,7 +525,7 @@ interface Math { /** * Returns the arc cosine (or inverse cosine) of a number. * @param x A numeric expression. - */ + */ acos(x: number): number; /** * Returns the arcsine of a number. @@ -548,7 +551,7 @@ interface Math { /** * Returns the cosine of a number. * @param x A numeric expression that contains an angle measured in radians. - */ + */ cos(x: number): number; /** * Returns e (the base of natural logarithms) raised to a power. @@ -581,7 +584,7 @@ interface Math { * @param y The exponent value of the expression. */ pow(x: number, y: number): number; - /** Returns a pseudorandom number between 0 and 1. */ + /** Returns a pseudorandom number between 0 and 1. */ random(): number; /** * Returns a supplied numeric expression rounded to the nearest number. @@ -663,44 +666,44 @@ interface Date { * Sets the date and time value in the Date object. * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. */ - setTime(time: number): void; + setTime(time: number): number; /** * Sets the milliseconds value in the Date object using local time. * @param ms A numeric value equal to the millisecond value. */ - setMilliseconds(ms: number): void; + setMilliseconds(ms: number): number; /** * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). * @param ms A numeric value equal to the millisecond value. */ - setUTCMilliseconds(ms: number): void; + setUTCMilliseconds(ms: number): number; /** * Sets the seconds value in the Date object using local time. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ - setSeconds(sec: number, ms?: number): void; + setSeconds(sec: number, ms?: number): number; /** * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ - setUTCSeconds(sec: number, ms?: number): void; + setUTCSeconds(sec: number, ms?: number): number; /** * Sets the minutes value in the Date object using local time. * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ - setMinutes(min: number, sec?: number, ms?: number): void; + setMinutes(min: number, sec?: number, ms?: number): number; /** * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ - setUTCMinutes(min: number, sec?: number, ms?: number): void; + setUTCMinutes(min: number, sec?: number, ms?: number): number; /** * Sets the hour value in the Date object using local time. * @param hours A numeric value equal to the hours value. @@ -708,7 +711,7 @@ interface Date { * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ - setHours(hours: number, min?: number, sec?: number, ms?: number): void; + setHours(hours: number, min?: number, sec?: number, ms?: number): number; /** * Sets the hours value in the Date object using Universal Coordinated Time (UTC). * @param hours A numeric value equal to the hours value. @@ -716,43 +719,43 @@ interface Date { * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ - setUTCHours(hours: number, min?: number, sec?: number, ms?: number): void; + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; /** * Sets the numeric day-of-the-month value of the Date object using local time. * @param date A numeric value equal to the day of the month. */ - setDate(date: number): void; + setDate(date: number): number; /** * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). * @param date A numeric value equal to the day of the month. */ - setUTCDate(date: number): void; + setUTCDate(date: number): number; /** * Sets the month value in the Date object using local time. * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. */ - setMonth(month: number, date?: number): void; + setMonth(month: number, date?: number): number; /** * Sets the month value in the Date object using Universal Coordinated Time (UTC). * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. */ - setUTCMonth(month: number, date?: number): void; + setUTCMonth(month: number, date?: number): number; /** * Sets the year of the Date object using local time. * @param year A numeric value for the year. * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. * @param date A numeric value equal for the day of the month. */ - setFullYear(year: number, month?: number, date?: number): void; + setFullYear(year: number, month?: number, date?: number): number; /** * Sets the year value in the Date object using Universal Coordinated Time (UTC). * @param year A numeric value equal to the year. * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. * @param date A numeric value equal to the day of the month. */ - setUTCFullYear(year: number, month?: number, date?: number): void; + setUTCFullYear(year: number, month?: number, date?: number): number; /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ toUTCString(): string; /** Returns a date as a string value in ISO format. */ @@ -802,7 +805,7 @@ interface RegExpExecArray { push(...items: string[]): number; reverse(): string[]; shift(): string; - slice(start: number, end?: number): string[]; + slice(start?: number, end?: number): string[]; sort(compareFn?: (a: string, b: string) => number): string[]; splice(start: number): string[]; splice(start: number, deleteCount: number, ...items: string[]): string[]; @@ -826,7 +829,7 @@ interface RegExp { * @param string The String object or string literal on which to perform the search. */ exec(string: string): RegExpExecArray; - + /** * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. * @param string String on which to perform the search. @@ -835,7 +838,7 @@ interface RegExp { /** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */ source: string; - + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ global: boolean; @@ -1018,7 +1021,7 @@ interface Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ - slice(start: number, end?: number): T[]; + slice(start?: number, end?: number): T[]; /** * Sorts an array. @@ -1129,7 +1132,7 @@ interface Array { [n: number]: T; } declare var Array: { - new(arrayLength?: number): any[]; + new (arrayLength?: number): any[]; new (arrayLength: number): T[]; new (...items: T[]): T[]; (arrayLength?: number): any[]; @@ -1913,13 +1916,13 @@ interface String { } interface Number { - toLocaleString(locales: string[], options?: Intl.NumberFormatOptions): string; - toLocaleString(locale: string, options?: Intl.NumberFormatOptions): string; + toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string; + toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string; } interface Date { - toLocaleString(locales: string[], options?: Intl.DateTimeFormatOptions): string; - toLocaleString(locale: string, options?: Intl.DateTimeFormatOptions): string; + toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string; } @@ -3346,11 +3349,9 @@ declare var ControlRangeCollection: { interface MSNamespaceInfo extends MSEventAttachmentTarget { urn: string; onreadystatechange: (ev: Event) => any; - addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; name: string; readyState: string; doImport(implementationUrl: string): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var MSNamespaceInfo: { prototype: MSNamespaceInfo; @@ -3484,149 +3485,89 @@ declare var SVGAnimatedLengthList: { interface Window extends EventTarget, MSEventAttachmentTarget, WindowLocalStorage, MSWindowExtensions, WindowSessionStorage, WindowTimers { ondragend: (ev: DragEvent) => any; - addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onkeydown: (ev: KeyboardEvent) => any; - addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; ondragover: (ev: DragEvent) => any; - addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onkeyup: (ev: KeyboardEvent) => any; - addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; onreset: (ev: Event) => any; - addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; onmouseup: (ev: MouseEvent) => any; - addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondragstart: (ev: DragEvent) => any; - addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; ondrag: (ev: DragEvent) => any; - addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; screenX: number; onmouseover: (ev: MouseEvent) => any; - addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondragleave: (ev: DragEvent) => any; - addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; history: History; pageXOffset: number; name: string; onafterprint: (ev: Event) => any; - addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; onpause: (ev: Event) => any; - addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeprint: (ev: Event) => any; - addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; top: Window; onmousedown: (ev: MouseEvent) => any; - addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onseeked: (ev: Event) => any; - addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; opener: Window; onclick: (ev: MouseEvent) => any; - addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; innerHeight: number; onwaiting: (ev: Event) => any; - addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; ononline: (ev: Event) => any; - addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; ondurationchange: (ev: Event) => any; - addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; frames: Window; onblur: (ev: FocusEvent) => any; - addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onemptied: (ev: Event) => any; - addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; onseeking: (ev: Event) => any; - addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; oncanplay: (ev: Event) => any; - addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; outerWidth: number; onstalled: (ev: Event) => any; - addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; onmousemove: (ev: MouseEvent) => any; - addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; innerWidth: number; onoffline: (ev: Event) => any; - addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; length: number; screen: Screen; onbeforeunload: (ev: BeforeUnloadEvent) => any; - addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; onratechange: (ev: Event) => any; - addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; onstorage: (ev: StorageEvent) => any; - addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; onloadstart: (ev: Event) => any; - addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; ondragenter: (ev: DragEvent) => any; - addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onsubmit: (ev: Event) => any; - addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; self: Window; document: Document; onprogress: (ev: any) => any; - addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; ondblclick: (ev: MouseEvent) => any; - addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; pageYOffset: number; oncontextmenu: (ev: MouseEvent) => any; - addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onchange: (ev: Event) => any; - addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; onloadedmetadata: (ev: Event) => any; - addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; onplay: (ev: Event) => any; - addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; onerror: ErrorEventHandler; onplaying: (ev: Event) => any; - addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; parent: Window; location: Location; oncanplaythrough: (ev: Event) => any; - addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; onabort: (ev: UIEvent) => any; - addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onreadystatechange: (ev: Event) => any; - addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; outerHeight: number; onkeypress: (ev: KeyboardEvent) => any; - addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; frameElement: Element; onloadeddata: (ev: Event) => any; - addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; onsuspend: (ev: Event) => any; - addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; window: Window; onfocus: (ev: FocusEvent) => any; - addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onmessage: (ev: MessageEvent) => any; - addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; ontimeupdate: (ev: Event) => any; - addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; onresize: (ev: UIEvent) => any; - addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onselect: (ev: UIEvent) => any; - addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; navigator: Navigator; styleMedia: StyleMedia; ondrop: (ev: DragEvent) => any; - addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onmouseout: (ev: MouseEvent) => any; - addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onended: (ev: Event) => any; - addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; onhashchange: (ev: Event) => any; - addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; onunload: (ev: Event) => any; - addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; onscroll: (ev: UIEvent) => any; - addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; screenY: number; onmousewheel: (ev: MouseWheelEvent) => any; - addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; onload: (ev: Event) => any; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onvolumechange: (ev: Event) => any; - addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; oninput: (ev: Event) => any; - addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; performance: Performance; alert(message?: any): void; scroll(x?: number, y?: number): void; @@ -3644,7 +3585,6 @@ interface Window extends EventTarget, MSEventAttachmentTarget, WindowLocalStorag blur(): void; getSelection(): Selection; getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var Window: { prototype: Window; @@ -3883,8 +3823,8 @@ declare var HTMLAreaElement: { } interface EventTarget { - removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; dispatchEvent(evt: Event): boolean; } @@ -4009,33 +3949,11 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document * @param ev The keyboard event */ onkeydown: (ev: KeyboardEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; /** * Fires when the user releases a key. * @param ev The keyboard event */ onkeyup: (ev: KeyboardEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; /** * Gets the implementation object of the current document. @@ -4046,17 +3964,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document * @param ev The event. */ onreset: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Retrieves a collection of all script objects in the document. @@ -4068,34 +3975,12 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document * @param ev The event. */ onhelp: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. * @param ev The drag event. */ ondragleave: (ev: DragEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; /** * Gets or sets the character set used to encode the object. @@ -4108,17 +3993,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onfocusin: (ev: FocusEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; /** * Sets or gets the color of the links that the user has visited. @@ -4131,17 +4005,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onseeked: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; security: string; /** @@ -4180,17 +4043,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondurationchange: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Returns a reference to the collection of elements contained by the object. @@ -4208,17 +4060,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onblur: (ev: FocusEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; /** * Sets or retrieves a value that indicates the reading order of the object. @@ -4231,17 +4072,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onemptied: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Sets or gets a value that indicates whether the document can be edited. @@ -4254,17 +4084,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onseeking: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires when the activeElement is changed from the current object to another object in the parent document. @@ -4272,17 +4091,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondeactivate: (ev: UIEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; /** * Occurs when playback is possible, but would require further buffering. @@ -4290,17 +4098,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ oncanplay: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires when the data set exposed by a data source object changes. @@ -4308,17 +4105,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondatasetchanged: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Fires when rows are about to be deleted from the recordset. @@ -4326,17 +4112,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onrowsdelete: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; Script: MSScriptHost; /** @@ -4345,17 +4120,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onloadstart: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Gets the URL for the document, stripped of any character encoding. @@ -4370,17 +4134,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ oncontrolselect: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Fires on the target element when the user drags the object to a valid drop target. @@ -4388,29 +4141,7 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondragenter: (ev: DragEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onsubmit: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Returns the character encoding used to create the webpage that is loaded into the document object. @@ -4428,17 +4159,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onchange: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Retrieves a collection of all a objects that specify the href property and all area objects in the document. @@ -4461,32 +4181,10 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onbeforeactivate: (ev: UIEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; head: HTMLHeadElement; cookie: string; xmlEncoding: string; oncanplaythrough: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Retrieves the document compatibility mode of the document. @@ -4501,17 +4199,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document anchors: HTMLCollection; onbeforeupdate: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Fires to indicate that all data is available from the data source object. @@ -4519,17 +4206,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondatasetcomplete: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; plugins: HTMLCollection; /** @@ -4538,17 +4214,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onsuspend: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Gets the root svg element in the document hierarchy. @@ -4576,17 +4241,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onerrorupdate: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Gets a reference to the container object of the window. @@ -4599,17 +4253,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onmouseout: (ev: MouseEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; /** * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. @@ -4617,17 +4260,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onmsthumbnailclick: (ev: MSSiteModeEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "msthumbnailclick", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; /** * Fires when the wheel button is rotated. @@ -4635,17 +4267,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onmousewheel: (ev: MouseWheelEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; /** * Occurs when the volume is changed, or playback is muted or unmuted. @@ -4653,17 +4274,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onvolumechange: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires when data changes in the data provider. @@ -4671,17 +4281,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ oncellchange: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Fires just before the data source control changes the current row in the object. @@ -4689,17 +4288,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onrowexit: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Fires just after new rows are inserted in the current recordset. @@ -4707,17 +4295,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onrowsinserted: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Gets or sets the version attribute specified in the declaration of an XML document. @@ -4732,17 +4309,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onpropertychange: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Fires on the source object when the user releases the mouse at the close of a drag operation. @@ -4750,17 +4316,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondragend: (ev: DragEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; /** * Gets an object representing the document type declaration associated with the current document. @@ -4773,17 +4328,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondragover: (ev: DragEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; /** * Deprecated. Sets or retrieves a value that indicates the background color behind the object. @@ -4796,17 +4340,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondragstart: (ev: DragEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; /** * Fires when the user releases a mouse button while the mouse is over the object. @@ -4814,17 +4347,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onmouseup: (ev: MouseEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; /** * Fires on the source object continuously during a drag operation. @@ -4832,17 +4354,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondrag: (ev: DragEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; /** * Fires when the user moves the mouse pointer into the object. @@ -4850,17 +4361,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onmouseover: (ev: MouseEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; /** * Sets or gets the color of the document links. @@ -4873,17 +4373,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onpause: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires when the user clicks the object with either mouse button. @@ -4891,17 +4380,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onmousedown: (ev: MouseEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; /** * Fires when the user clicks the left mouse button on the object @@ -4909,17 +4387,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onclick: (ev: MouseEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; /** * Occurs when playback stops because the next frame of a video resource is not available. @@ -4927,17 +4394,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onwaiting: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires when the user clicks the Stop button or leaves the Web page. @@ -4946,16 +4402,8 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document onstop: (ev: Event) => any; /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. * false (false)[rolls - * Register the event handler for the bubbling phase. */ - addEventListener(type: "stop", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. @@ -4963,17 +4411,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "mssitemodejumplistitemremoved", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; /** * Retrieves a collection of all applet objects in the document. @@ -5003,17 +4440,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onstalled: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires when the user moves the mouse over the object. @@ -5021,17 +4447,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onmousemove: (ev: MouseEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; /** * Gets a reference to the root node of the document. @@ -5044,17 +4459,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onbeforeeditfocus: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Occurs when the playback rate is increased or decreased. @@ -5062,17 +4466,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onratechange: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Occurs to indicate progress while downloading media data. @@ -5080,17 +4473,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onprogress: (ev: any) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; /** * Fires when the user double-clicks the object. @@ -5098,17 +4480,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondblclick: (ev: MouseEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; /** * Fires when the user clicks the right mouse button in the client area, opening the context menu. @@ -5116,17 +4487,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ oncontextmenu: (ev: MouseEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; /** * Occurs when the duration and dimensions of the media have been determined. @@ -5134,17 +4494,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onloadedmetadata: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; media: string; /** @@ -5153,17 +4502,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onerror: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Occurs when the play method is requested. @@ -5171,29 +4509,7 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onplay: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; onafterupdate: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Occurs when the audio or video has started playing. @@ -5201,17 +4517,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onplaying: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Retrieves a collection, in source order, of img objects in the document. @@ -5229,17 +4534,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onabort: (ev: UIEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; /** * Fires for the current element with focus immediately after moving focus to another element. @@ -5247,17 +4541,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onfocusout: (ev: FocusEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; /** * Fires when the selection state of a document changes. @@ -5265,17 +4548,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onselectionchange: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "selectionchange", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires when a local DOM Storage area is written to disk. @@ -5283,17 +4555,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onstoragecommit: (ev: StorageEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "storagecommit", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; /** * Fires periodically as data arrives from data source objects that asynchronously transmit their data. @@ -5301,17 +4562,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ondataavailable: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Fires when the state of the object has changed. @@ -5319,17 +4569,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onreadystatechange: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Gets the date that the page was last modified, if the page supplies one. @@ -5342,17 +4581,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onkeypress: (ev: KeyboardEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; /** * Occurs when media data is loaded at the current playback position. @@ -5360,17 +4588,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onloadeddata: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires immediately before the activeElement is changed from the current object to another object in the parent document. @@ -5378,17 +4595,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onbeforedeactivate: (ev: UIEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; /** * Fires when the object is set as the active element. @@ -5396,30 +4602,8 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onactivate: (ev: UIEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onselectstart: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires when the object receives focus. @@ -5427,17 +4611,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onfocus: (ev: FocusEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; /** * Sets or gets the foreground (text) color of the document. @@ -5450,17 +4623,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ ontimeupdate: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Fires when the current selection changes. @@ -5468,29 +4630,7 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onselect: (ev: UIEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ondrop: (ev: DragEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; /** * Occurs when the end of playback is reached. @@ -5498,17 +4638,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onended: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Gets a value that indicates whether standards-compliant mode is switched on for the object. @@ -5521,17 +4650,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onscroll: (ev: UIEvent) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; /** * Fires to indicate that the current row has changed in the data source and new data values are available on the object. @@ -5539,17 +4657,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onrowenter: (ev: MSEventObj) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; /** * Fires immediately after the browser loads the object. @@ -5557,29 +4664,7 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document */ onload: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; oninput: (ev: Event) => any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event to register - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Returns the current value of the document, range, or current selection for the given command. @@ -6151,7 +5236,7 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document * @param tagName The name of an element. */ createElement(tagName: string): HTMLElement; - + /** * Removes mouse capture from the object in the current document. */ @@ -6750,7 +5835,7 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document * @param name Specifies the name of an element. */ getElementsByTagName(name: string): NodeList; - + /** * Creates a new document. */ @@ -6823,29 +5908,6 @@ interface Document extends Node, NodeSelector, MSEventAttachmentTarget, Document * @param elementId String that specifies the ID value. Case-insensitive. */ getElementById(elementId: string): HTMLElement; - - /** - * Registers an event handler for the specified event type. - * @param type The type of event type to register. - * @param listener The event handler function to associate with the event. - * @param useCapture Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: "DOMContentLoaded", listener: (ev: Event) => any, useCapture?: boolean): void; - /** - * Registers an event handler for the specified event type. - * @param type The type of event type to register. - * @param listener The event handler function to associate with the event. - * @param useCapture Boolean value that specifies the event phase to add the event handler for: - * true (true) - * Register the event handler for the capturing phase. - * false (false) - * Register the event handler for the bubbling phase. - */ - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var Document: { @@ -6866,30 +5928,19 @@ declare var MessageEvent: { interface SVGElement extends Element { onmouseover: (ev: MouseEvent) => any; - addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; viewportElement: SVGElement; onmousemove: (ev: MouseEvent) => any; - addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onmouseout: (ev: MouseEvent) => any; - addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondblclick: (ev: MouseEvent) => any; - addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onfocusout: (ev: FocusEvent) => any; - addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onfocusin: (ev: FocusEvent) => any; - addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; xmlbase: string; onmousedown: (ev: MouseEvent) => any; - addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onload: (ev: Event) => any; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onmouseup: (ev: MouseEvent) => any; - addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onclick: (ev: MouseEvent) => any; - addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ownerSVGElement: SVGSVGElement; id: string; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var SVGElement: { prototype: SVGElement; @@ -7173,18 +6224,10 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument, MSDataBindingExt * Raised when the object has been completely received from the server. */ onload: (ev: Event) => any; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied. */ security: any; - /** - * Registers an event handler for the specified event type. - * @param type The type of event type to register. - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for. If true, register the event handler for the capturing phase. If false, Register the event handler for the bubbling phase. - */ - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLFrameElement: { prototype: HTMLFrameElement; @@ -7250,13 +6293,10 @@ interface XMLHttpRequest extends EventTarget { responseText: string; responseXML: Document; ontimeout: (ev: Event) => any; - addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; statusText: string; onreadystatechange: (ev: Event) => any; - addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; timeout: number; onload: (ev: Event) => any; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; open(method: string, url: string, async?: boolean, user?: string, password?: string): void; create(): XMLHttpRequest; send(data?: any): void; @@ -7264,7 +6304,6 @@ interface XMLHttpRequest extends EventTarget { getAllResponseHeaders(): string; setRequestHeader(header: string, value: string): void; getResponseHeader(header: string): string; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; LOADING: number; DONE: number; UNSENT: number; @@ -7343,7 +6382,6 @@ interface SVGTransformable extends SVGLocatable { interface HTMLFrameSetElement extends HTMLElement { ononline: (ev: Event) => any; - addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Sets or retrieves the border color of the object. */ @@ -7360,7 +6398,6 @@ interface HTMLFrameSetElement extends HTMLElement { * Fires when the object loses the input focus. */ onblur: (ev: FocusEvent) => any; - addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; /** * Sets or retrieves the amount of additional space between the frames. */ @@ -7369,36 +6406,23 @@ interface HTMLFrameSetElement extends HTMLElement { * Fires when the object receives focus. */ onfocus: (ev: FocusEvent) => any; - addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onmessage: (ev: MessageEvent) => any; - addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; onerror: (ev: Event) => any; - addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; /** * Sets or retrieves whether to display a border for the frame. */ frameBorder: string; onresize: (ev: UIEvent) => any; - addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; name: string; onafterprint: (ev: Event) => any; - addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeprint: (ev: Event) => any; - addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; onoffline: (ev: Event) => any; - addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; border: string; onunload: (ev: Event) => any; - addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; onhashchange: (ev: Event) => any; - addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; onload: (ev: Event) => any; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeunload: (ev: BeforeUnloadEvent) => any; - addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; onstorage: (ev: StorageEvent) => any; - addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLFrameSetElement: { prototype: HTMLFrameSetElement; @@ -7552,26 +6576,20 @@ interface SVGSVGElement extends SVGElement, SVGStylable, SVGZoomAndPan, Document x: SVGAnimatedLength; contentStyleType: string; onzoom: (ev: any) => any; - addEventListener(type: "zoom", listener: (ev: any) => any, useCapture?: boolean): void; y: SVGAnimatedLength; viewport: SVGRect; onerror: (ev: Event) => any; - addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; pixelUnitToMillimeterY: number; onresize: (ev: UIEvent) => any; - addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; screenPixelToMillimeterY: number; height: SVGAnimatedLength; onabort: (ev: UIEvent) => any; - addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; contentScriptType: string; pixelUnitToMillimeterX: number; currentTranslate: SVGPoint; onunload: (ev: Event) => any; - addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; currentScale: number; onscroll: (ev: UIEvent) => any; - addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; screenPixelToMillimeterX: number; setCurrentTime(seconds: number): void; createSVGLength(): SVGLength; @@ -7596,7 +6614,6 @@ interface SVGSVGElement extends SVGElement, SVGStylable, SVGZoomAndPan, Document createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; getElementById(elementId: string): Element; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var SVGSVGElement: { prototype: SVGSVGElement; @@ -7816,14 +6833,6 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument, MSDataBindingEx * Raised when the object has been completely received from the server. */ onload: (ev: Event) => any; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; - /** - * Registers an event handler for the specified event type. - * @param type The type of event type to register. - * @param listener The event handler function to associate with the event. - * @param useCapture A Boolean value that specifies the event phase to add the event handler for. If true, register the event handler for the capturing phase. If false, Register the event handler for the bubbling phase. - */ - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLIFrameElement: { prototype: HTMLIFrameElement; @@ -7843,45 +6852,30 @@ declare var TextRangeCollection: { interface HTMLBodyElement extends HTMLElement, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { scroll: string; ononline: (ev: Event) => any; - addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; onblur: (ev: FocusEvent) => any; - addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; noWrap: boolean; onfocus: (ev: FocusEvent) => any; - addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onmessage: (ev: MessageEvent) => any; - addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; text: any; onerror: (ev: Event) => any; - addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; bgProperties: string; onresize: (ev: UIEvent) => any; - addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; link: any; aLink: any; bottomMargin: any; topMargin: any; onafterprint: (ev: Event) => any; - addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; vLink: any; onbeforeprint: (ev: Event) => any; - addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; onoffline: (ev: Event) => any; - addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; onunload: (ev: Event) => any; - addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; onhashchange: (ev: Event) => any; - addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; onload: (ev: Event) => any; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; rightMargin: any; onbeforeunload: (ev: BeforeUnloadEvent) => any; - addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; leftMargin: any; onstorage: (ev: StorageEvent) => any; - addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; createTextRange(): TextRange; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLBodyElement: { prototype: HTMLBodyElement; @@ -8339,20 +7333,15 @@ declare var SVGStringList: { interface XDomainRequest { timeout: number; onerror: (ev: Event) => any; - addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; onload: (ev: Event) => any; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; onprogress: (ev: any) => any; - addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; ontimeout: (ev: Event) => any; - addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; responseText: string; contentType: string; open(method: string, url: string): void; create(): XDomainRequest; abort(): void; send(data?: any): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var XDomainRequest: { prototype: XDomainRequest; @@ -8545,6 +7534,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); */ getContext(contextId: "2d"): CanvasRenderingContext2D; + getContext(contextId: "experimental-webgl"): WebGLRenderingContext; getContext(contextId: string, ...args: any[]): any; } declare var HTMLCanvasElement: { @@ -8971,8 +7961,8 @@ declare var CSSImportRule: { } interface CustomEvent extends Event { - detail: Object; - initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: Object): void; + detail: any; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; } declare var CustomEvent: { prototype: CustomEvent; @@ -9093,7 +8083,6 @@ interface DOML2DeprecatedAlignmentStyle { interface HTMLMarqueeElement extends HTMLElement, MSDataBindingExtensions, DOML2DeprecatedBackgroundColorStyle { width: string; onbounce: (ev: Event) => any; - addEventListener(type: "bounce", listener: (ev: Event) => any, useCapture?: boolean): void; vspace: number; trueSpeed: boolean; scrollAmount: number; @@ -9104,12 +8093,9 @@ interface HTMLMarqueeElement extends HTMLElement, MSDataBindingExtensions, DOML2 direction: string; hspace: number; onstart: (ev: Event) => any; - addEventListener(type: "start", listener: (ev: Event) => any, useCapture?: boolean): void; onfinish: (ev: Event) => any; - addEventListener(type: "finish", listener: (ev: Event) => any, useCapture?: boolean): void; stop(): void; start(): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; @@ -9419,7 +8405,7 @@ declare var SVGRectElement: { interface ErrorEventHandler { (event: Event, source: string, fileno: number, columnNumber: number): void; - (message: any, uri: string, lineNumber: number, columnNumber?: number): boolean; + (message: any, uri: string, lineNumber: number, columnNumber?: number): void; } interface HTMLDivElement extends HTMLElement, MSDataBindingExtensions { @@ -9518,25 +8504,20 @@ declare var ProcessingInstruction: { interface MSWindowExtensions { status: string; onmouseleave: (ev: MouseEvent) => any; - addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; screenLeft: number; offscreenBuffering: any; maxConnectionsPerServer: number; onmouseenter: (ev: MouseEvent) => any; - addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; clipboardData: DataTransfer; defaultStatus: string; clientInformation: Navigator; closed: boolean; onhelp: (ev: Event) => any; - addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; external: External; event: MSEventObj; onfocusout: (ev: FocusEvent) => any; - addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; screenTop: number; onfocusin: (ev: FocusEvent) => any; - addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; showModelessDialog(url?: string, argument?: any, options?: any): Window; navigate(url: string): void; resizeBy(x?: number, y?: number): void; @@ -9549,7 +8530,6 @@ interface MSWindowExtensions { moveTo(x?: number, y?: number): void; moveBy(x?: number, y?: number): void; showHelp(url: string, helpArg?: any, features?: string): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface MSBehaviorUrnsCollection { @@ -10147,226 +9127,136 @@ declare var HTMLBGSoundElement: { interface HTMLElement extends Element, ElementCSSInlineStyle, MSEventAttachmentTarget, MSNodeExtensions { onmouseleave: (ev: MouseEvent) => any; - addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onbeforecut: (ev: DragEvent) => any; - addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onkeydown: (ev: KeyboardEvent) => any; - addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; onmove: (ev: MSEventObj) => any; - addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onkeyup: (ev: KeyboardEvent) => any; - addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; onreset: (ev: Event) => any; - addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; onhelp: (ev: Event) => any; - addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; ondragleave: (ev: DragEvent) => any; - addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; className: string; onfocusin: (ev: FocusEvent) => any; - addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onseeked: (ev: Event) => any; - addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; recordNumber: any; title: string; parentTextEdit: Element; outerHTML: string; ondurationchange: (ev: Event) => any; - addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; offsetHeight: number; all: HTMLCollection; onblur: (ev: FocusEvent) => any; - addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; dir: string; onemptied: (ev: Event) => any; - addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; onseeking: (ev: Event) => any; - addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; oncanplay: (ev: Event) => any; - addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; ondeactivate: (ev: UIEvent) => any; - addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ondatasetchanged: (ev: MSEventObj) => any; - addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onrowsdelete: (ev: MSEventObj) => any; - addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; sourceIndex: number; onloadstart: (ev: Event) => any; - addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; onlosecapture: (ev: MSEventObj) => any; - addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; ondragenter: (ev: DragEvent) => any; - addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; oncontrolselect: (ev: MSEventObj) => any; - addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onsubmit: (ev: Event) => any; - addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; behaviorUrns: MSBehaviorUrnsCollection; scopeName: string; onchange: (ev: Event) => any; - addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; id: string; onlayoutcomplete: (ev: MSEventObj) => any; - addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; uniqueID: string; onbeforeactivate: (ev: UIEvent) => any; - addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; oncanplaythrough: (ev: Event) => any; - addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforeupdate: (ev: MSEventObj) => any; - addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onfilterchange: (ev: MSEventObj) => any; - addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; offsetParent: Element; ondatasetcomplete: (ev: MSEventObj) => any; - addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onsuspend: (ev: Event) => any; - addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; readyState: any; onmouseenter: (ev: MouseEvent) => any; - addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; innerText: string; onerrorupdate: (ev: MSEventObj) => any; - addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onmouseout: (ev: MouseEvent) => any; - addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; parentElement: HTMLElement; onmousewheel: (ev: MouseWheelEvent) => any; - addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; onvolumechange: (ev: Event) => any; - addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; oncellchange: (ev: MSEventObj) => any; - addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onrowexit: (ev: MSEventObj) => any; - addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onrowsinserted: (ev: MSEventObj) => any; - addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onpropertychange: (ev: MSEventObj) => any; - addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; filters: Object; children: HTMLCollection; ondragend: (ev: DragEvent) => any; - addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onbeforepaste: (ev: DragEvent) => any; - addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; ondragover: (ev: DragEvent) => any; - addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; offsetTop: number; onmouseup: (ev: MouseEvent) => any; - addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; ondragstart: (ev: DragEvent) => any; - addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onbeforecopy: (ev: DragEvent) => any; - addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; ondrag: (ev: DragEvent) => any; - addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; innerHTML: string; onmouseover: (ev: MouseEvent) => any; - addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; lang: string; uniqueNumber: number; onpause: (ev: Event) => any; - addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; tagUrn: string; onmousedown: (ev: MouseEvent) => any; - addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onclick: (ev: MouseEvent) => any; - addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onwaiting: (ev: Event) => any; - addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; onresizestart: (ev: MSEventObj) => any; - addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; offsetLeft: number; isTextEdit: boolean; isDisabled: boolean; onpaste: (ev: DragEvent) => any; - addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; canHaveHTML: boolean; onmoveend: (ev: MSEventObj) => any; - addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; language: string; onstalled: (ev: Event) => any; - addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; onmousemove: (ev: MouseEvent) => any; - addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; style: MSStyleCSSProperties; isContentEditable: boolean; onbeforeeditfocus: (ev: MSEventObj) => any; - addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onratechange: (ev: Event) => any; - addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; contentEditable: string; tabIndex: number; document: Document; onprogress: (ev: any) => any; - addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; ondblclick: (ev: MouseEvent) => any; - addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; oncontextmenu: (ev: MouseEvent) => any; - addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; onloadedmetadata: (ev: Event) => any; - addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; onafterupdate: (ev: MSEventObj) => any; - addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onerror: (ev: Event) => any; - addEventListener(type: "error", listener: (ev: Event) => any, useCapture?: boolean): void; onplay: (ev: Event) => any; - addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; onresizeend: (ev: MSEventObj) => any; - addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onplaying: (ev: Event) => any; - addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; isMultiLine: boolean; onfocusout: (ev: FocusEvent) => any; - addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; onabort: (ev: UIEvent) => any; - addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ondataavailable: (ev: MSEventObj) => any; - addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; hideFocus: boolean; onreadystatechange: (ev: Event) => any; - addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; onkeypress: (ev: KeyboardEvent) => any; - addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; onloadeddata: (ev: Event) => any; - addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; onbeforedeactivate: (ev: UIEvent) => any; - addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; outerText: string; disabled: boolean; onactivate: (ev: UIEvent) => any; - addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; accessKey: string; onmovestart: (ev: MSEventObj) => any; - addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onselectstart: (ev: Event) => any; - addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; onfocus: (ev: FocusEvent) => any; - addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; ontimeupdate: (ev: Event) => any; - addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; onresize: (ev: UIEvent) => any; - addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; oncut: (ev: DragEvent) => any; - addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onselect: (ev: UIEvent) => any; - addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; ondrop: (ev: DragEvent) => any; - addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; offsetWidth: number; oncopy: (ev: DragEvent) => any; - addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; onended: (ev: Event) => any; - addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; onscroll: (ev: UIEvent) => any; - addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; onrowenter: (ev: MSEventObj) => any; - addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; onload: (ev: Event) => any; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; canHaveChildren: boolean; oninput: (ev: Event) => any; - addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; dragDrop(): boolean; scrollIntoView(top?: boolean): void; addFilter(filter: Object): void; @@ -10390,7 +9280,6 @@ interface HTMLElement extends Element, ElementCSSInlineStyle, MSEventAttachmentT applyElement(apply: Element, where?: string): Element; addBehavior(bstrUrl: string, factory?: any): number; insertAdjacentHTML(where: string, html: string): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var HTMLElement: { prototype: HTMLElement; @@ -10911,149 +9800,89 @@ declare var Option: { new (text?: string, value?: string, defaultSelected?: bool declare var Image: { new (width?: number, height?: number): HTMLImageElement; }; declare var ondragend: (ev: DragEvent) => any; -declare function addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var onkeydown: (ev: KeyboardEvent) => any; -declare function addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; declare var ondragover: (ev: DragEvent) => any; -declare function addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var onkeyup: (ev: KeyboardEvent) => any; -declare function addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; declare var onreset: (ev: Event) => any; -declare function addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onmouseup: (ev: MouseEvent) => any; -declare function addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var ondragstart: (ev: DragEvent) => any; -declare function addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var ondrag: (ev: DragEvent) => any; -declare function addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var screenX: number; declare var onmouseover: (ev: MouseEvent) => any; -declare function addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var ondragleave: (ev: DragEvent) => any; -declare function addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var history: History; declare var pageXOffset: number; declare var name: string; declare var onafterprint: (ev: Event) => any; -declare function addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onpause: (ev: Event) => any; -declare function addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onbeforeprint: (ev: Event) => any; -declare function addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; declare var top: Window; declare var onmousedown: (ev: MouseEvent) => any; -declare function addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var onseeked: (ev: Event) => any; -declare function addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; declare var opener: Window; declare var onclick: (ev: MouseEvent) => any; -declare function addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var innerHeight: number; declare var onwaiting: (ev: Event) => any; -declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; declare var ononline: (ev: Event) => any; -declare function addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; declare var ondurationchange: (ev: Event) => any; -declare function addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var frames: Window; declare var onblur: (ev: FocusEvent) => any; -declare function addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare var onemptied: (ev: Event) => any; -declare function addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onseeking: (ev: Event) => any; -declare function addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; declare var oncanplay: (ev: Event) => any; -declare function addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; declare var outerWidth: number; declare var onstalled: (ev: Event) => any; -declare function addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onmousemove: (ev: MouseEvent) => any; -declare function addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var innerWidth: number; declare var onoffline: (ev: Event) => any; -declare function addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; declare var length: number; declare var screen: Screen; declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; -declare function addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; declare var onratechange: (ev: Event) => any; -declare function addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onstorage: (ev: StorageEvent) => any; -declare function addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; declare var onloadstart: (ev: Event) => any; -declare function addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; declare var ondragenter: (ev: DragEvent) => any; -declare function addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var onsubmit: (ev: Event) => any; -declare function addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; declare var self: Window; declare var document: Document; declare var onprogress: (ev: any) => any; -declare function addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; declare var ondblclick: (ev: MouseEvent) => any; -declare function addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var pageYOffset: number; declare var oncontextmenu: (ev: MouseEvent) => any; -declare function addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var onchange: (ev: Event) => any; -declare function addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onloadedmetadata: (ev: Event) => any; -declare function addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onplay: (ev: Event) => any; -declare function addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onerror: ErrorEventHandler; declare var onplaying: (ev: Event) => any; -declare function addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; declare var parent: Window; declare var location: Location; declare var oncanplaythrough: (ev: Event) => any; -declare function addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onabort: (ev: UIEvent) => any; -declare function addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare var onreadystatechange: (ev: Event) => any; -declare function addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var outerHeight: number; declare var onkeypress: (ev: KeyboardEvent) => any; -declare function addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; declare var frameElement: Element; declare var onloadeddata: (ev: Event) => any; -declare function addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onsuspend: (ev: Event) => any; -declare function addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; declare var window: Window; declare var onfocus: (ev: FocusEvent) => any; -declare function addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare var onmessage: (ev: MessageEvent) => any; -declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; declare var ontimeupdate: (ev: Event) => any; -declare function addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onresize: (ev: UIEvent) => any; -declare function addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare var onselect: (ev: UIEvent) => any; -declare function addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare var navigator: Navigator; declare var styleMedia: StyleMedia; declare var ondrop: (ev: DragEvent) => any; -declare function addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; declare var onmouseout: (ev: MouseEvent) => any; -declare function addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var onended: (ev: Event) => any; -declare function addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onhashchange: (ev: Event) => any; -declare function addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onunload: (ev: Event) => any; -declare function addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onscroll: (ev: UIEvent) => any; -declare function addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; declare var screenY: number; declare var onmousewheel: (ev: MouseWheelEvent) => any; -declare function addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; declare var onload: (ev: Event) => any; -declare function addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; declare var onvolumechange: (ev: Event) => any; -declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare var oninput: (ev: Event) => any; -declare function addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; declare var performance: Performance; declare function alert(message?: any): void; declare function scroll(x?: number, y?: number): void; @@ -11071,7 +9900,6 @@ declare function showModalDialog(url?: string, argument?: any, options?: any): a declare function blur(): void; declare function getSelection(): Selection; declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; -declare function addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; declare function removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; declare function dispatchEvent(evt: Event): boolean; declare function attachEvent(event: string, listener: EventListener): boolean; @@ -11079,25 +9907,20 @@ declare function detachEvent(event: string, listener: EventListener): void; declare var localStorage: Storage; declare var status: string; declare var onmouseleave: (ev: MouseEvent) => any; -declare function addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var screenLeft: number; declare var offscreenBuffering: any; declare var maxConnectionsPerServer: number; declare var onmouseenter: (ev: MouseEvent) => any; -declare function addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; declare var clipboardData: DataTransfer; declare var defaultStatus: string; declare var clientInformation: Navigator; declare var closed: boolean; declare var onhelp: (ev: Event) => any; -declare function addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; declare var external: External; declare var event: MSEventObj; declare var onfocusout: (ev: FocusEvent) => any; -declare function addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare var screenTop: number; declare var onfocusin: (ev: FocusEvent) => any; -declare function addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; declare function showModelessDialog(url?: string, argument?: any, options?: any): Window; declare function navigate(url: string): void; declare function resizeBy(x?: number, y?: number): void; @@ -11122,14 +9945,12 @@ declare function setInterval(handler: any, timeout?: any, ...args: any[]): numbe ///////////////////////////// - interface ObjectURLOptions { oneTimeOnly?: boolean; } interface HTMLBodyElement { onpopstate: (ev: PopStateEvent) => any; - addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; } interface MSGestureEvent extends UIEvent { @@ -11158,8 +9979,6 @@ interface MSGestureEvent extends UIEvent { MSGESTURE_FLAG_NONE: number; } declare var MSGestureEvent: { - prototype: MSGestureEvent; - new (): MSGestureEvent; MSGESTURE_FLAG_BEGIN: number; MSGESTURE_FLAG_END: number; MSGESTURE_FLAG_CANCEL: number; @@ -11279,14 +10098,11 @@ interface HTMLInputElement { interface ErrorEvent extends Event { colno: number; filename: string; + error: any; lineno: number; message: string; initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; } -declare var ErrorEvent: { - prototype: ErrorEvent; - new (): ErrorEvent; -} interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { y: SVGAnimatedLength; @@ -11299,33 +10115,17 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLan filterResY: SVGAnimatedInteger; setFilterRes(filterResX: number, filterResY: number): void; } -declare var SVGFilterElement: { - prototype: SVGFilterElement; - new (): SVGFilterElement; -} interface TrackEvent extends Event { track: any; } -declare var TrackEvent: { - prototype: TrackEvent; - new (): TrackEvent; -} interface SVGFEMergeNodeElement extends SVGElement { in1: SVGAnimatedString; } -declare var SVGFEMergeNodeElement: { - prototype: SVGFEMergeNodeElement; - new (): SVGFEMergeNodeElement; -} interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { } -declare var SVGFEFloodElement: { - prototype: SVGFEFloodElement; - new (): SVGFEFloodElement; -} interface MSGesture { target: Element; @@ -11339,7 +10139,6 @@ declare var MSGesture: { interface TextTrackCue extends EventTarget { onenter: (ev: Event) => any; - addEventListener(type: "enter", listener: (ev: Event) => any, useCapture?: boolean): void; track: TextTrack; endTime: number; text: string; @@ -11347,9 +10146,7 @@ interface TextTrackCue extends EventTarget { id: string; startTime: number; onexit: (ev: Event) => any; - addEventListener(type: "exit", listener: (ev: Event) => any, useCapture?: boolean): void; getCueAsHTML(): DocumentFragment; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var TextTrackCue: { prototype: TextTrackCue; @@ -11378,10 +10175,6 @@ interface DOMTokenList { [index: number]: string; toString(): string; } -declare var DOMTokenList: { - prototype: DOMTokenList; - new (): DOMTokenList; -} interface EventException { name: string; @@ -11393,18 +10186,10 @@ interface Performance { interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { } -declare var SVGFEFuncAElement: { - prototype: SVGFEFuncAElement; - new (): SVGFEFuncAElement; -} interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; } -declare var SVGFETileElement: { - prototype: SVGFETileElement; - new (): SVGFETileElement; -} interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in2: SVGAnimatedString; @@ -11418,8 +10203,6 @@ interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttrib SVG_FEBLEND_MODE_LIGHTEN: number; } declare var SVGFEBlendElement: { - prototype: SVGFEBlendElement; - new (): SVGFEBlendElement; SVG_FEBLEND_MODE_DARKEN: number; SVG_FEBLEND_MODE_UNKNOWN: number; SVG_FEBLEND_MODE_MULTIPLY: number; @@ -11430,10 +10213,6 @@ declare var SVGFEBlendElement: { interface WindowTimers extends WindowTimersExtension { } -declare var WindowTimers: { - prototype: WindowTimers; - new (): WindowTimers; -} interface CSSStyleDeclaration { animationFillMode: string; @@ -11564,10 +10343,6 @@ declare var MessageChannel: { interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { } -declare var SVGFEMergeElement: { - prototype: SVGFEMergeElement; - new (): SVGFEMergeElement; -} interface Navigator extends MSFileSaver { msMaxTouchPoints: number; @@ -11581,10 +10356,6 @@ interface TransitionEvent extends Event { elapsedTime: number; initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; } -declare var TransitionEvent: { - prototype: TransitionEvent; - new (): TransitionEvent; -} interface MediaQueryList { matches: boolean; @@ -11592,19 +10363,11 @@ interface MediaQueryList { addListener(listener: MediaQueryListListener): void; removeListener(listener: MediaQueryListListener): void; } -declare var MediaQueryList: { - prototype: MediaQueryList; - new (): MediaQueryList; -} interface DOMError { name: string; toString(): string; } -declare var DOMError: { - prototype: DOMError; - new (): DOMError; -} interface CloseEvent extends Event { wasClean: boolean; @@ -11612,29 +10375,20 @@ interface CloseEvent extends Event { code: number; initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; } -declare var CloseEvent: { - prototype: CloseEvent; - new (): CloseEvent; -} interface WebSocket extends EventTarget { protocol: string; readyState: number; bufferedAmount: number; onopen: (ev: Event) => any; - addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void; extensions: string; onmessage: (ev: any) => any; - addEventListener(type: "message", listener: (ev: any) => any, useCapture?: boolean): void; onclose: (ev: CloseEvent) => any; - addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; binaryType: string; url: string; close(code?: number, reason?: string): void; send(data: any): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; OPEN: number; CLOSING: number; CONNECTING: number; @@ -11656,10 +10410,6 @@ interface SVGFEPointLightElement extends SVGElement { x: SVGAnimatedNumber; z: SVGAnimatedNumber; } -declare var SVGFEPointLightElement: { - prototype: SVGFEPointLightElement; - new (): SVGFEPointLightElement; -} interface ProgressEvent extends Event { loaded: number; @@ -11667,10 +10417,6 @@ interface ProgressEvent extends Event { total: number; initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; } -declare var ProgressEvent: { - prototype: ProgressEvent; - new (): ProgressEvent; -} interface IDBObjectStore { indexNames: DOMStringList; @@ -11688,10 +10434,6 @@ interface IDBObjectStore { get(key: any): IDBRequest; delete(key: any): IDBRequest; } -declare var IDBObjectStore: { - prototype: IDBObjectStore; - new (): IDBObjectStore; -} interface HTMLCanvasElement { /** @@ -11706,10 +10448,6 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; } -declare var SVGFEGaussianBlurElement: { - prototype: SVGFEGaussianBlurElement; - new (): SVGFEGaussianBlurElement; -} interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { y: SVGAnimatedLength; @@ -11722,52 +10460,31 @@ interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { interface Element { msRegionOverflow: string; onmspointerdown: (ev: any) => any; - addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; onmsgotpointercapture: (ev: any) => any; - addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturedoubletap: (ev: any) => any; - addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerhover: (ev: any) => any; - addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturehold: (ev: any) => any; - addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; onmspointermove: (ev: any) => any; - addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturechange: (ev: any) => any; - addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturestart: (ev: any) => any; - addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; onmspointercancel: (ev: any) => any; - addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; onmsgestureend: (ev: any) => any; - addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturetap: (ev: any) => any; - addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerout: (ev: any) => any; - addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; onmsinertiastart: (ev: any) => any; - addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; onmslostpointercapture: (ev: any) => any; - addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerover: (ev: any) => any; - addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; msContentZoomFactor: number; onmspointerup: (ev: any) => any; - addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; msGetRegionContent(): MSRangeCollection; msReleasePointerCapture(pointerId: number): void; msSetPointerCapture(pointerId: number): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface IDBVersionChangeEvent extends Event { newVersion: number; oldVersion: number; } -declare var IDBVersionChangeEvent: { - prototype: IDBVersionChangeEvent; - new (): IDBVersionChangeEvent; -} interface IDBIndex { unique: boolean; @@ -11780,10 +10497,6 @@ interface IDBIndex { get(key: any): IDBRequest; openCursor(range?: IDBKeyRange, direction?: string): IDBRequest; } -declare var IDBIndex: { - prototype: IDBIndex; - new (): IDBIndex; -} interface WheelEvent { getCurrentPoint(element: Element): void; @@ -11794,10 +10507,6 @@ interface FileList { item(index: number): File; [index: number]: File; } -declare var FileList: { - prototype: FileList; - new (): FileList; -} interface IDBCursor { source: any; @@ -11808,18 +10517,6 @@ interface IDBCursor { delete(): IDBRequest; continue(key?: any): void; update(value: any): IDBRequest; - PREV: string; - PREV_NO_DUPLICATE: string; - NEXT: string; - NEXT_NO_DUPLICATE: string; -} -declare var IDBCursor: { - prototype: IDBCursor; - new (): IDBCursor; - PREV: string; - PREV_NO_DUPLICATE: string; - NEXT: string; - NEXT_NO_DUPLICATE: string; } interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { @@ -11830,19 +10527,11 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta kernelUnitLengthX: SVGAnimatedNumber; specularConstant: SVGAnimatedNumber; } -declare var SVGFESpecularLightingElement: { - prototype: SVGFESpecularLightingElement; - new (): SVGFESpecularLightingElement; -} interface File extends Blob { lastModifiedDate: any; name: string; } -declare var File: { - prototype: File; - new (): File; -} interface URL { revokeObjectURL(url: string): void; @@ -11857,10 +10546,6 @@ interface RangeException { interface IDBCursorWithValue extends IDBCursor { value: any; } -declare var IDBCursorWithValue: { - prototype: IDBCursorWithValue; - new (): IDBCursorWithValue; -} interface HTMLTextAreaElement { /** @@ -11904,24 +10589,12 @@ interface HTMLTextAreaElement { interface XMLHttpRequestEventTarget extends EventTarget { onprogress: (ev: ProgressEvent) => any; - addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onload: (ev: any) => any; - addEventListener(type: "load", listener: (ev: any) => any, useCapture?: boolean): void; ontimeout: (ev: any) => any; - addEventListener(type: "timeout", listener: (ev: any) => any, useCapture?: boolean): void; onabort: (ev: any) => any; - addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; onloadstart: (ev: any) => any; - addEventListener(type: "loadstart", listener: (ev: any) => any, useCapture?: boolean): void; onloadend: (ev: ProgressEvent) => any; - addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; -} -declare var XMLHttpRequestEventTarget: { - prototype: XMLHttpRequestEventTarget; - new (): XMLHttpRequestEventTarget; } interface IDBEnvironment { @@ -11932,36 +10605,22 @@ interface IDBEnvironment { interface AudioTrackList extends EventTarget { length: number; onchange: (ev: any) => any; - addEventListener(type: "change", listener: (ev: any) => any, useCapture?: boolean): void; onaddtrack: (ev: TrackEvent) => any; - addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; getTrackById(id: string): AudioTrack; item(index: number): AudioTrack; [index: number]: AudioTrack; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; -} -declare var AudioTrackList: { - prototype: AudioTrackList; - new (): AudioTrackList; } interface MSBaseReader extends EventTarget { onprogress: (ev: ProgressEvent) => any; - addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; readyState: number; onabort: (ev: any) => any; - addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; onloadend: (ev: ProgressEvent) => any; - addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onload: (ev: any) => any; - addEventListener(type: "load", listener: (ev: any) => any, useCapture?: boolean): void; onloadstart: (ev: any) => any; - addEventListener(type: "loadstart", listener: (ev: any) => any, useCapture?: boolean): void; result: any; abort(): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; LOADING: number; EMPTY: number; DONE: number; @@ -11983,8 +10642,6 @@ interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardA SVG_MORPHOLOGY_OPERATOR_DILATE: number; } declare var SVGFEMorphologyElement: { - prototype: SVGFEMorphologyElement; - new (): SVGFEMorphologyElement; SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; SVG_MORPHOLOGY_OPERATOR_ERODE: number; SVG_MORPHOLOGY_OPERATOR_DILATE: number; @@ -12028,7 +10685,6 @@ interface CSSRule { VIEWPORT_RULE: number; } //declare var CSSRule: { -// prototype: CSSRule; // KEYFRAMES_RULE: number; // KEYFRAME_RULE: number; // VIEWPORT_RULE: number; @@ -12036,10 +10692,6 @@ interface CSSRule { interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { } -declare var SVGFEFuncRElement: { - prototype: SVGFEFuncRElement; - new (): SVGFEFuncRElement; -} interface WindowTimersExtension { msSetImmediate(expression: any, ...args: any[]): number; @@ -12061,8 +10713,6 @@ interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStan SVG_CHANNEL_A: number; } declare var SVGFEDisplacementMapElement: { - prototype: SVGFEDisplacementMapElement; - new (): SVGFEDisplacementMapElement; SVG_CHANNEL_B: number; SVG_CHANNEL_R: number; SVG_CHANNEL_G: number; @@ -12075,10 +10725,6 @@ interface AnimationEvent extends Event { elapsedTime: number; initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; } -declare var AnimationEvent: { - prototype: AnimationEvent; - new (): AnimationEvent; -} interface SVGComponentTransferFunctionElement extends SVGElement { tableValues: SVGAnimatedNumberList; @@ -12096,8 +10742,6 @@ interface SVGComponentTransferFunctionElement extends SVGElement { SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; } declare var SVGComponentTransferFunctionElement: { - prototype: SVGComponentTransferFunctionElement; - new (): SVGComponentTransferFunctionElement; SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; @@ -12111,19 +10755,11 @@ interface MSRangeCollection { item(index: number): Range; [index: number]: Range; } -declare var MSRangeCollection: { - prototype: MSRangeCollection; - new (): MSRangeCollection; -} interface SVGFEDistantLightElement extends SVGElement { azimuth: SVGAnimatedNumber; elevation: SVGAnimatedNumber; } -declare var SVGFEDistantLightElement: { - prototype: SVGFEDistantLightElement; - new (): SVGFEDistantLightElement; -} interface SVGException { name: string; @@ -12131,10 +10767,6 @@ interface SVGException { interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { } -declare var SVGFEFuncBElement: { - prototype: SVGFEFuncBElement; - new (): SVGFEFuncBElement; -} interface IDBKeyRange { upper: any; @@ -12146,10 +10778,6 @@ interface IDBKeyRange { lowerBound(bound: any, open?: boolean): IDBKeyRange; upperBound(bound: any, open?: boolean): IDBKeyRange; } -declare var IDBKeyRange: { - prototype: IDBKeyRange; - new (): IDBKeyRange; -} interface WindowConsole { console: Console; @@ -12157,27 +10785,13 @@ interface WindowConsole { interface IDBTransaction extends EventTarget { oncomplete: (ev: Event) => any; - addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; db: IDBDatabase; mode: string; error: DOMError; onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onabort: (ev: any) => any; - addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; abort(): void; objectStore(name: string): IDBObjectStore; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; - READ_ONLY: string; - VERSION_CHANGE: string; - READ_WRITE: string; -} -declare var IDBTransaction: { - prototype: IDBTransaction; - new (): IDBTransaction; - READ_ONLY: string; - VERSION_CHANGE: string; - READ_WRITE: string; } interface AudioTrack { @@ -12187,10 +10801,6 @@ interface AudioTrack { label: string; enabled: boolean; } -declare var AudioTrack: { - prototype: AudioTrack; - new (): AudioTrack; -} interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { orderY: SVGAnimatedInteger; @@ -12211,8 +10821,6 @@ interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStand SVG_EDGEMODE_NONE: number; } declare var SVGFEConvolveMatrixElement: { - prototype: SVGFEConvolveMatrixElement; - new (): SVGFEConvolveMatrixElement; SVG_EDGEMODE_WRAP: number; SVG_EDGEMODE_DUPLICATE: number; SVG_EDGEMODE_UNKNOWN: number; @@ -12225,10 +10833,6 @@ interface TextTrackCueList { [index: number]: TextTrackCue; getCueById(id: string): TextTrackCue; } -declare var TextTrackCueList: { - prototype: TextTrackCueList; - new (): TextTrackCueList; -} interface CSSKeyframesRule extends CSSRule { name: string; @@ -12237,45 +10841,26 @@ interface CSSKeyframesRule extends CSSRule { deleteRule(rule: string): void; appendRule(rule: string): void; } -declare var CSSKeyframesRule: { - prototype: CSSKeyframesRule; - new (): CSSKeyframesRule; -} interface Window extends WindowBase64, IDBEnvironment, WindowConsole { onmspointerdown: (ev: any) => any; - addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; animationStartTime: number; onmsgesturedoubletap: (ev: any) => any; - addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerhover: (ev: any) => any; - addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturehold: (ev: any) => any; - addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; onmspointermove: (ev: any) => any; - addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturechange: (ev: any) => any; - addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturestart: (ev: any) => any; - addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; onmspointercancel: (ev: any) => any; - addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; onmsgestureend: (ev: any) => any; - addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturetap: (ev: any) => any; - addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerout: (ev: any) => any; - addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; msAnimationStartTime: number; applicationCache: ApplicationCache; onmsinertiastart: (ev: any) => any; - addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerover: (ev: any) => any; - addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; onpopstate: (ev: PopStateEvent) => any; - addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; onmspointerup: (ev: any) => any; - addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; msCancelRequestAnimationFrame(handle: number): void; matchMedia(mediaQuery: string): MediaQueryList; cancelAnimationFrame(handle: number): void; @@ -12300,8 +10885,6 @@ interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardA SVG_STITCHTYPE_STITCH: number; } declare var SVGFETurbulenceElement: { - prototype: SVGFETurbulenceElement; - new (): SVGFETurbulenceElement; SVG_STITCHTYPE_UNKNOWN: number; SVG_STITCHTYPE_NOSTITCH: number; SVG_TURBULENCE_TYPE_UNKNOWN: number; @@ -12315,17 +10898,9 @@ interface TextTrackList { item(index: number): TextTrack; [index: number]: TextTrack; } -declare var TextTrackList: { - prototype: TextTrackList; - new (): TextTrackList; -} interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { } -declare var SVGFEFuncGElement: { - prototype: SVGFEFuncGElement; - new (): SVGFEFuncGElement; -} interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; @@ -12338,8 +10913,6 @@ interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandard SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; } declare var SVGFEColorMatrixElement: { - prototype: SVGFEColorMatrixElement; - new (): SVGFEColorMatrixElement; SVG_FECOLORMATRIX_TYPE_SATURATE: number; SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; SVG_FECOLORMATRIX_TYPE_MATRIX: number; @@ -12359,10 +10932,6 @@ interface Console { log(message?: any, ...optionalParams: any[]): void; profileEnd(): void; } -declare var Console: { - prototype: Console; - new (): Console; -} interface SVGFESpotLightElement extends SVGElement { pointsAtY: SVGAnimatedNumber; @@ -12374,10 +10943,6 @@ interface SVGFESpotLightElement extends SVGElement { z: SVGAnimatedNumber; pointsAtX: SVGAnimatedNumber; } -declare var SVGFESpotLightElement: { - prototype: SVGFESpotLightElement; - new (): SVGFESpotLightElement; -} interface HTMLImageElement { /** @@ -12404,18 +10969,11 @@ interface IDBDatabase extends EventTarget { name: string; objectStoreNames: DOMStringList; onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onabort: (ev: any) => any; - addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; close(): void; transaction(storeNames: any, mode?: string): IDBTransaction; deleteObjectStore(name: string): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; -} -declare var IDBDatabase: { - prototype: IDBDatabase; - new (): IDBDatabase; } interface DOMStringList { @@ -12424,10 +10982,6 @@ interface DOMStringList { item(index: number): string; [index: number]: string; } -declare var DOMStringList: { - prototype: DOMStringList; - new (): DOMStringList; -} interface HTMLButtonElement { /** @@ -12479,14 +11033,7 @@ interface HTMLButtonElement { interface IDBOpenDBRequest extends IDBRequest { onupgradeneeded: (ev: IDBVersionChangeEvent) => any; - addEventListener(type: "upgradeneeded", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; onblocked: (ev: Event) => any; - addEventListener(type: "blocked", listener: (ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; -} -declare var IDBOpenDBRequest: { - prototype: IDBOpenDBRequest; - new (): IDBOpenDBRequest; } interface HTMLProgressElement extends HTMLElement { @@ -12507,10 +11054,6 @@ interface HTMLProgressElement extends HTMLElement { */ form: HTMLFormElement; } -declare var HTMLProgressElement: { - prototype: HTMLProgressElement; - new (): HTMLProgressElement; -} interface MSLaunchUriCallback { (): void; @@ -12521,10 +11064,6 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri in1: SVGAnimatedString; dx: SVGAnimatedNumber; } -declare var SVGFEOffsetElement: { - prototype: SVGFEOffsetElement; - new (): SVGFEOffsetElement; -} interface HTMLFormElement { /** @@ -12547,42 +11086,26 @@ interface MSUnsafeFunctionCallback { interface Document { onmspointerdown: (ev: any) => any; - addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; msHidden: boolean; msVisibilityState: string; onmsgesturedoubletap: (ev: any) => any; - addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; visibilityState: string; onmsmanipulationstatechanged: (ev: any) => any; - addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerhover: (ev: any) => any; - addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; onmscontentzoom: (ev: any) => any; - addEventListener(type: "mscontentzoom", listener: (ev: any) => any, useCapture?: boolean): void; onmspointermove: (ev: any) => any; - addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturehold: (ev: any) => any; - addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturechange: (ev: any) => any; - addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturestart: (ev: any) => any; - addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; onmspointercancel: (ev: any) => any; - addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; onmsgestureend: (ev: any) => any; - addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; onmsgesturetap: (ev: any) => any; - addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerout: (ev: any) => any; - addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; onmsinertiastart: (ev: any) => any; - addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; msCSSOMElementFloatMetrics: boolean; onmspointerover: (ev: any) => any; - addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; hidden: boolean; onmspointerup: (ev: any) => any; - addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; msElementsFromPoint(x: number, y: number): NodeList; msElementsFromRect(left: number, top: number, width: number, height: number): NodeList; clear(): void; @@ -12647,14 +11170,10 @@ interface TextTrack extends EventTarget { activeCues: TextTrackCueList; cues: TextTrackCueList; oncuechange: (ev: Event) => any; - addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; kind: string; onload: (ev: any) => any; - addEventListener(type: "load", listener: (ev: any) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; label: string; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; ERROR: number; SHOWING: number; LOADING: number; @@ -12664,8 +11183,6 @@ interface TextTrack extends EventTarget { DISABLED: number; } declare var TextTrack: { - prototype: TextTrack; - new (): TextTrack; ERROR: number; SHOWING: number; LOADING: number; @@ -12682,31 +11199,18 @@ interface MediaQueryListListener { interface IDBRequest extends EventTarget { source: any; onsuccess: (ev: Event) => any; - addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; error: DOMError; transaction: IDBTransaction; onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; readyState: string; result: any; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; -} -declare var IDBRequest: { - prototype: IDBRequest; - new (): IDBRequest; } interface MessagePort extends EventTarget { onmessage: (ev: any) => any; - addEventListener(type: "message", listener: (ev: any) => any, useCapture?: boolean): void; close(): void; - postMessage(message: any, ports?: any): void; + postMessage(message?: any, ports?: any): void; start(): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; -} -declare var MessagePort: { - prototype: MessagePort; - new (): MessagePort; } interface FileReader extends MSBaseReader { @@ -12730,7 +11234,6 @@ interface Blob { size: number; msDetachStream(): any; slice(start?: number, end?: number, contentType?: string): Blob; - close(): void; msClose(): void; } declare var Blob: { @@ -12741,25 +11244,16 @@ declare var Blob: { interface ApplicationCache extends EventTarget { status: number; ondownloading: (ev: Event) => any; - addEventListener(type: "downloading", listener: (ev: Event) => any, useCapture?: boolean): void; onprogress: (ev: ProgressEvent) => any; - addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; onupdateready: (ev: Event) => any; - addEventListener(type: "updateready", listener: (ev: Event) => any, useCapture?: boolean): void; oncached: (ev: Event) => any; - addEventListener(type: "cached", listener: (ev: Event) => any, useCapture?: boolean): void; onobsolete: (ev: Event) => any; - addEventListener(type: "obsolete", listener: (ev: Event) => any, useCapture?: boolean): void; onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onchecking: (ev: Event) => any; - addEventListener(type: "checking", listener: (ev: Event) => any, useCapture?: boolean): void; onnoupdate: (ev: Event) => any; - addEventListener(type: "noupdate", listener: (ev: Event) => any, useCapture?: boolean): void; swapCache(): void; abort(): void; update(): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; CHECKING: number; UNCACHED: number; UPDATEREADY: number; @@ -12768,8 +11262,6 @@ interface ApplicationCache extends EventTarget { OBSOLETE: number; } declare var ApplicationCache: { - prototype: ApplicationCache; - new (): ApplicationCache; CHECKING: number; UNCACHED: number; UPDATEREADY: number; @@ -12786,36 +11278,23 @@ interface XMLHttpRequest { response: any; withCredentials: boolean; onprogress: (ev: ProgressEvent) => any; - addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; onabort: (ev: any) => any; - addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; responseType: string; onloadend: (ev: ProgressEvent) => any; - addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; upload: XMLHttpRequestEventTarget; onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; onloadstart: (ev: any) => any; - addEventListener(type: "loadstart", listener: (ev: any) => any, useCapture?: boolean): void; } interface PopStateEvent extends Event { state: any; initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; } -declare var PopStateEvent: { - prototype: PopStateEvent; - new (): PopStateEvent; -} interface CSSKeyframeRule extends CSSRule { keyText: string; style: CSSStyleDeclaration; } -declare var CSSKeyframeRule: { - prototype: CSSKeyframeRule; - new (): CSSKeyframeRule; -} interface MSFileSaver { msSaveBlob(blob: any, defaultName?: string): boolean; @@ -12827,10 +11306,6 @@ interface MSStream { msDetachStream(): any; msClose(): void; } -declare var MSStream: { - prototype: MSStream; - new (): MSStream; -} interface MediaError { msExtendedCode: number; @@ -12871,13 +11346,10 @@ declare var MSBlobBuilder: { interface HTMLElement { onmscontentzoom: (ev: any) => any; - addEventListener(type: "mscontentzoom", listener: (ev: any) => any, useCapture?: boolean): void; oncuechange: (ev: Event) => any; - addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; spellcheck: boolean; classList: DOMTokenList; onmsmanipulationstatechanged: (ev: any) => any; - addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; draggable: boolean; } @@ -12889,20 +11361,12 @@ interface DataTransfer { interface DOMSettableTokenList extends DOMTokenList { value: string; } -declare var DOMSettableTokenList: { - prototype: DOMSettableTokenList; - new (): DOMSettableTokenList; -} interface IDBFactory { open(name: string, version?: number): IDBOpenDBRequest; cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; } -declare var IDBFactory: { - prototype: IDBFactory; - new (): IDBFactory; -} interface Range { createContextualFragment(fragment: string): DocumentFragment; @@ -12953,8 +11417,6 @@ interface MSPointerEvent extends MouseEvent { MSPOINTER_TYPE_TOUCH: number; } declare var MSPointerEvent: { - prototype: MSPointerEvent; - new (): MSPointerEvent; MSPOINTER_TYPE_PEN: number; MSPOINTER_TYPE_MOUSE: number; MSPOINTER_TYPE_TOUCH: number; @@ -12967,7 +11429,6 @@ interface DOMException { TIMEOUT_ERR: number; } //declare var DOMException: { -// prototype: DOMException; // INVALID_NODE_TYPE_ERR: number; // DATA_CLONE_ERR: number; // TIMEOUT_ERR: number; @@ -12982,8 +11443,6 @@ interface MSManipulationEvent extends UIEvent { MS_MANIPULATION_STATE_INERTIA: number; } declare var MSManipulationEvent: { - prototype: MSManipulationEvent; - new (): MSManipulationEvent; MS_MANIPULATION_STATE_STOPPED: number; MS_MANIPULATION_STATE_ACTIVE: number; MS_MANIPULATION_STATE_INERTIA: number; @@ -13000,23 +11459,13 @@ declare var FormData: { interface HTMLDataListElement extends HTMLElement { options: HTMLCollection; } -declare var HTMLDataListElement: { - prototype: HTMLDataListElement; - new (): HTMLDataListElement; -} interface SVGFEImageElement extends SVGElement, SVGLangSpace, SVGFilterPrimitiveStandardAttributes, SVGURIReference, SVGExternalResourcesRequired { preserveAspectRatio: SVGAnimatedPreserveAspectRatio; } -declare var SVGFEImageElement: { - prototype: SVGFEImageElement; - new (): SVGFEImageElement; -} interface AbstractWorker extends EventTarget { onerror: (ev: ErrorEvent) => any; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { @@ -13036,8 +11485,6 @@ interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAt SVG_FECOMPOSITE_OPERATOR_ATOP: number; } declare var SVGFECompositeElement: { - prototype: SVGFECompositeElement; - new (): SVGFECompositeElement; SVG_FECOMPOSITE_OPERATOR_OUT: number; SVG_FECOMPOSITE_OPERATOR_OVER: number; SVG_FECOMPOSITE_OPERATOR_XOR: number; @@ -13058,10 +11505,6 @@ interface ValidityState { tooLong: boolean; valid: boolean; } -declare var ValidityState: { - prototype: ValidityState; - new (): ValidityState; -} interface HTMLTrackElement extends HTMLElement { kind: string; @@ -13071,10 +11514,6 @@ interface HTMLTrackElement extends HTMLElement { label: string; default: boolean; } -declare var HTMLTrackElement: { - prototype: HTMLTrackElement; - new (): HTMLTrackElement; -} interface MSApp { createFileFromStorageFile(storageFile: any): File; @@ -13093,28 +11532,20 @@ interface HTMLVideoElement { msIsStereo3D: boolean; msStereo3DPackingMode: string; onMSVideoOptimalLayoutChanged: (ev: any) => any; - addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (ev: any) => any, useCapture?: boolean): void; onMSVideoFrameStepCompleted: (ev: any) => any; - addEventListener(type: "MSVideoFrameStepCompleted", listener: (ev: any) => any, useCapture?: boolean): void; msStereo3DRenderMode: string; msIsLayoutOptimalForPlayback: boolean; msHorizontalMirror: boolean; onMSVideoFormatChanged: (ev: any) => any; - addEventListener(type: "MSVideoFormatChanged", listener: (ev: any) => any, useCapture?: boolean): void; msZoom: boolean; msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; msFrameStep(forward: boolean): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { in1: SVGAnimatedString; } -declare var SVGFEComponentTransferElement: { - prototype: SVGFEComponentTransferElement; - new (): SVGFEComponentTransferElement; -} interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { kernelUnitLengthY: SVGAnimatedNumber; @@ -13123,10 +11554,6 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan kernelUnitLengthX: SVGAnimatedNumber; diffuseConstant: SVGAnimatedNumber; } -declare var SVGFEDiffuseLightingElement: { - prototype: SVGFEDiffuseLightingElement; - new (): SVGFEDiffuseLightingElement; -} interface MSCSSMatrix { m24: number; @@ -13169,10 +11596,8 @@ declare var MSCSSMatrix: { interface Worker extends AbstractWorker { onmessage: (ev: any) => any; - addEventListener(type: "message", listener: (ev: any) => any, useCapture?: boolean): void; postMessage(message: any, ports?: any): void; terminate(): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var Worker: { prototype: Worker; @@ -13184,38 +11609,23 @@ interface HTMLIFrameElement { } declare var onmspointerdown: (ev: any) => any; -declare function addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; declare var animationStartTime: number; declare var onmsgesturedoubletap: (ev: any) => any; -declare function addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmspointerhover: (ev: any) => any; -declare function addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmsgesturehold: (ev: any) => any; -declare function addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmspointermove: (ev: any) => any; -declare function addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmsgesturechange: (ev: any) => any; -declare function addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmsgesturestart: (ev: any) => any; -declare function addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmspointercancel: (ev: any) => any; -declare function addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmsgestureend: (ev: any) => any; -declare function addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmsgesturetap: (ev: any) => any; -declare function addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmspointerout: (ev: any) => any; -declare function addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; declare var msAnimationStartTime: number; declare var applicationCache: ApplicationCache; declare var onmsinertiastart: (ev: any) => any; -declare function addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; declare var onmspointerover: (ev: any) => any; -declare function addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; declare var onpopstate: (ev: PopStateEvent) => any; -declare function addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; declare var onmspointerup: (ev: any) => any; -declare function addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; declare function msCancelRequestAnimationFrame(handle: number): void; declare function matchMedia(mediaQuery: string): MediaQueryList; declare function cancelAnimationFrame(handle: number): void; @@ -13229,10 +11639,10 @@ declare var msIndexedDB: IDBFactory; declare var indexedDB: IDBFactory; declare var console: Console; -///////////////////////////// -/// IE11 APIs -///////////////////////////// +///////////////////////////// +/// IE11 DOM APIs +///////////////////////////// interface StoreExceptionsInformation extends ExceptionInformation { @@ -13296,16 +11706,10 @@ interface NavigatorID { product: string; vendor: string; } -declare var NavigatorID: { - prototype: NavigatorID; - new (): NavigatorID; -} interface HTMLBodyElement { onpageshow: (ev: PageTransitionEvent) => any; - addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; onpagehide: (ev: PageTransitionEvent) => any; - addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; } interface MSExecAtPriorityFunctionCallback { @@ -13316,26 +11720,18 @@ interface MSWindowExtensions { captureEvents(): void; releaseEvents(): void; } -declare var MSWindowExtensions: { - prototype: MSWindowExtensions; - new (): MSWindowExtensions; -} interface MSGraphicsTrust { status: string; constrictionActive: boolean; } -declare var MSGraphicsTrust: { - prototype: MSGraphicsTrust; - new (): MSGraphicsTrust; -} interface AudioTrack { sourceBuffer: SourceBuffer; } interface DragEvent { - msConvertURL(file: File, targetType: string, targetURL?: string): boolean; + msConvertURL(file: File, targetType: string, targetURL?: string): void; } interface SubtleCrypto { @@ -13351,44 +11747,39 @@ interface SubtleCrypto { sign(algorithm: any, key: Key, buffer?: ArrayBufferView): CryptoOperation; decrypt(algorithm: any, key: Key, buffer?: ArrayBufferView): CryptoOperation; } -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new (): SubtleCrypto; -} interface Crypto extends RandomSource { subtle: SubtleCrypto; } -declare var Crypto: { - prototype: Crypto; - new (): Crypto; -} interface VideoPlaybackQuality { + totalFrameDelay: number; creationTime: number; totalVideoFrames: number; droppedVideoFrames: number; } -declare var VideoPlaybackQuality: { - prototype: VideoPlaybackQuality; - new (): VideoPlaybackQuality; + +interface GlobalEventHandlers { + onpointerenter: (ev: PointerEvent) => any; + onpointerout: (ev: PointerEvent) => any; + onpointerdown: (ev: PointerEvent) => any; + onpointerup: (ev: PointerEvent) => any; + onpointercancel: (ev: PointerEvent) => any; + onpointerover: (ev: PointerEvent) => any; + onpointermove: (ev: PointerEvent) => any; + onpointerleave: (ev: PointerEvent) => any; } -interface Window { +interface Window extends GlobalEventHandlers { onpageshow: (ev: PageTransitionEvent) => any; - addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; ondevicemotion: (ev: DeviceMotionEvent) => any; - addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; devicePixelRatio: number; msCrypto: Crypto; ondeviceorientation: (ev: DeviceOrientationEvent) => any; - addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; + doNotTrack: string; onmspointerenter: (ev: any) => any; - addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; onpagehide: (ev: PageTransitionEvent) => any; - addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; onmspointerleave: (ev: any) => any; - addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; } interface Key { @@ -13397,15 +11788,9 @@ interface Key { extractable: boolean; keyUsage: string[]; } -declare var Key: { - prototype: Key; - new (): Key; -} interface TextTrackList extends EventTarget { onaddtrack: (ev: any) => any; - addEventListener(type: "addtrack", listener: (ev: any) => any, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface DeviceAcceleration { @@ -13413,10 +11798,6 @@ interface DeviceAcceleration { x: number; z: number; } -declare var DeviceAcceleration: { - prototype: DeviceAcceleration; - new (): DeviceAcceleration; -} interface Console { count(countTitle?: string): void; @@ -13432,45 +11813,35 @@ interface Console { } interface MSNavigatorDoNotTrack { - removeSiteSpecificTrackingException(args: ExceptionInformation): boolean; - removeWebWideTrackingException(args: ExceptionInformation): boolean; + removeSiteSpecificTrackingException(args: ExceptionInformation): void; + removeWebWideTrackingException(args: ExceptionInformation): void; storeWebWideTrackingException(args: StoreExceptionsInformation): void; storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; confirmWebWideTrackingException(args: ExceptionInformation): boolean; } -declare var MSNavigatorDoNotTrack: { - prototype: MSNavigatorDoNotTrack; - new (): MSNavigatorDoNotTrack; -} interface HTMLImageElement { crossOrigin: string; + msPlayToPreferredSourceUri: string; } interface HTMLAllCollection extends HTMLCollection { namedItem(name: string): Element; -} -declare var HTMLAllCollection: { - prototype: HTMLAllCollection; - new (): HTMLAllCollection; + //[name: string]: Element; } interface MSNavigatorExtensions { language: string; } -declare var MSNavigatorExtensions: { - prototype: MSNavigatorExtensions; - new (): MSNavigatorExtensions; -} interface AesGcmEncryptResult { ciphertext: ArrayBuffer; tag: ArrayBuffer; } -declare var AesGcmEncryptResult: { - prototype: AesGcmEncryptResult; - new (): AesGcmEncryptResult; + +interface HTMLSourceElement { + msKeySystem: string; } interface CSSStyleDeclaration { @@ -13489,6 +11860,7 @@ interface CSSStyleDeclaration { flexWrap: string; borderImageOutset: string; flexDirection: string; + touchAction: string; flexFlow: string; borderImage: string; justifyContent: string; @@ -13496,18 +11868,10 @@ interface CSSStyleDeclaration { msTextCombineHorizontal: string; } -interface HTMLSourceElement { - msKeySystem: string; -} - interface NavigationCompletedEvent extends NavigationEvent { webErrorStatus: number; isSuccess: boolean; } -declare var NavigationCompletedEvent: { - prototype: NavigationCompletedEvent; - new (): NavigationCompletedEvent; -} interface MutationRecord { oldValue: string; @@ -13520,22 +11884,19 @@ interface MutationRecord { attributeNamespace: string; type: string; } -declare var MutationRecord: { - prototype: MutationRecord; - new (): MutationRecord; + +interface Navigator { + pointerEnabled: boolean; + maxTouchPoints: number; } -interface Document extends MSDocumentExtensions { +interface Document extends MSDocumentExtensions, GlobalEventHandlers { msFullscreenEnabled: boolean; onmsfullscreenerror: (ev: any) => any; - addEventListener(type: "msfullscreenerror", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerenter: (ev: any) => any; - addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; msFullscreenElement: Element; onmsfullscreenchange: (ev: any) => any; - addEventListener(type: "msfullscreenchange", listener: (ev: any) => any, useCapture?: boolean): void; onmspointerleave: (ev: any) => any; - addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; msExitFullscreen(): void; } @@ -13544,10 +11905,7 @@ interface MimeTypeArray { item(index: number): Plugin; [index: number]: Plugin; namedItem(type: string): Plugin; -} -declare var MimeTypeArray: { - prototype: MimeTypeArray; - new (): MimeTypeArray; + //[type: string]: Plugin; } interface HTMLMediaElement { @@ -13556,7 +11914,6 @@ interface HTMLMediaElement { */ msPlayToPreferredSourceUri: string; onmsneedkey: (ev: MSMediaKeyNeededEvent) => any; - addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; /** * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. */ @@ -13564,7 +11921,6 @@ interface HTMLMediaElement { msGraphicsTrustStatus: MSGraphicsTrust; msSetMediaKeys(mediaKeys: MSMediaKeys): void; addTextTrack(kind: string, label?: string, language?: string): TextTrack; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface TextTrack { @@ -13574,23 +11930,12 @@ interface TextTrack { interface KeyOperation extends EventTarget { oncomplete: (ev: any) => any; - addEventListener(type: "complete", listener: (ev: any) => any, useCapture?: boolean): void; onerror: (ev: any) => any; - addEventListener(type: "error", listener: (ev: any) => any, useCapture?: boolean): void; result: any; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; -} -declare var KeyOperation: { - prototype: KeyOperation; - new (): KeyOperation; } interface DOMStringMap { } -declare var DOMStringMap: { - prototype: DOMStringMap; - new (): DOMStringMap; -} interface DeviceOrientationEvent extends Event { gamma: number; @@ -13599,19 +11944,6 @@ interface DeviceOrientationEvent extends Event { beta: number; initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number, beta: number, gamma: number, absolute: boolean): void; } -declare var DeviceOrientationEvent: { - prototype: DeviceOrientationEvent; - new (): DeviceOrientationEvent; -} - -interface MSMediaKeyMessageEvent extends Event { - destinationURL: string; - message: Uint8Array; -} -declare var MSMediaKeyMessageEvent: { - prototype: MSMediaKeyMessageEvent; - new (): MSMediaKeyMessageEvent; -} interface MSMediaKeys { keySystem: string; @@ -13623,6 +11955,11 @@ declare var MSMediaKeys: { new (): MSMediaKeys; } +interface MSMediaKeyMessageEvent extends Event { + destinationURL: string; + message: Uint8Array; +} + interface MSHTMLWebViewElement extends HTMLElement { documentTitle: string; width: number; @@ -13643,26 +11980,20 @@ interface MSHTMLWebViewElement extends HTMLElement { invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; } -declare var MSHTMLWebViewElement: { - prototype: MSHTMLWebViewElement; - new (): MSHTMLWebViewElement; -} interface NavigationEvent extends Event { uri: string; } -declare var NavigationEvent: { - prototype: NavigationEvent; - new (): NavigationEvent; -} -interface Element { +interface Element extends GlobalEventHandlers { + onlostpointercapture: (ev: PointerEvent) => any; onmspointerenter: (ev: any) => any; - addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + ongotpointercapture: (ev: PointerEvent) => any; onmspointerleave: (ev: any) => any; - addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; msZoomTo(args: MsZoomToOptions): void; + setPointerCapture(pointerId: number): void; msGetUntransformedBounds(): ClientRect; + releasePointerCapture(pointerId: number): void; msRequestFullscreen(): void; } @@ -13688,30 +12019,18 @@ interface SourceBuffer extends EventTarget { abort(): void; appendStream(stream: MSStream, maxSize?: number): void; } -declare var SourceBuffer: { - prototype: SourceBuffer; - new (): SourceBuffer; -} interface MSInputMethodContext extends EventTarget { oncandidatewindowshow: (ev: any) => any; - addEventListener(type: "candidatewindowshow", listener: (ev: any) => any, useCapture?: boolean): void; target: HTMLElement; compositionStartOffset: number; oncandidatewindowhide: (ev: any) => any; - addEventListener(type: "candidatewindowhide", listener: (ev: any) => any, useCapture?: boolean): void; oncandidatewindowupdate: (ev: any) => any; - addEventListener(type: "candidatewindowupdate", listener: (ev: any) => any, useCapture?: boolean): void; compositionEndOffset: number; getCompositionAlternatives(): string[]; getCandidateWindowClientRect(): ClientRect; hasComposition(): boolean; isCandidateWindowVisible(): boolean; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; -} -declare var MSInputMethodContext: { - prototype: MSInputMethodContext; - new (): MSInputMethodContext; } interface DeviceRotationRate { @@ -13719,10 +12038,6 @@ interface DeviceRotationRate { alpha: number; beta: number; } -declare var DeviceRotationRate: { - prototype: DeviceRotationRate; - new (): DeviceRotationRate; -} interface PluginArray { length: number; @@ -13730,10 +12045,7 @@ interface PluginArray { item(index: number): Plugin; [index: number]: Plugin; namedItem(name: string): Plugin; -} -declare var PluginArray: { - prototype: PluginArray; - new (): PluginArray; + //[name: string]: Plugin; } interface MSMediaKeyError { @@ -13747,8 +12059,6 @@ interface MSMediaKeyError { MS_MEDIA_KEYERR_CLIENT: number; } declare var MSMediaKeyError: { - prototype: MSMediaKeyError; - new (): MSMediaKeyError; MS_MEDIA_KEYERR_SERVICE: number; MS_MEDIA_KEYERR_HARDWARECHANGE: number; MS_MEDIA_KEYERR_OUTPUT: number; @@ -13766,32 +12076,25 @@ interface Plugin { item(index: number): MimeType; [index: number]: MimeType; namedItem(type: string): MimeType; -} -declare var Plugin: { - prototype: Plugin; - new (): Plugin; + //[type: string]: MimeType; } interface HTMLFrameSetElement { onpageshow: (ev: PageTransitionEvent) => any; - addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; onpagehide: (ev: PageTransitionEvent) => any; - addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; } interface Screen extends EventTarget { msOrientation: string; onmsorientationchange: (ev: any) => any; - addEventListener(type: "msorientationchange", listener: (ev: any) => any, useCapture?: boolean): void; msLockOrientation(orientations: string[]): boolean; msUnlockOrientation(): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface MediaSource extends EventTarget { sourceBuffers: SourceBufferList; - duration: string; - readyState: any; + duration: number; + readyState: string; activeSourceBuffers: SourceBufferList; addSourceBuffer(type: string): SourceBuffer; endOfStream(error?: string): void; @@ -13807,7 +12110,6 @@ interface MediaError { MS_MEDIA_ERR_ENCRYPTED: number; } //declare var MediaError: { -// prototype: MediaError; // MS_MEDIA_ERR_ENCRYPTED: number; //} @@ -13816,17 +12118,9 @@ interface SourceBufferList extends EventTarget { item(index: number): SourceBuffer; [index: number]: SourceBuffer; } -declare var SourceBufferList: { - prototype: SourceBufferList; - new (): SourceBufferList; -} interface XMLDocument extends Document { } -declare var XMLDocument: { - prototype: XMLDocument; - new (): XMLDocument; -} interface DeviceMotionEvent extends Event { rotationRate: DeviceRotationRate; @@ -13835,10 +12129,6 @@ interface DeviceMotionEvent extends Event { accelerationIncludingGravity: DeviceAcceleration; initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict, accelerationIncludingGravity: DeviceAccelerationDict, rotationRate: DeviceRotationRateDict, interval: number): void; } -declare var DeviceMotionEvent: { - prototype: DeviceMotionEvent; - new (): DeviceMotionEvent; -} interface MimeType { enabledPlugin: Plugin; @@ -13846,9 +12136,23 @@ interface MimeType { type: string; description: string; } -declare var MimeType: { - prototype: MimeType; - new (): MimeType; + +interface PointerEvent extends MouseEvent { + width: number; + rotation: number; + pressure: number; + pointerType: any; + isPrimary: boolean; + tiltY: number; + height: number; + intermediatePoints: any; + currentPoint: any; + tiltX: number; + hwTimestamp: number; + pointerId: number; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; } interface MSDocumentExtensions { @@ -13869,12 +12173,11 @@ interface MutationObserver { } declare var MutationObserver: { prototype: MutationObserver; - new (callback: (arr: MutationRecord[], observer: MutationObserver)=>any): MutationObserver; + new (): MutationObserver; } interface AudioTrackList { onremovetrack: (ev: PluginArray) => any; - //addEventListener(type: "removetrack", listener: (ev: PluginArray) => any, useCapture?: boolean): void; } interface HTMLObjectElement { @@ -13890,6 +12193,7 @@ interface HTMLObjectElement { * Gets or sets whether the DLNA PlayTo device is available. */ msPlayToDisabled: boolean; + readyState: number; /** * Gets the source associated with the media element for use by the PlayToManager. */ @@ -13909,6 +12213,7 @@ interface HTMLEmbedElement { * Gets or sets whether the DLNA PlayTo device is available. */ msPlayToDisabled: boolean; + readyState: string; /** * Gets the source associated with the media element for use by the PlayToManager. */ @@ -13918,15 +12223,12 @@ interface HTMLEmbedElement { interface MSWebViewAsyncOperation extends EventTarget { target: MSHTMLWebViewElement; oncomplete: (ev: any) => any; - addEventListener(type: "complete", listener: (ev: any) => any, useCapture?: boolean): void; error: DOMError; onerror: (ev: any) => any; - addEventListener(type: "error", listener: (ev: any) => any, useCapture?: boolean): void; readyState: number; type: number; result: any; start(): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; ERROR: number; TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; TYPE_INVOKE_SCRIPT: number; @@ -13935,8 +12237,6 @@ interface MSWebViewAsyncOperation extends EventTarget { STARTED: number; } declare var MSWebViewAsyncOperation: { - prototype: MSWebViewAsyncOperation; - new (): MSWebViewAsyncOperation; ERROR: number; TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; TYPE_INVOKE_SCRIPT: number; @@ -13949,10 +12249,6 @@ interface ScriptNotifyEvent extends Event { value: string; callingUri: string; } -declare var ScriptNotifyEvent: { - prototype: ScriptNotifyEvent; - new (): ScriptNotifyEvent; -} interface PerformanceNavigationTiming extends PerformanceEntry { redirectStart: number; @@ -13978,18 +12274,10 @@ interface PerformanceNavigationTiming extends PerformanceEntry { domContentLoadedEventEnd: number; type: string; } -declare var PerformanceNavigationTiming: { - prototype: PerformanceNavigationTiming; - new (): PerformanceNavigationTiming; -} interface MSMediaKeyNeededEvent extends Event { initData: Uint8Array; } -declare var MSMediaKeyNeededEvent: { - prototype: MSMediaKeyNeededEvent; - new (): MSMediaKeyNeededEvent; -} interface MSManipulationEvent { MS_MANIPULATION_STATE_SELECTING: number; @@ -13999,7 +12287,6 @@ interface MSManipulationEvent { MS_MANIPULATION_STATE_CANCELLED: number; } //declare var MSManipulationEvent: { -// prototype: MSManipulationEvent; // MS_MANIPULATION_STATE_SELECTING: number; // MS_MANIPULATION_STATE_COMMITTED: number; // MS_MANIPULATION_STATE_PRESELECT: number; @@ -14011,50 +12298,41 @@ interface LongRunningScriptDetectedEvent extends Event { stopPageScriptExecution: boolean; executionTime: number; } -declare var LongRunningScriptDetectedEvent: { - prototype: LongRunningScriptDetectedEvent; - new (): LongRunningScriptDetectedEvent; -} interface MSAppView { viewId: number; close(): void; postMessage(message: any, targetOrigin: string, ports?: any): void; } -declare var MSAppView: { - prototype: MSAppView; - new (): MSAppView; -} interface PerfWidgetExternal { maxCpuSpeed: number; - performanceCounterFrequency: number; + independentRenderingEnabled: boolean; + irDisablingContentString: string; + irStatusAvailable: boolean; performanceCounter: number; averagePaintTime: number; activeNetworkRequestCount: number; paintRequestsPerSecond: number; + extraInformationEnabled: boolean; + performanceCounterFrequency: number; + averageFrameTime: number; repositionWindow(x: number, y: number): void; getRecentMemoryUsage(last: number): any; getMemoryUsage(): number; resizeWindow(width: number, height: number): void; getProcessCpuUsage(): number; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; removeEventListener(eventType: string, callback: (ev: any) => any): void; getRecentCpuUsage(last: number): any; addEventListener(eventType: string, callback: (ev: any) => any): void; + getRecentFrames(last: number): any; getRecentPaintRequests(last: number): any; } -declare var PerfWidgetExternal: { - prototype: PerfWidgetExternal; - new (): PerfWidgetExternal; -} interface PageTransitionEvent extends Event { persisted: boolean; } -declare var PageTransitionEvent: { - prototype: PageTransitionEvent; - new (): PageTransitionEvent; -} interface MutationCallback { (mutations: MutationRecord[], observer: MutationObserver): void; @@ -14062,19 +12340,11 @@ interface MutationCallback { interface HTMLDocument extends Document { } -declare var HTMLDocument: { - prototype: HTMLDocument; - new (): HTMLDocument; -} interface KeyPair { privateKey: Key; publicKey: Key; } -declare var KeyPair: { - prototype: KeyPair; - new (): KeyPair; -} interface MSApp { getViewOpener(): MSAppView; @@ -14090,28 +12360,12 @@ interface MSApp { CURRENT: string; } //declare var MSApp: { -// prototype: MSApp; // NORMAL: string; // HIGH: string; // IDLE: string; // CURRENT: string; //} -interface HTMLTrackElement { - readyState: number; - ERROR: number; - LOADING: number; - LOADED: number; - NONE: number; -} -//declare var HTMLTrackElement: { -// prototype: HTMLTrackElement; -// ERROR: number; -// LOADING: number; -// LOADED: number; -// NONE: number; -//} - interface MSMediaKeySession extends EventTarget { sessionId: string; error: MSMediaKeyError; @@ -14119,59 +12373,2534 @@ interface MSMediaKeySession extends EventTarget { close(): void; update(key: Uint8Array): void; } -declare var MSMediaKeySession: { - prototype: MSMediaKeySession; - new (): MSMediaKeySession; + +interface HTMLTrackElement { + readyState: number; + ERROR: number; + LOADING: number; + LOADED: number; + NONE: number; } +//declare var HTMLTrackElement: { +// ERROR: number; +// LOADING: number; +// LOADED: number; +// NONE: number; +//} interface HTMLVideoElement { - videoPlaybackQuality: VideoPlaybackQuality; + getVideoPlaybackQuality(): VideoPlaybackQuality; } interface UnviewableContentIdentifiedEvent extends NavigationEvent { referrer: string; } -declare var UnviewableContentIdentifiedEvent: { - prototype: UnviewableContentIdentifiedEvent; - new (): UnviewableContentIdentifiedEvent; -} interface CryptoOperation extends EventTarget { algorithm: Algorithm; oncomplete: (ev: any) => any; - addEventListener(type: "complete", listener: (ev: any) => any, useCapture?: boolean): void; onerror: (ev: any) => any; - addEventListener(type: "error", listener: (ev: any) => any, useCapture?: boolean): void; onprogress: (ev: any) => any; - addEventListener(type: "progress", listener: (ev: any) => any, useCapture?: boolean): void; onabort: (ev: any) => any; - addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; key: Key; result: any; abort(): void; finish(): void; process(buffer: ArrayBufferView): void; - addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; -} -declare var CryptoOperation: { - prototype: CryptoOperation; - new (): CryptoOperation; } declare var onpageshow: (ev: PageTransitionEvent) => any; -declare function addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; declare var ondevicemotion: (ev: DeviceMotionEvent) => any; -declare function addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; declare var devicePixelRatio: number; declare var msCrypto: Crypto; declare var ondeviceorientation: (ev: DeviceOrientationEvent) => any; -declare function addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; +declare var doNotTrack: string; declare var onmspointerenter: (ev: any) => any; -declare function addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; declare var onpagehide: (ev: PageTransitionEvent) => any; -declare function addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; declare var onmspointerleave: (ev: any) => any; +declare var onpointerenter: (ev: PointerEvent) => any; +declare var onpointerout: (ev: PointerEvent) => any; +declare var onpointerdown: (ev: PointerEvent) => any; +declare var onpointerup: (ev: PointerEvent) => any; +declare var onpointercancel: (ev: PointerEvent) => any; +declare var onpointerover: (ev: PointerEvent) => any; +declare var onpointermove: (ev: PointerEvent) => any; +declare var onpointerleave: (ev: PointerEvent) => any; + + +///////////////////////////// +/// WebGL APIs +///////////////////////////// + + +interface WebGLTexture extends WebGLObject { +} + +interface OES_texture_float { +} + +interface WebGLContextEvent extends Event { + statusMessage: string; +} +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new (): WebGLContextEvent; +} + +interface WebGLRenderbuffer extends WebGLObject { +} + +interface WebGLUniformLocation { +} + +interface WebGLActiveInfo { + name: string; + type: number; + size: number; +} + +interface WEBGL_compressed_texture_s3tc { + COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} +declare var WEBGL_compressed_texture_s3tc: { + COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +interface WebGLContextAttributes { + alpha: boolean; + depth: boolean; + stencil: boolean; + antialias: boolean; + premultipliedAlpha: boolean; + preserveDrawingBuffer: boolean; +} + +interface WebGLRenderingContext { + drawingBufferWidth: number; + drawingBufferHeight: number; + canvas: HTMLCanvasElement; + getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation; + bindTexture(target: number, texture: WebGLTexture): void; + bufferData(target: number, size: number, usage: number): void; + depthMask(flag: boolean): void; + getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; + vertexAttrib3fv(indx: number, values: Float32Array): void; + linkProgram(program: WebGLProgram): void; + getSupportedExtensions(): string[]; + bufferSubData(target: number, offset: number, data: ArrayBufferView): void; + vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; + polygonOffset(factor: number, units: number): void; + blendColor(red: number, green: number, blue: number, alpha: number): void; + createTexture(): WebGLTexture; + hint(target: number, mode: number): void; + getVertexAttrib(index: number, pname: number): any; + enableVertexAttribArray(index: number): void; + depthRange(zNear: number, zFar: number): void; + cullFace(mode: number): void; + createFramebuffer(): WebGLFramebuffer; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture, level: number): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer): void; + colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + getExtension(name: string): Object; + createProgram(): WebGLProgram; + deleteShader(shader: WebGLShader): void; + getAttachedShaders(program: WebGLProgram): WebGLShader[]; + enable(cap: number): void; + blendEquation(mode: number): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; + createBuffer(): WebGLBuffer; + deleteTexture(texture: WebGLTexture): void; + useProgram(program: WebGLProgram): void; + vertexAttrib2fv(indx: number, values: Float32Array): void; + checkFramebufferStatus(target: number): number; + frontFace(mode: number): void; + getBufferParameter(target: number, pname: number): any; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; + copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; + getVertexAttribOffset(index: number, pname: number): number; + disableVertexAttribArray(index: number): void; + blendFunc(sfactor: number, dfactor: number): void; + drawElements(mode: number, count: number, type: number, offset: number): void; + isFramebuffer(framebuffer: WebGLFramebuffer): boolean; + uniform3iv(location: WebGLUniformLocation, v: Int32Array): void; + lineWidth(width: number): void; + getShaderInfoLog(shader: WebGLShader): string; + getTexParameter(target: number, pname: number): any; + getParameter(pname: number): any; + getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat; + getContextAttributes(): WebGLContextAttributes; + vertexAttrib1f(indx: number, x: number): void; + bindFramebuffer(target: number, framebuffer: WebGLFramebuffer): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; + isContextLost(): boolean; + uniform1iv(location: WebGLUniformLocation, v: Int32Array): void; + getRenderbufferParameter(target: number, pname: number): any; + uniform2fv(location: WebGLUniformLocation, v: Float32Array): void; + isTexture(texture: WebGLTexture): boolean; + getError(): number; + shaderSource(shader: WebGLShader, source: string): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer): void; + stencilMask(mask: number): void; + bindBuffer(target: number, buffer: WebGLBuffer): void; + getAttribLocation(program: WebGLProgram, name: string): number; + uniform3i(location: WebGLUniformLocation, x: number, y: number, z: number): void; + blendEquationSeparate(modeRGB: number, modeAlpha: number): void; + clear(mask: number): void; + blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; + stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + scissor(x: number, y: number, width: number, height: number): void; + uniform2i(location: WebGLUniformLocation, x: number, y: number): void; + getActiveAttrib(program: WebGLProgram, index: number): WebGLActiveInfo; + getShaderSource(shader: WebGLShader): string; + generateMipmap(target: number): void; + bindAttribLocation(program: WebGLProgram, index: number, name: string): void; + uniform1fv(location: WebGLUniformLocation, v: Float32Array): void; + uniform2iv(location: WebGLUniformLocation, v: Int32Array): void; + stencilOp(fail: number, zfail: number, zpass: number): void; + uniform4fv(location: WebGLUniformLocation, v: Float32Array): void; + vertexAttrib1fv(indx: number, values: Float32Array): void; + flush(): void; + uniform4f(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + deleteProgram(program: WebGLProgram): void; + isRenderbuffer(renderbuffer: WebGLRenderbuffer): boolean; + uniform1i(location: WebGLUniformLocation, x: number): void; + getProgramParameter(program: WebGLProgram, pname: number): any; + getActiveUniform(program: WebGLProgram, index: number): WebGLActiveInfo; + stencilFunc(func: number, ref: number, mask: number): void; + pixelStorei(pname: number, param: number): void; + disable(cap: number): void; + vertexAttrib4fv(indx: number, values: Float32Array): void; + createRenderbuffer(): WebGLRenderbuffer; + isBuffer(buffer: WebGLBuffer): boolean; + stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; + getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; + uniform4i(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + sampleCoverage(value: number, invert: boolean): void; + depthFunc(func: number): void; + texParameterf(target: number, pname: number, param: number): void; + vertexAttrib3f(indx: number, x: number, y: number, z: number): void; + drawArrays(mode: number, first: number, count: number): void; + texParameteri(target: number, pname: number, param: number): void; + vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; + getShaderParameter(shader: WebGLShader, pname: number): any; + clearDepth(depth: number): void; + activeTexture(texture: number): void; + viewport(x: number, y: number, width: number, height: number): void; + detachShader(program: WebGLProgram, shader: WebGLShader): void; + uniform1f(location: WebGLUniformLocation, x: number): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + deleteBuffer(buffer: WebGLBuffer): void; + copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; + uniform3fv(location: WebGLUniformLocation, v: Float32Array): void; + stencilMaskSeparate(face: number, mask: number): void; + attachShader(program: WebGLProgram, shader: WebGLShader): void; + compileShader(shader: WebGLShader): void; + clearColor(red: number, green: number, blue: number, alpha: number): void; + isShader(shader: WebGLShader): boolean; + clearStencil(s: number): void; + framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer): void; + finish(): void; + uniform2f(location: WebGLUniformLocation, x: number, y: number): void; + renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; + uniform3f(location: WebGLUniformLocation, x: number, y: number, z: number): void; + getProgramInfoLog(program: WebGLProgram): string; + validateProgram(program: WebGLProgram): void; + isEnabled(cap: number): boolean; + vertexAttrib2f(indx: number, x: number, y: number): void; + isProgram(program: WebGLProgram): boolean; + createShader(type: number): WebGLShader; + bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer): void; + uniform4iv(location: WebGLUniformLocation, v: Int32Array): void; + DEPTH_FUNC: number; + DEPTH_COMPONENT16: number; + REPLACE: number; + REPEAT: number; + VERTEX_ATTRIB_ARRAY_ENABLED: number; + FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + STENCIL_BUFFER_BIT: number; + RENDERER: number; + STENCIL_BACK_REF: number; + TEXTURE26: number; + RGB565: number; + DITHER: number; + CONSTANT_COLOR: number; + GENERATE_MIPMAP_HINT: number; + POINTS: number; + DECR: number; + INT_VEC3: number; + TEXTURE28: number; + ONE_MINUS_CONSTANT_ALPHA: number; + BACK: number; + RENDERBUFFER_STENCIL_SIZE: number; + UNPACK_FLIP_Y_WEBGL: number; + BLEND: number; + TEXTURE9: number; + ARRAY_BUFFER_BINDING: number; + MAX_VIEWPORT_DIMS: number; + INVALID_FRAMEBUFFER_OPERATION: number; + TEXTURE: number; + TEXTURE0: number; + TEXTURE31: number; + TEXTURE24: number; + HIGH_INT: number; + RENDERBUFFER_BINDING: number; + BLEND_COLOR: number; + FASTEST: number; + STENCIL_WRITEMASK: number; + ALIASED_POINT_SIZE_RANGE: number; + TEXTURE12: number; + DST_ALPHA: number; + BLEND_EQUATION_RGB: number; + FRAMEBUFFER_COMPLETE: number; + NEAREST_MIPMAP_NEAREST: number; + VERTEX_ATTRIB_ARRAY_SIZE: number; + TEXTURE3: number; + DEPTH_WRITEMASK: number; + CONTEXT_LOST_WEBGL: number; + INVALID_VALUE: number; + TEXTURE_MAG_FILTER: number; + ONE_MINUS_CONSTANT_COLOR: number; + ONE_MINUS_SRC_ALPHA: number; + TEXTURE_CUBE_MAP_POSITIVE_Z: number; + NOTEQUAL: number; + ALPHA: number; + DEPTH_STENCIL: number; + MAX_VERTEX_UNIFORM_VECTORS: number; + DEPTH_COMPONENT: number; + RENDERBUFFER_RED_SIZE: number; + TEXTURE20: number; + RED_BITS: number; + RENDERBUFFER_BLUE_SIZE: number; + SCISSOR_BOX: number; + VENDOR: number; + FRONT_AND_BACK: number; + CONSTANT_ALPHA: number; + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + NEAREST: number; + CULL_FACE: number; + ALIASED_LINE_WIDTH_RANGE: number; + TEXTURE19: number; + FRONT: number; + DEPTH_CLEAR_VALUE: number; + GREEN_BITS: number; + TEXTURE29: number; + TEXTURE23: number; + MAX_RENDERBUFFER_SIZE: number; + STENCIL_ATTACHMENT: number; + TEXTURE27: number; + BOOL_VEC2: number; + OUT_OF_MEMORY: number; + MIRRORED_REPEAT: number; + POLYGON_OFFSET_UNITS: number; + TEXTURE_MIN_FILTER: number; + STENCIL_BACK_PASS_DEPTH_PASS: number; + LINE_LOOP: number; + FLOAT_MAT3: number; + TEXTURE14: number; + LINEAR: number; + RGB5_A1: number; + ONE_MINUS_SRC_COLOR: number; + SAMPLE_COVERAGE_INVERT: number; + DONT_CARE: number; + FRAMEBUFFER_BINDING: number; + RENDERBUFFER_ALPHA_SIZE: number; + STENCIL_REF: number; + ZERO: number; + DECR_WRAP: number; + SAMPLE_COVERAGE: number; + STENCIL_BACK_FUNC: number; + TEXTURE30: number; + VIEWPORT: number; + STENCIL_BITS: number; + FLOAT: number; + COLOR_WRITEMASK: number; + SAMPLE_COVERAGE_VALUE: number; + TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + STENCIL_BACK_FAIL: number; + FLOAT_MAT4: number; + UNSIGNED_SHORT_4_4_4_4: number; + TEXTURE6: number; + RENDERBUFFER_WIDTH: number; + RGBA4: number; + ALWAYS: number; + BLEND_EQUATION_ALPHA: number; + COLOR_BUFFER_BIT: number; + TEXTURE_CUBE_MAP: number; + DEPTH_BUFFER_BIT: number; + STENCIL_CLEAR_VALUE: number; + BLEND_EQUATION: number; + RENDERBUFFER_GREEN_SIZE: number; + NEAREST_MIPMAP_LINEAR: number; + VERTEX_ATTRIB_ARRAY_TYPE: number; + INCR_WRAP: number; + ONE_MINUS_DST_COLOR: number; + HIGH_FLOAT: number; + BYTE: number; + FRONT_FACE: number; + SAMPLE_ALPHA_TO_COVERAGE: number; + CCW: number; + TEXTURE13: number; + MAX_VERTEX_ATTRIBS: number; + MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_WRAP_T: number; + UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + FLOAT_VEC2: number; + LUMINANCE: number; + GREATER: number; + INT_VEC2: number; + VALIDATE_STATUS: number; + FRAMEBUFFER: number; + FRAMEBUFFER_UNSUPPORTED: number; + TEXTURE5: number; + FUNC_SUBTRACT: number; + BLEND_DST_ALPHA: number; + SAMPLER_CUBE: number; + ONE_MINUS_DST_ALPHA: number; + LESS: number; + TEXTURE_CUBE_MAP_POSITIVE_X: number; + BLUE_BITS: number; + DEPTH_TEST: number; + VERTEX_ATTRIB_ARRAY_STRIDE: number; + DELETE_STATUS: number; + TEXTURE18: number; + POLYGON_OFFSET_FACTOR: number; + UNSIGNED_INT: number; + TEXTURE_2D: number; + DST_COLOR: number; + FLOAT_MAT2: number; + COMPRESSED_TEXTURE_FORMATS: number; + MAX_FRAGMENT_UNIFORM_VECTORS: number; + DEPTH_STENCIL_ATTACHMENT: number; + LUMINANCE_ALPHA: number; + CW: number; + VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + LINEAR_MIPMAP_LINEAR: number; + BUFFER_SIZE: number; + SAMPLE_BUFFERS: number; + TEXTURE15: number; + ACTIVE_TEXTURE: number; + VERTEX_SHADER: number; + TEXTURE22: number; + VERTEX_ATTRIB_ARRAY_POINTER: number; + INCR: number; + COMPILE_STATUS: number; + MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + TEXTURE7: number; + UNSIGNED_SHORT_5_5_5_1: number; + DEPTH_BITS: number; + RGBA: number; + TRIANGLE_STRIP: number; + COLOR_CLEAR_VALUE: number; + BROWSER_DEFAULT_WEBGL: number; + INVALID_ENUM: number; + SCISSOR_TEST: number; + LINE_STRIP: number; + FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + STENCIL_FUNC: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + RENDERBUFFER_HEIGHT: number; + TEXTURE8: number; + TRIANGLES: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + STENCIL_BACK_VALUE_MASK: number; + TEXTURE25: number; + RENDERBUFFER: number; + LEQUAL: number; + TEXTURE1: number; + STENCIL_INDEX8: number; + FUNC_ADD: number; + STENCIL_FAIL: number; + BLEND_SRC_ALPHA: number; + BOOL: number; + ALPHA_BITS: number; + LOW_INT: number; + TEXTURE10: number; + SRC_COLOR: number; + MAX_VARYING_VECTORS: number; + BLEND_DST_RGB: number; + TEXTURE_BINDING_CUBE_MAP: number; + STENCIL_INDEX: number; + TEXTURE_BINDING_2D: number; + MEDIUM_INT: number; + SHADER_TYPE: number; + POLYGON_OFFSET_FILL: number; + DYNAMIC_DRAW: number; + TEXTURE4: number; + STENCIL_BACK_PASS_DEPTH_FAIL: number; + STREAM_DRAW: number; + MAX_CUBE_MAP_TEXTURE_SIZE: number; + TEXTURE17: number; + TRIANGLE_FAN: number; + UNPACK_ALIGNMENT: number; + CURRENT_PROGRAM: number; + LINES: number; + INVALID_OPERATION: number; + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + LINEAR_MIPMAP_NEAREST: number; + CLAMP_TO_EDGE: number; + RENDERBUFFER_DEPTH_SIZE: number; + TEXTURE_WRAP_S: number; + ELEMENT_ARRAY_BUFFER: number; + UNSIGNED_SHORT_5_6_5: number; + ACTIVE_UNIFORMS: number; + FLOAT_VEC3: number; + NO_ERROR: number; + ATTACHED_SHADERS: number; + DEPTH_ATTACHMENT: number; + TEXTURE11: number; + STENCIL_TEST: number; + ONE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + STATIC_DRAW: number; + GEQUAL: number; + BOOL_VEC4: number; + COLOR_ATTACHMENT0: number; + PACK_ALIGNMENT: number; + MAX_TEXTURE_SIZE: number; + STENCIL_PASS_DEPTH_FAIL: number; + CULL_FACE_MODE: number; + TEXTURE16: number; + STENCIL_BACK_WRITEMASK: number; + SRC_ALPHA: number; + UNSIGNED_SHORT: number; + TEXTURE21: number; + FUNC_REVERSE_SUBTRACT: number; + SHADING_LANGUAGE_VERSION: number; + EQUAL: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + BOOL_VEC3: number; + SAMPLER_2D: number; + TEXTURE_CUBE_MAP_NEGATIVE_X: number; + MAX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_CUBE_MAP_POSITIVE_Y: number; + RENDERBUFFER_INTERNAL_FORMAT: number; + STENCIL_VALUE_MASK: number; + ELEMENT_ARRAY_BUFFER_BINDING: number; + ARRAY_BUFFER: number; + DEPTH_RANGE: number; + NICEST: number; + ACTIVE_ATTRIBUTES: number; + NEVER: number; + FLOAT_VEC4: number; + CURRENT_VERTEX_ATTRIB: number; + STENCIL_PASS_DEPTH_PASS: number; + INVERT: number; + LINK_STATUS: number; + RGB: number; + INT_VEC4: number; + TEXTURE2: number; + UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + MEDIUM_FLOAT: number; + SRC_ALPHA_SATURATE: number; + BUFFER_USAGE: number; + SHORT: number; + NONE: number; + UNSIGNED_BYTE: number; + INT: number; + SUBPIXEL_BITS: number; + KEEP: number; + SAMPLES: number; + FRAGMENT_SHADER: number; + LINE_WIDTH: number; + BLEND_SRC_RGB: number; + LOW_FLOAT: number; + VERSION: number; +} +declare var WebGLRenderingContext: { + DEPTH_FUNC: number; + DEPTH_COMPONENT16: number; + REPLACE: number; + REPEAT: number; + VERTEX_ATTRIB_ARRAY_ENABLED: number; + FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + STENCIL_BUFFER_BIT: number; + RENDERER: number; + STENCIL_BACK_REF: number; + TEXTURE26: number; + RGB565: number; + DITHER: number; + CONSTANT_COLOR: number; + GENERATE_MIPMAP_HINT: number; + POINTS: number; + DECR: number; + INT_VEC3: number; + TEXTURE28: number; + ONE_MINUS_CONSTANT_ALPHA: number; + BACK: number; + RENDERBUFFER_STENCIL_SIZE: number; + UNPACK_FLIP_Y_WEBGL: number; + BLEND: number; + TEXTURE9: number; + ARRAY_BUFFER_BINDING: number; + MAX_VIEWPORT_DIMS: number; + INVALID_FRAMEBUFFER_OPERATION: number; + TEXTURE: number; + TEXTURE0: number; + TEXTURE31: number; + TEXTURE24: number; + HIGH_INT: number; + RENDERBUFFER_BINDING: number; + BLEND_COLOR: number; + FASTEST: number; + STENCIL_WRITEMASK: number; + ALIASED_POINT_SIZE_RANGE: number; + TEXTURE12: number; + DST_ALPHA: number; + BLEND_EQUATION_RGB: number; + FRAMEBUFFER_COMPLETE: number; + NEAREST_MIPMAP_NEAREST: number; + VERTEX_ATTRIB_ARRAY_SIZE: number; + TEXTURE3: number; + DEPTH_WRITEMASK: number; + CONTEXT_LOST_WEBGL: number; + INVALID_VALUE: number; + TEXTURE_MAG_FILTER: number; + ONE_MINUS_CONSTANT_COLOR: number; + ONE_MINUS_SRC_ALPHA: number; + TEXTURE_CUBE_MAP_POSITIVE_Z: number; + NOTEQUAL: number; + ALPHA: number; + DEPTH_STENCIL: number; + MAX_VERTEX_UNIFORM_VECTORS: number; + DEPTH_COMPONENT: number; + RENDERBUFFER_RED_SIZE: number; + TEXTURE20: number; + RED_BITS: number; + RENDERBUFFER_BLUE_SIZE: number; + SCISSOR_BOX: number; + VENDOR: number; + FRONT_AND_BACK: number; + CONSTANT_ALPHA: number; + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + NEAREST: number; + CULL_FACE: number; + ALIASED_LINE_WIDTH_RANGE: number; + TEXTURE19: number; + FRONT: number; + DEPTH_CLEAR_VALUE: number; + GREEN_BITS: number; + TEXTURE29: number; + TEXTURE23: number; + MAX_RENDERBUFFER_SIZE: number; + STENCIL_ATTACHMENT: number; + TEXTURE27: number; + BOOL_VEC2: number; + OUT_OF_MEMORY: number; + MIRRORED_REPEAT: number; + POLYGON_OFFSET_UNITS: number; + TEXTURE_MIN_FILTER: number; + STENCIL_BACK_PASS_DEPTH_PASS: number; + LINE_LOOP: number; + FLOAT_MAT3: number; + TEXTURE14: number; + LINEAR: number; + RGB5_A1: number; + ONE_MINUS_SRC_COLOR: number; + SAMPLE_COVERAGE_INVERT: number; + DONT_CARE: number; + FRAMEBUFFER_BINDING: number; + RENDERBUFFER_ALPHA_SIZE: number; + STENCIL_REF: number; + ZERO: number; + DECR_WRAP: number; + SAMPLE_COVERAGE: number; + STENCIL_BACK_FUNC: number; + TEXTURE30: number; + VIEWPORT: number; + STENCIL_BITS: number; + FLOAT: number; + COLOR_WRITEMASK: number; + SAMPLE_COVERAGE_VALUE: number; + TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + STENCIL_BACK_FAIL: number; + FLOAT_MAT4: number; + UNSIGNED_SHORT_4_4_4_4: number; + TEXTURE6: number; + RENDERBUFFER_WIDTH: number; + RGBA4: number; + ALWAYS: number; + BLEND_EQUATION_ALPHA: number; + COLOR_BUFFER_BIT: number; + TEXTURE_CUBE_MAP: number; + DEPTH_BUFFER_BIT: number; + STENCIL_CLEAR_VALUE: number; + BLEND_EQUATION: number; + RENDERBUFFER_GREEN_SIZE: number; + NEAREST_MIPMAP_LINEAR: number; + VERTEX_ATTRIB_ARRAY_TYPE: number; + INCR_WRAP: number; + ONE_MINUS_DST_COLOR: number; + HIGH_FLOAT: number; + BYTE: number; + FRONT_FACE: number; + SAMPLE_ALPHA_TO_COVERAGE: number; + CCW: number; + TEXTURE13: number; + MAX_VERTEX_ATTRIBS: number; + MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_WRAP_T: number; + UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + FLOAT_VEC2: number; + LUMINANCE: number; + GREATER: number; + INT_VEC2: number; + VALIDATE_STATUS: number; + FRAMEBUFFER: number; + FRAMEBUFFER_UNSUPPORTED: number; + TEXTURE5: number; + FUNC_SUBTRACT: number; + BLEND_DST_ALPHA: number; + SAMPLER_CUBE: number; + ONE_MINUS_DST_ALPHA: number; + LESS: number; + TEXTURE_CUBE_MAP_POSITIVE_X: number; + BLUE_BITS: number; + DEPTH_TEST: number; + VERTEX_ATTRIB_ARRAY_STRIDE: number; + DELETE_STATUS: number; + TEXTURE18: number; + POLYGON_OFFSET_FACTOR: number; + UNSIGNED_INT: number; + TEXTURE_2D: number; + DST_COLOR: number; + FLOAT_MAT2: number; + COMPRESSED_TEXTURE_FORMATS: number; + MAX_FRAGMENT_UNIFORM_VECTORS: number; + DEPTH_STENCIL_ATTACHMENT: number; + LUMINANCE_ALPHA: number; + CW: number; + VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + LINEAR_MIPMAP_LINEAR: number; + BUFFER_SIZE: number; + SAMPLE_BUFFERS: number; + TEXTURE15: number; + ACTIVE_TEXTURE: number; + VERTEX_SHADER: number; + TEXTURE22: number; + VERTEX_ATTRIB_ARRAY_POINTER: number; + INCR: number; + COMPILE_STATUS: number; + MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + TEXTURE7: number; + UNSIGNED_SHORT_5_5_5_1: number; + DEPTH_BITS: number; + RGBA: number; + TRIANGLE_STRIP: number; + COLOR_CLEAR_VALUE: number; + BROWSER_DEFAULT_WEBGL: number; + INVALID_ENUM: number; + SCISSOR_TEST: number; + LINE_STRIP: number; + FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + STENCIL_FUNC: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + RENDERBUFFER_HEIGHT: number; + TEXTURE8: number; + TRIANGLES: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + STENCIL_BACK_VALUE_MASK: number; + TEXTURE25: number; + RENDERBUFFER: number; + LEQUAL: number; + TEXTURE1: number; + STENCIL_INDEX8: number; + FUNC_ADD: number; + STENCIL_FAIL: number; + BLEND_SRC_ALPHA: number; + BOOL: number; + ALPHA_BITS: number; + LOW_INT: number; + TEXTURE10: number; + SRC_COLOR: number; + MAX_VARYING_VECTORS: number; + BLEND_DST_RGB: number; + TEXTURE_BINDING_CUBE_MAP: number; + STENCIL_INDEX: number; + TEXTURE_BINDING_2D: number; + MEDIUM_INT: number; + SHADER_TYPE: number; + POLYGON_OFFSET_FILL: number; + DYNAMIC_DRAW: number; + TEXTURE4: number; + STENCIL_BACK_PASS_DEPTH_FAIL: number; + STREAM_DRAW: number; + MAX_CUBE_MAP_TEXTURE_SIZE: number; + TEXTURE17: number; + TRIANGLE_FAN: number; + UNPACK_ALIGNMENT: number; + CURRENT_PROGRAM: number; + LINES: number; + INVALID_OPERATION: number; + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + LINEAR_MIPMAP_NEAREST: number; + CLAMP_TO_EDGE: number; + RENDERBUFFER_DEPTH_SIZE: number; + TEXTURE_WRAP_S: number; + ELEMENT_ARRAY_BUFFER: number; + UNSIGNED_SHORT_5_6_5: number; + ACTIVE_UNIFORMS: number; + FLOAT_VEC3: number; + NO_ERROR: number; + ATTACHED_SHADERS: number; + DEPTH_ATTACHMENT: number; + TEXTURE11: number; + STENCIL_TEST: number; + ONE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + STATIC_DRAW: number; + GEQUAL: number; + BOOL_VEC4: number; + COLOR_ATTACHMENT0: number; + PACK_ALIGNMENT: number; + MAX_TEXTURE_SIZE: number; + STENCIL_PASS_DEPTH_FAIL: number; + CULL_FACE_MODE: number; + TEXTURE16: number; + STENCIL_BACK_WRITEMASK: number; + SRC_ALPHA: number; + UNSIGNED_SHORT: number; + TEXTURE21: number; + FUNC_REVERSE_SUBTRACT: number; + SHADING_LANGUAGE_VERSION: number; + EQUAL: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + BOOL_VEC3: number; + SAMPLER_2D: number; + TEXTURE_CUBE_MAP_NEGATIVE_X: number; + MAX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_CUBE_MAP_POSITIVE_Y: number; + RENDERBUFFER_INTERNAL_FORMAT: number; + STENCIL_VALUE_MASK: number; + ELEMENT_ARRAY_BUFFER_BINDING: number; + ARRAY_BUFFER: number; + DEPTH_RANGE: number; + NICEST: number; + ACTIVE_ATTRIBUTES: number; + NEVER: number; + FLOAT_VEC4: number; + CURRENT_VERTEX_ATTRIB: number; + STENCIL_PASS_DEPTH_PASS: number; + INVERT: number; + LINK_STATUS: number; + RGB: number; + INT_VEC4: number; + TEXTURE2: number; + UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + MEDIUM_FLOAT: number; + SRC_ALPHA_SATURATE: number; + BUFFER_USAGE: number; + SHORT: number; + NONE: number; + UNSIGNED_BYTE: number; + INT: number; + SUBPIXEL_BITS: number; + KEEP: number; + SAMPLES: number; + FRAGMENT_SHADER: number; + LINE_WIDTH: number; + BLEND_SRC_RGB: number; + LOW_FLOAT: number; + VERSION: number; +} + +interface WebGLProgram extends WebGLObject { +} + +interface OES_standard_derivatives { + FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} +declare var OES_standard_derivatives: { + FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +interface WebGLFramebuffer extends WebGLObject { +} + +interface WebGLShader extends WebGLObject { +} + +interface OES_texture_float_linear { +} + +interface WebGLObject { +} + +interface WebGLBuffer extends WebGLObject { +} + +interface WebGLShaderPrecisionFormat { + rangeMin: number; + rangeMax: number; + precision: number; +} + +interface EXT_texture_filter_anisotropic { + TEXTURE_MAX_ANISOTROPY_EXT: number; + MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; +} +declare var EXT_texture_filter_anisotropic: { + TEXTURE_MAX_ANISOTROPY_EXT: number; + MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; +} + + +///////////////////////////// +/// addEventListener overloads +///////////////////////////// + +interface HTMLElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Document { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "msthumbnailclick", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stop", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mssitemodejumplistitemremoved", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectionchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "storagecommit", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msfullscreenerror", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msfullscreenchange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Element { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSNamespaceInfo { + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Window { + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface SVGElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLFrameElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface XMLHttpRequest { + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLFrameSetElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Screen { + addEventListener(type: "msorientationchange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface SVGSVGElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "zoom", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLIFrameElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLBodyElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface XDomainRequest { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLMarqueeElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "bounce", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "start", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "finish", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSWindowExtensions { + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLMediaElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLVideoElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoFrameStepCompleted", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoFormatChanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface TextTrackCue { + addEventListener(type: "enter", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "exit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface WebSocket { + addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface XMLHttpRequestEventTarget { + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface AudioTrackList { + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: "removetrack", listener: (ev: any /*PluginArray*/) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSBaseReader { + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} +interface IDBTransaction { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface TextTrackList { + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface IDBDatabase { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface IDBOpenDBRequest { + addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "upgradeneeded", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blocked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface TextTrack { + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface IDBRequest { + addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MessagePort { + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface ApplicationCache { + addEventListener(type: "downloading", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "updateready", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cached", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "obsolete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "checking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "noupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface AbstractWorker { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} +interface Worker { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface GlobalEventHandlers { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} +interface KeyOperation { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSInputMethodContext { + addEventListener(type: "candidatewindowshow", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "candidatewindowhide", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "candidatewindowupdate", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSWebViewAsyncOperation { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface CryptoOperation { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + + +declare function addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; ///////////////////////////// diff --git a/_infrastructure/tests/typescript/0.9.5-beta/tsc b/_infrastructure/tests/typescript/0.9.7/tsc similarity index 100% rename from _infrastructure/tests/typescript/0.9.5-beta/tsc rename to _infrastructure/tests/typescript/0.9.7/tsc diff --git a/_infrastructure/tests/typescript/0.9.5-beta/tsc.js b/_infrastructure/tests/typescript/0.9.7/tsc.js similarity index 86% rename from _infrastructure/tests/typescript/0.9.5-beta/tsc.js rename to _infrastructure/tests/typescript/0.9.7/tsc.js index a31675a5ad..01bea509c4 100644 --- a/_infrastructure/tests/typescript/0.9.5-beta/tsc.js +++ b/_infrastructure/tests/typescript/0.9.7/tsc.js @@ -57,7 +57,7 @@ var TypeScript; Implementations_are_not_allowed_in_ambient_contexts: "Implementations are not allowed in ambient contexts.", declare_modifier_not_allowed_for_code_already_in_an_ambient_context: "'declare' modifier not allowed for code already in an ambient context.", Initializers_are_not_allowed_in_ambient_contexts: "Initializers are not allowed in ambient contexts.", - Parameter_property_declarations_can_only_be_used_in_constructors: "Parameter property declarations can only be used in constructors.", + Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration: "Parameter property declarations can only be used in a non-ambient constructor declaration.", Function_implementation_expected: "Function implementation expected.", Constructor_implementation_expected: "Constructor implementation expected.", Function_overload_name_must_be_0: "Function overload name must be '{0}'.", @@ -97,13 +97,15 @@ var TypeScript; declare_modifier_not_allowed_on_import_declaration: "'declare' modifier not allowed on import declaration.", Function_overload_must_be_static: "Function overload must be static.", Function_overload_must_not_be_static: "Function overload must not be static.", - Parameter_property_declarations_cannot_be_used_in_an_ambient_context: "Parameter property declarations cannot be used in an ambient context.", Parameter_property_declarations_cannot_be_used_in_a_constructor_overload: "Parameter property declarations cannot be used in a constructor overload.", Invalid_reference_directive_syntax: "Invalid 'reference' directive syntax.", Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: "Octal literals are not available when targeting ECMAScript 5 and higher.", Accessors_are_not_allowed_in_ambient_contexts: "Accessors are not allowed in ambient contexts.", _0_modifier_cannot_appear_on_a_constructor_declaration: "'{0}' modifier cannot appear on a constructor declaration.", _0_modifier_cannot_appear_on_a_parameter: "'{0}' modifier cannot appear on a parameter.", + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: "Only a single variable declaration is allowed in a 'for...in' statement.", + Type_parameters_cannot_appear_on_a_constructor_declaration: "Type parameters cannot appear on a constructor declaration.", + Type_annotation_cannot_appear_on_a_constructor_declaration: "Type annotation cannot appear on a constructor declaration.", Duplicate_identifier_0: "Duplicate identifier '{0}'.", The_name_0_does_not_exist_in_the_current_scope: "The name '{0}' does not exist in the current scope.", The_name_0_does_not_refer_to_a_value: "The name '{0}' does not refer to a value.", @@ -199,14 +201,14 @@ var TypeScript; Could_not_find_symbol_0: "Could not find symbol '{0}'.", get_and_set_accessor_must_have_the_same_type: "'get' and 'set' accessor must have the same type.", this_cannot_be_referenced_in_current_location: "'this' cannot be referenced in current location.", - Static_methods_cannot_reference_class_type_parameters: "Static methods cannot reference class type parameters.", + Static_members_cannot_reference_class_type_parameters: "Static members cannot reference class type parameters.", Class_0_is_recursively_referenced_as_a_base_type_of_itself: "Class '{0}' is recursively referenced as a base type of itself.", Interface_0_is_recursively_referenced_as_a_base_type_of_itself: "Interface '{0}' is recursively referenced as a base type of itself.", super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.", super_cannot_be_referenced_in_non_derived_classes: "'super' cannot be referenced in non-derived classes.", A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: "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: "Constructors for derived classes must contain a 'super' call.", - Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors: "Super calls are not permitted outside constructors or in local functions inside constructors.", + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: "Super calls are not permitted outside constructors or in nested functions inside constructors.", _0_1_is_inaccessible: "'{0}.{1}' is inaccessible.", this_cannot_be_referenced_within_module_bodies: "'this' cannot be referenced within module bodies.", Invalid_expression_types_not_known_to_support_the_addition_operator: "Invalid '+' expression - types not known to support the addition operator.", @@ -219,11 +221,11 @@ var TypeScript; The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.", The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "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_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "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_a_subtype_of_the_Function_interface_type: "The right-hand side of an 'instanceof' expression must be of type 'any' or a subtype of the 'Function' interface type.", + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.", Setters_cannot_return_a_value: "Setters cannot return a value.", Tried_to_query_type_of_uninitialized_module_0: "Tried to query type of uninitialized module '{0}'.", Tried_to_set_variable_type_to_uninitialized_module_type_0: "Tried to set variable type to uninitialized module type '{0}'.", - Function_0_declared_a_non_void_return_type_but_has_no_return_expression: "Function '{0}' declared a non-void return type, but has no return expression.", + Type_0_does_not_have_type_parameters: "Type '{0}' does not have type parameters.", Getters_must_return_a_value: "Getters must return a value.", Getter_and_setter_accessors_do_not_agree_in_visibility: "Getter and setter accessors do not agree in visibility.", Invalid_left_hand_side_of_assignment_expression: "Invalid left-hand side of assignment expression.", @@ -250,7 +252,7 @@ var TypeScript; Overload_signatures_must_all_be_exported_or_not_exported: "Overload signatures must all be exported or not exported.", Overload_signatures_must_all_be_ambient_or_non_ambient: "Overload signatures must all be ambient or non-ambient.", Overload_signatures_must_all_be_optional_or_required: "Overload signatures must all be optional or required.", - Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature: "Specialized overload signature is not subtype of any non-specialized signature.", + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: "Specialized overload signature is not assignable to any non-specialized signature.", this_cannot_be_referenced_in_constructor_arguments: "'this' cannot be referenced in constructor arguments.", Instance_member_cannot_be_accessed_off_a_class: "Instance member cannot be accessed off a class.", Untyped_function_calls_may_not_accept_type_arguments: "Untyped function calls may not accept type arguments.", @@ -261,14 +263,14 @@ var TypeScript; Export_assignments_may_only_be_used_at_the_top_level_of_external_modules: "Export assignments may only be used at the top-level of external modules.", Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.", Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: "Only public methods of the base class are accessible via the 'super' keyword.", - Numeric_indexer_type_0_must_be_a_subtype_of_string_indexer_type_1: "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}'.", - Numeric_indexer_type_0_must_be_a_subtype_of_string_indexer_type_1_NL_2: "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}':{NL}{2}", - All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type_0: "All numerically named properties must be subtypes of numeric indexer type '{0}'.", - All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type_0_NL_1: "All numerically named properties must be subtypes of numeric indexer type '{0}':{NL}{1}", - All_named_properties_must_be_subtypes_of_string_indexer_type_0: "All named properties must be subtypes of string indexer type '{0}'.", - All_named_properties_must_be_subtypes_of_string_indexer_type_0_NL_1: "All named properties must be subtypes of string indexer type '{0}':{NL}{1}", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0: "All numerically named properties must be assignable to numeric indexer type '{0}'.", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1: "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}", + All_named_properties_must_be_assignable_to_string_indexer_type_0: "All named properties must be assignable to string indexer type '{0}'.", + All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1: "All named properties must be assignable to string indexer type '{0}':{NL}{1}", Generic_type_references_must_include_all_type_arguments: "Generic type references must include all type arguments.", - Default_arguments_are_not_allowed_in_an_overload_parameter: "Default arguments are not allowed in an overload parameter.", + Default_arguments_are_only_allowed_in_implementation: "Default arguments are only allowed in implementation.", Overloads_cannot_differ_only_by_return_type: "Overloads cannot differ only by return type.", Function_expression_declared_a_non_void_return_type_but_has_no_return_expression: "Function expression declared a non-void return type, but has no return expression.", Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.", @@ -280,7 +282,7 @@ var TypeScript; Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.", Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.", Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.", - Type_reference_0_in_extends_clause_does_not_reference_constructor_function_for_1: "Type reference '{0}' in extends clause does not reference constructor function for '{1}'.", + Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1: "Type name '{0}' in extends clause does not reference constructor function for '{1}'.", Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1: "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.", Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2: "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.", Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}", @@ -323,6 +325,13 @@ var TypeScript; Type_of_conditional_0_must_be_identical_to_1_or_2: "Type of conditional '{0}' must be identical to '{1}' or '{2}'.", Type_of_conditional_0_must_be_identical_to_1_2_or_3: "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.", Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.", + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.", + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.", + Parameter_0_cannot_be_referenced_in_its_initializer: "Parameter '{0}' cannot be referenced in its initializer.", + Duplicate_string_index_signature: "Duplicate string index signature.", + Duplicate_number_index_signature: "Duplicate number index signature.", + All_declarations_of_an_interface_must_have_identical_type_parameters: "All declarations of an interface must have identical type parameters.", + Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.", Type_0_is_missing_property_1_from_type_2: "Type '{0}' is missing property '{1}' from type '{2}'.", Types_of_property_0_of_types_1_and_2_are_incompatible: "Types of property '{0}' of types '{1}' and '{2}' are incompatible.", Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3: "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}", @@ -347,20 +356,23 @@ var TypeScript; Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}", Type_reference_cannot_refer_to_container_0: "Type reference cannot refer to container '{0}'.", Type_reference_must_refer_to_type: "Type reference must refer to type.", - Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element: "Enums with multiple declarations must provide an initializer for the first enum element.", + In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element: "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.", _0_overload_s: " (+ {0} overload(s))", Variable_declaration_cannot_have_the_same_name_as_an_import_declaration: "Variable declaration cannot have the same name as an import declaration.", Signature_expected_0_type_arguments_got_1_instead: "Signature expected {0} type arguments, got {1} instead.", Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2: "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.", - Types_0_and_1_originating_in_inifinitely_expanding_type_reference_do_not_refer_to_same_named_type: "Types '{0}' and '{1}' originating in inifinitely expanding type reference do not refer to same named type.", - Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments: "Types '{0}' and '{1}' originating in inifinitely expanding type reference have incompatible type arguments.", - Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: "Types '{0}' and '{1}' originating in inifinitely expanding type reference have incompatible type arguments:{NL}{2}", - Types_of_property_0_of_types_1_and_2_are_not_identical: "Types of property '{0}' of types '{1}' and '{2}' are not identical.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type: "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}", + Named_properties_0_of_types_1_and_2_are_not_identical: "Named properties '{0}' of types '{1}' and '{2}' are not identical.", Types_of_string_indexer_of_types_0_and_1_are_not_identical: "Types of string indexer of types '{0}' and '{1}' are not identical.", Types_of_number_indexer_of_types_0_and_1_are_not_identical: "Types of number indexer of types '{0}' and '{1}' are not identical.", - Type_of_number_indexer_in_type_0_is_not_a_subtype_of_string_indexer_type_in_type_1_NL_2: "Type of number indexer in type '{0}' is not a subtype of string indexer type in type '{1}'.{NL}{2}", - Type_of_property_0_in_type_1_is_not_a_subtype_of_string_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not a subtype of string indexer type in type '{2}'.{NL}{3}", - Type_of_property_0_in_type_1_is_not_a_subtype_of_number_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not a subtype of number indexer type in type '{2}'.{NL}{3}", + Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2: "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}", + Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}", + Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}", + Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_static_property_2_as_private: "Types '{0}' and '{1}' define static property '{2}' as private.", Current_host_does_not_support_0_option: "Current host does not support '{0}' option.", ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2: "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'", Module_code_generation_0_not_supported: "Module code generation '{0}' not supported.", @@ -420,6 +432,7 @@ var TypeScript; DIRECTORY: "DIRECTORY", NUMBER: "NUMBER", Specify_the_codepage_to_use_when_opening_source_files: "Specify the codepage to use when opening source files.", + Additional_locations: "Additional locations:", This_version_of_the_Javascript_runtime_does_not_support_the_0_function: "This version of the Javascript runtime does not support the '{0}' function.", Unknown_rule: "Unknown rule.", Invalid_line_number_0: "Invalid line number ({0})", @@ -435,7 +448,9 @@ var TypeScript; Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.", Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.", Array_Literal_implicitly_has_an_any_type_from_widening: "Array Literal implicitly has an 'any' type from widening.", - _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type." + _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.", + Index_signature_of_object_type_implicitly_has_an_any_type: "Index signature of object type implicitly has an 'any' type.", + Object_literal_s_property_0_implicitly_has_an_any_type_from_widening: "Object literal's property '{0}' implicitly has an 'any' type from widening." }; })(TypeScript || (TypeScript = {})); var TypeScript; @@ -959,20 +974,64 @@ var TypeScript; })(); TypeScript.Debug = Debug; })(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; var TypeScript; (function (TypeScript) { TypeScript.LocalizedDiagnosticMessages = null; - var Diagnostic = (function () { - function Diagnostic(fileName, lineMap, start, length, diagnosticKey, arguments) { - if (typeof arguments === "undefined") { arguments = null; } - this._diagnosticKey = diagnosticKey; - this._arguments = (arguments && arguments.length > 0) ? arguments : null; + var Location = (function () { + function Location(fileName, lineMap, start, length) { this._fileName = fileName; this._lineMap = lineMap; this._start = start; this._length = length; } + Location.prototype.fileName = function () { + return this._fileName; + }; + + Location.prototype.lineMap = function () { + return this._lineMap; + }; + + Location.prototype.line = function () { + return this._lineMap ? this._lineMap.getLineNumberFromPosition(this.start()) : 0; + }; + + Location.prototype.character = function () { + return this._lineMap ? this._lineMap.getLineAndCharacterFromPosition(this.start()).character() : 0; + }; + + Location.prototype.start = function () { + return this._start; + }; + + Location.prototype.length = function () { + return this._length; + }; + + Location.equals = function (location1, location2) { + return location1._fileName === location2._fileName && location1._start === location2._start && location1._length === location2._length; + }; + return Location; + })(); + TypeScript.Location = Location; + + var Diagnostic = (function (_super) { + __extends(Diagnostic, _super); + function Diagnostic(fileName, lineMap, start, length, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + _super.call(this, fileName, lineMap, start, length); + this._diagnosticKey = diagnosticKey; + this._arguments = (_arguments && _arguments.length > 0) ? _arguments : null; + this._additionalLocations = (additionalLocations && additionalLocations.length > 0) ? additionalLocations : null; + } Diagnostic.prototype.toJSON = function (key) { var result = {}; result.start = this.start(); @@ -980,34 +1039,14 @@ var TypeScript; result.diagnosticCode = this._diagnosticKey; - var arguments = this.arguments(); - if (arguments && arguments.length > 0) { - result.arguments = arguments; + var _arguments = this.arguments(); + if (_arguments && _arguments.length > 0) { + result.arguments = _arguments; } return result; }; - Diagnostic.prototype.fileName = function () { - return this._fileName; - }; - - Diagnostic.prototype.line = function () { - return this._lineMap ? this._lineMap.getLineNumberFromPosition(this.start()) : 0; - }; - - Diagnostic.prototype.character = function () { - return this._lineMap ? this._lineMap.getLineAndCharacterFromPosition(this.start()).character() : 0; - }; - - Diagnostic.prototype.start = function () { - return this._start; - }; - - Diagnostic.prototype.length = function () { - return this._length; - }; - Diagnostic.prototype.diagnosticKey = function () { return this._diagnosticKey; }; @@ -1025,11 +1064,11 @@ var TypeScript; }; Diagnostic.prototype.additionalLocations = function () { - return []; + return this._additionalLocations || []; }; Diagnostic.equals = function (diagnostic1, diagnostic2) { - return diagnostic1._fileName === diagnostic2._fileName && diagnostic1._start === diagnostic2._start && diagnostic1._length === diagnostic2._length && diagnostic1._diagnosticKey === diagnostic2._diagnosticKey && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { + return Location.equals(diagnostic1, diagnostic2) && diagnostic1._diagnosticKey === diagnostic2._diagnosticKey && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { return v1 === v2; }); }; @@ -1038,7 +1077,7 @@ var TypeScript; return getDiagnosticInfoFromKey(this.diagnosticKey()); }; return Diagnostic; - })(); + })(Location); TypeScript.Diagnostic = Diagnostic; function newLine() { @@ -1051,7 +1090,7 @@ var TypeScript; var regex = /\{(\d+)\}/g; var match; - while ((match = regex.exec(diagnostic)) != null) { + while (match = regex.exec(diagnostic)) { var val = parseInt(match[1]); if (!isNaN(val) && val > largest) { largest = val; @@ -1216,7 +1255,7 @@ var TypeScript; numberOfCharsLeft -= 2; } - if (numberOfCharsLeft == 1) { + if (numberOfCharsLeft === 1) { h ^= key.charCodeAt(index); h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); } @@ -2252,7 +2291,7 @@ var TypeScript; "code": 1039, "category": 1 /* Error */ }, - "Parameter property declarations can only be used in constructors.": { + "Parameter property declarations can only be used in a non-ambient constructor declaration.": { "code": 1040, "category": 1 /* Error */ }, @@ -2412,10 +2451,6 @@ var TypeScript; "code": 1081, "category": 1 /* Error */ }, - "Parameter property declarations cannot be used in an ambient context.": { - "code": 1082, - "category": 1 /* Error */ - }, "Parameter property declarations cannot be used in a constructor overload.": { "code": 1083, "category": 1 /* Error */ @@ -2440,6 +2475,18 @@ var TypeScript; "code": 1090, "category": 1 /* Error */ }, + "Only a single variable declaration is allowed in a 'for...in' statement.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type parameters cannot appear on a constructor declaration.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type annotation cannot appear on a constructor declaration.": { + "code": 1092, + "category": 1 /* Error */ + }, "Duplicate identifier '{0}'.": { "code": 2000, "category": 1 /* Error */ @@ -2820,7 +2867,7 @@ var TypeScript; "code": 2097, "category": 1 /* Error */ }, - "Static methods cannot reference class type parameters.": { + "Static members cannot reference class type parameters.": { "code": 2099, "category": 1 /* Error */ }, @@ -2848,7 +2895,7 @@ var TypeScript; "code": 2105, "category": 1 /* Error */ }, - "Super calls are not permitted outside constructors or in local functions inside constructors.": { + "Super calls are not permitted outside constructors or in nested functions inside constructors.": { "code": 2106, "category": 1 /* Error */ }, @@ -2900,7 +2947,7 @@ var TypeScript; "code": 2120, "category": 1 /* Error */ }, - "The right-hand side of an 'instanceof' expression must be of type 'any' or a subtype of the 'Function' interface type.": { + "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.": { "code": 2121, "category": 1 /* Error */ }, @@ -2916,7 +2963,7 @@ var TypeScript; "code": 2124, "category": 1 /* Error */ }, - "Function '{0}' declared a non-void return type, but has no return expression.": { + "Type '{0}' does not have type parameters.": { "code": 2125, "category": 1 /* Error */ }, @@ -3024,7 +3071,7 @@ var TypeScript; "code": 2153, "category": 1 /* Error */ }, - "Specialized overload signature is not subtype of any non-specialized signature.": { + "Specialized overload signature is not assignable to any non-specialized signature.": { "code": 2154, "category": 1 /* Error */ }, @@ -3068,27 +3115,27 @@ var TypeScript; "code": 2166, "category": 1 /* Error */ }, - "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}'.": { + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.": { "code": 2167, "category": 1 /* Error */ }, - "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}':{NL}{2}": { + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}": { "code": 2168, "category": 1 /* Error */ }, - "All numerically named properties must be subtypes of numeric indexer type '{0}'.": { + "All numerically named properties must be assignable to numeric indexer type '{0}'.": { "code": 2169, "category": 1 /* Error */ }, - "All numerically named properties must be subtypes of numeric indexer type '{0}':{NL}{1}": { + "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}": { "code": 2170, "category": 1 /* Error */ }, - "All named properties must be subtypes of string indexer type '{0}'.": { + "All named properties must be assignable to string indexer type '{0}'.": { "code": 2171, "category": 1 /* Error */ }, - "All named properties must be subtypes of string indexer type '{0}':{NL}{1}": { + "All named properties must be assignable to string indexer type '{0}':{NL}{1}": { "code": 2172, "category": 1 /* Error */ }, @@ -3096,7 +3143,7 @@ var TypeScript; "code": 2173, "category": 1 /* Error */ }, - "Default arguments are not allowed in an overload parameter.": { + "Default arguments are only allowed in implementation.": { "code": 2174, "category": 1 /* Error */ }, @@ -3144,7 +3191,7 @@ var TypeScript; "code": 2185, "category": 1 /* Error */ }, - "Type reference '{0}' in extends clause does not reference constructor function for '{1}'.": { + "Type name '{0}' in extends clause does not reference constructor function for '{1}'.": { "code": 2186, "category": 1 /* Error */ }, @@ -3316,6 +3363,34 @@ var TypeScript; "code": 2228, "category": 1 /* Error */ }, + "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": { + "code": 2229, + "category": 1 /* Error */ + }, + "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.": { + "code": 2230, + "category": 1 /* Error */ + }, + "Parameter '{0}' cannot be referenced in its initializer.": { + "code": 2231, + "category": 1 /* Error */ + }, + "Duplicate string index signature.": { + "code": 2232, + "category": 1 /* Error */ + }, + "Duplicate number index signature.": { + "code": 2233, + "category": 1 /* Error */ + }, + "All declarations of an interface must have identical type parameters.": { + "code": 2234, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.": { + "code": 2235, + "category": 1 /* Error */ + }, "Type '{0}' is missing property '{1}' from type '{2}'.": { "code": 4000, "category": 3 /* NoPrefix */ @@ -3412,7 +3487,7 @@ var TypeScript; "code": 4023, "category": 1 /* Error */ }, - "Enums with multiple declarations must provide an initializer for the first enum element.": { + "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.": { "code": 4024, "category": 1 /* Error */ }, @@ -3432,19 +3507,19 @@ var TypeScript; "code": 4028, "category": 3 /* NoPrefix */ }, - "Types '{0}' and '{1}' originating in inifinitely expanding type reference do not refer to same named type.": { + "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.": { "code": 4029, "category": 3 /* NoPrefix */ }, - "Types '{0}' and '{1}' originating in inifinitely expanding type reference have incompatible type arguments.": { + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.": { "code": 4030, "category": 3 /* NoPrefix */ }, - "Types '{0}' and '{1}' originating in inifinitely expanding type reference have incompatible type arguments:{NL}{2}": { + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}": { "code": 4031, "category": 3 /* NoPrefix */ }, - "Types of property '{0}' of types '{1}' and '{2}' are not identical.": { + "Named properties '{0}' of types '{1}' and '{2}' are not identical.": { "code": 4032, "category": 3 /* NoPrefix */ }, @@ -3456,18 +3531,30 @@ var TypeScript; "code": 4034, "category": 3 /* NoPrefix */ }, - "Type of number indexer in type '{0}' is not a subtype of string indexer type in type '{1}'.{NL}{2}": { + "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}": { "code": 4035, "category": 3 /* NoPrefix */ }, - "Type of property '{0}' in type '{1}' is not a subtype of string indexer type in type '{2}'.{NL}{3}": { + "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}": { "code": 4036, "category": 3 /* NoPrefix */ }, - "Type of property '{0}' in type '{1}' is not a subtype of number indexer type in type '{2}'.{NL}{3}": { + "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}": { "code": 4037, "category": 3 /* NoPrefix */ }, + "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4038, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4039, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define static property '{2}' as private.": { + "code": 4040, + "category": 3 /* NoPrefix */ + }, "Current host does not support '{0}' option.": { "code": 5001, "category": 1 /* Error */ @@ -3704,6 +3791,10 @@ var TypeScript; "code": 6040, "category": 2 /* Message */ }, + "Additional locations:": { + "code": 6041, + "category": 2 /* Message */ + }, "This version of the Javascript runtime does not support the '{0}' function.": { "code": 7000, "category": 1 /* Error */ @@ -3767,6 +3858,14 @@ var TypeScript; "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.": { "code": 7016, "category": 1 /* Error */ + }, + "Index signature of object type implicitly has an 'any' type.": { + "code": 7017, + "category": 1 /* Error */ + }, + "Object literal's property '{0}' implicitly has an 'any' type from widening.": { + "code": 7018, + "category": 1 /* Error */ } }; })(TypeScript || (TypeScript = {})); @@ -3943,12 +4042,6 @@ var TypeScript; })(TypeScript.LineMap1 || (TypeScript.LineMap1 = {})); var LineMap1 = TypeScript.LineMap1; })(TypeScript || (TypeScript = {})); -var __extends = this.__extends || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; var TypeScript; (function (TypeScript) { (function (TextFactory) { @@ -6082,40 +6175,47 @@ var TypeScript; var end = this.slidingWindow.absoluteIndex(); var trailingTriviaInfo = this.scanTriviaInfo(diagnostics, true); + var fullEnd = this.slidingWindow.absoluteIndex(); var isVariableWidthKeyword = (kindAndFlags & -2147483648 /* IsVariableWidthKeyword */) !== 0; var kind = kindAndFlags & ~-2147483648 /* IsVariableWidthKeyword */; - var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, trailingTriviaInfo, isVariableWidthKeyword); + var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword); return diagnosticsLength !== diagnostics.length ? TypeScript.Syntax.realizeToken(token) : token; }; - Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, trailingTriviaInfo, isVariableWidthKeyword) { + Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword) { if (!isVariableWidthKeyword && kind >= 15 /* FirstFixedWidth */) { if (leadingTriviaInfo === 0) { if (trailingTriviaInfo === 0) { return new TypeScript.Syntax.FixedWidthTokenWithNoTrivia(kind); } else { - return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(this.text, fullStart, kind, trailingTriviaInfo); + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); } } else if (trailingTriviaInfo === 0) { - return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(this.text, fullStart, kind, leadingTriviaInfo); + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); } else { - return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(this.text, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo); + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); } } else { var width = end - start; + + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + if (leadingTriviaInfo === 0) { if (trailingTriviaInfo === 0) { - return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(this.text, fullStart, kind, width); + return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(fullText, kind); } else { - return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(this.text, fullStart, kind, width, trailingTriviaInfo); + return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); } } else if (trailingTriviaInfo === 0) { - return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(this.text, fullStart, kind, leadingTriviaInfo, width); + return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); } else { - return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(this.text, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo); + return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); } } }; @@ -8606,8 +8706,8 @@ var TypeScript; NormalModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, false); }; - NormalModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, parameterList, block, semicolonToken) { - return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, parameterList, block, semicolonToken, false); + NormalModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, false); }; NormalModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, false); @@ -8868,8 +8968,8 @@ var TypeScript; StrictModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, true); }; - StrictModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, parameterList, block, semicolonToken) { - return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, parameterList, block, semicolonToken, true); + StrictModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, true); }; StrictModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, true); @@ -9495,12 +9595,13 @@ var TypeScript; result.parsedInStrictMode = true; } + var thisAsIndexable = this; for (var i = 0, n = this.childCount(); i < n; i++) { var value = this.childAt(i); if (value) { for (var name in this) { - if (value === this[name]) { + if (value === thisAsIndexable[name]) { result[name] = value; break; } @@ -12799,12 +12900,13 @@ var TypeScript; var ArgumentListSyntax = (function (_super) { __extends(ArgumentListSyntax, _super); - function ArgumentListSyntax(typeArgumentList, openParenToken, arguments, closeParenToken, parsedInStrictMode) { + function ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, parsedInStrictMode) { _super.call(this, parsedInStrictMode); this.typeArgumentList = typeArgumentList; this.openParenToken = openParenToken; - this.arguments = arguments; this.closeParenToken = closeParenToken; + + this.arguments = _arguments; } ArgumentListSyntax.prototype.accept = function (visitor) { return visitor.visitArgumentList(this); @@ -14038,11 +14140,11 @@ var TypeScript; var ConstructorDeclarationSyntax = (function (_super) { __extends(ConstructorDeclarationSyntax, _super); - function ConstructorDeclarationSyntax(modifiers, constructorKeyword, parameterList, block, semicolonToken, parsedInStrictMode) { + function ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, parsedInStrictMode) { _super.call(this, parsedInStrictMode); this.modifiers = modifiers; this.constructorKeyword = constructorKeyword; - this.parameterList = parameterList; + this.callSignature = callSignature; this.block = block; this.semicolonToken = semicolonToken; } @@ -14065,7 +14167,7 @@ var TypeScript; case 1: return this.constructorKeyword; case 2: - return this.parameterList; + return this.callSignature; case 3: return this.block; case 4: @@ -14079,20 +14181,20 @@ var TypeScript; return true; }; - ConstructorDeclarationSyntax.prototype.update = function (modifiers, constructorKeyword, parameterList, block, semicolonToken) { - if (this.modifiers === modifiers && this.constructorKeyword === constructorKeyword && this.parameterList === parameterList && this.block === block && this.semicolonToken === semicolonToken) { + ConstructorDeclarationSyntax.prototype.update = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.constructorKeyword === constructorKeyword && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { return this; } - return new ConstructorDeclarationSyntax(modifiers, constructorKeyword, parameterList, block, semicolonToken, this.parsedInStrictMode()); + return new ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, this.parsedInStrictMode()); }; - ConstructorDeclarationSyntax.create = function (constructorKeyword, parameterList) { - return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, constructorKeyword, parameterList, null, null, false); + ConstructorDeclarationSyntax.create = function (constructorKeyword, callSignature) { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, constructorKeyword, callSignature, null, null, false); }; ConstructorDeclarationSyntax.create1 = function () { - return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(62 /* ConstructorKeyword */), ParameterListSyntax.create1(), null, null, false); + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(62 /* ConstructorKeyword */), CallSignatureSyntax.create1(), null, null, false); }; ConstructorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { @@ -14104,7 +14206,7 @@ var TypeScript; }; ConstructorDeclarationSyntax.prototype.withModifiers = function (modifiers) { - return this.update(modifiers, this.constructorKeyword, this.parameterList, this.block, this.semicolonToken); + return this.update(modifiers, this.constructorKeyword, this.callSignature, this.block, this.semicolonToken); }; ConstructorDeclarationSyntax.prototype.withModifier = function (modifier) { @@ -14112,19 +14214,19 @@ var TypeScript; }; ConstructorDeclarationSyntax.prototype.withConstructorKeyword = function (constructorKeyword) { - return this.update(this.modifiers, constructorKeyword, this.parameterList, this.block, this.semicolonToken); + return this.update(this.modifiers, constructorKeyword, this.callSignature, this.block, this.semicolonToken); }; - ConstructorDeclarationSyntax.prototype.withParameterList = function (parameterList) { - return this.update(this.modifiers, this.constructorKeyword, parameterList, this.block, this.semicolonToken); + ConstructorDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.constructorKeyword, callSignature, this.block, this.semicolonToken); }; ConstructorDeclarationSyntax.prototype.withBlock = function (block) { - return this.update(this.modifiers, this.constructorKeyword, this.parameterList, block, this.semicolonToken); + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, block, this.semicolonToken); }; ConstructorDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { - return this.update(this.modifiers, this.constructorKeyword, this.parameterList, this.block, semicolonToken); + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, this.block, semicolonToken); }; ConstructorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { @@ -17614,7 +17716,7 @@ var TypeScript; }; SyntaxRewriter.prototype.visitConstructorDeclaration = function (node) { - return node.update(this.visitList(node.modifiers), this.visitToken(node.constructorKeyword), this.visitNode(node.parameterList), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + return node.update(this.visitList(node.modifiers), this.visitToken(node.constructorKeyword), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); }; SyntaxRewriter.prototype.visitMemberFunctionDeclaration = function (node) { @@ -18036,14 +18138,12 @@ var TypeScript; (function (TypeScript) { (function (Syntax) { var VariableWidthTokenWithNoTrivia = (function () { - function VariableWidthTokenWithNoTrivia(sourceText, fullStart, kind, textOrWidth) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function VariableWidthTokenWithNoTrivia(fullText, kind) { + this._fullText = fullText; this.tokenKind = kind; - this._textOrWidth = textOrWidth; } VariableWidthTokenWithNoTrivia.prototype.clone = function () { - return new VariableWidthTokenWithNoTrivia(this._sourceText, this._fullStart, this.tokenKind, this._textOrWidth); + return new VariableWidthTokenWithNoTrivia(this._fullText, this.tokenKind); }; VariableWidthTokenWithNoTrivia.prototype.isNode = function () { @@ -18071,29 +18171,17 @@ var TypeScript; }; VariableWidthTokenWithNoTrivia.prototype.fullWidth = function () { - return this.width(); + return this.fullText().length; }; - VariableWidthTokenWithNoTrivia.prototype.start = function () { - return this._fullStart; - }; - VariableWidthTokenWithNoTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - VariableWidthTokenWithNoTrivia.prototype.width = function () { - return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); }; VariableWidthTokenWithNoTrivia.prototype.text = function () { - if (typeof this._textOrWidth === 'number') { - this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); - } - - return this._textOrWidth; + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); }; - VariableWidthTokenWithNoTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; VariableWidthTokenWithNoTrivia.prototype.value = function () { @@ -18214,15 +18302,13 @@ var TypeScript; Syntax.VariableWidthTokenWithNoTrivia = VariableWidthTokenWithNoTrivia; var VariableWidthTokenWithLeadingTrivia = (function () { - function VariableWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, textOrWidth) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._leadingTriviaInfo = leadingTriviaInfo; - this._textOrWidth = textOrWidth; } VariableWidthTokenWithLeadingTrivia.prototype.clone = function () { - return new VariableWidthTokenWithLeadingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._textOrWidth); + return new VariableWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); }; VariableWidthTokenWithLeadingTrivia.prototype.isNode = function () { @@ -18250,29 +18336,17 @@ var TypeScript; }; VariableWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { - return getTriviaWidth(this._leadingTriviaInfo) + this.width(); + return this.fullText().length; }; - VariableWidthTokenWithLeadingTrivia.prototype.start = function () { - return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); - }; - VariableWidthTokenWithLeadingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - VariableWidthTokenWithLeadingTrivia.prototype.width = function () { - return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); }; VariableWidthTokenWithLeadingTrivia.prototype.text = function () { - if (typeof this._textOrWidth === 'number') { - this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); - } - - return this._textOrWidth; + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); }; - VariableWidthTokenWithLeadingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; VariableWidthTokenWithLeadingTrivia.prototype.value = function () { @@ -18307,7 +18381,7 @@ var TypeScript; return getTriviaWidth(this._leadingTriviaInfo); }; VariableWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); }; VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { @@ -18393,15 +18467,13 @@ var TypeScript; Syntax.VariableWidthTokenWithLeadingTrivia = VariableWidthTokenWithLeadingTrivia; var VariableWidthTokenWithTrailingTrivia = (function () { - function VariableWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, textOrWidth, trailingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; - this._textOrWidth = textOrWidth; this._trailingTriviaInfo = trailingTriviaInfo; } VariableWidthTokenWithTrailingTrivia.prototype.clone = function () { - return new VariableWidthTokenWithTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._textOrWidth, this._trailingTriviaInfo); + return new VariableWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); }; VariableWidthTokenWithTrailingTrivia.prototype.isNode = function () { @@ -18429,29 +18501,17 @@ var TypeScript; }; VariableWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { - return this.width() + getTriviaWidth(this._trailingTriviaInfo); + return this.fullText().length; }; - VariableWidthTokenWithTrailingTrivia.prototype.start = function () { - return this._fullStart; - }; - VariableWidthTokenWithTrailingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - VariableWidthTokenWithTrailingTrivia.prototype.width = function () { - return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); }; VariableWidthTokenWithTrailingTrivia.prototype.text = function () { - if (typeof this._textOrWidth === 'number') { - this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); - } - - return this._textOrWidth; + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); }; - VariableWidthTokenWithTrailingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; VariableWidthTokenWithTrailingTrivia.prototype.value = function () { @@ -18505,7 +18565,7 @@ var TypeScript; return getTriviaWidth(this._trailingTriviaInfo); }; VariableWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); }; VariableWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { @@ -18572,16 +18632,14 @@ var TypeScript; Syntax.VariableWidthTokenWithTrailingTrivia = VariableWidthTokenWithTrailingTrivia; var VariableWidthTokenWithLeadingAndTrailingTrivia = (function () { - function VariableWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, textOrWidth, trailingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._leadingTriviaInfo = leadingTriviaInfo; - this._textOrWidth = textOrWidth; this._trailingTriviaInfo = trailingTriviaInfo; } VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { - return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._textOrWidth, this._trailingTriviaInfo); + return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { @@ -18609,29 +18667,17 @@ var TypeScript; }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { - return getTriviaWidth(this._leadingTriviaInfo) + this.width() + getTriviaWidth(this._trailingTriviaInfo); + return this.fullText().length; }; - VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.start = function () { - return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); - }; - VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { - return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { - if (typeof this._textOrWidth === 'number') { - this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); - } - - return this._textOrWidth; + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); }; - VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { @@ -18666,7 +18712,7 @@ var TypeScript; return getTriviaWidth(this._leadingTriviaInfo); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { @@ -18685,7 +18731,7 @@ var TypeScript; return getTriviaWidth(this._trailingTriviaInfo); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { @@ -18784,11 +18830,12 @@ var TypeScript; }; FixedWidthTokenWithNoTrivia.prototype.fullWidth = function () { - return this.width(); + return this.fullText().length; }; FixedWidthTokenWithNoTrivia.prototype.width = function () { return this.text().length; }; + FixedWidthTokenWithNoTrivia.prototype.text = function () { return TypeScript.SyntaxFacts.getText(this.tokenKind); }; @@ -18904,14 +18951,13 @@ var TypeScript; Syntax.FixedWidthTokenWithNoTrivia = FixedWidthTokenWithNoTrivia; var FixedWidthTokenWithLeadingTrivia = (function () { - function FixedWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._leadingTriviaInfo = leadingTriviaInfo; } FixedWidthTokenWithLeadingTrivia.prototype.clone = function () { - return new FixedWidthTokenWithLeadingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo); + return new FixedWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); }; FixedWidthTokenWithLeadingTrivia.prototype.isNode = function () { @@ -18939,23 +18985,17 @@ var TypeScript; }; FixedWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { - return getTriviaWidth(this._leadingTriviaInfo) + this.width(); + return this.fullText().length; }; - FixedWidthTokenWithLeadingTrivia.prototype.start = function () { - return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); - }; - FixedWidthTokenWithLeadingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - FixedWidthTokenWithLeadingTrivia.prototype.width = function () { return this.text().length; }; + FixedWidthTokenWithLeadingTrivia.prototype.text = function () { return TypeScript.SyntaxFacts.getText(this.tokenKind); }; FixedWidthTokenWithLeadingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; FixedWidthTokenWithLeadingTrivia.prototype.value = function () { @@ -18980,7 +19020,7 @@ var TypeScript; return getTriviaWidth(this._leadingTriviaInfo); }; FixedWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); }; FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { @@ -19066,14 +19106,13 @@ var TypeScript; Syntax.FixedWidthTokenWithLeadingTrivia = FixedWidthTokenWithLeadingTrivia; var FixedWidthTokenWithTrailingTrivia = (function () { - function FixedWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, trailingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._trailingTriviaInfo = trailingTriviaInfo; } FixedWidthTokenWithTrailingTrivia.prototype.clone = function () { - return new FixedWidthTokenWithTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._trailingTriviaInfo); + return new FixedWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); }; FixedWidthTokenWithTrailingTrivia.prototype.isNode = function () { @@ -19101,23 +19140,17 @@ var TypeScript; }; FixedWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { - return this.width() + getTriviaWidth(this._trailingTriviaInfo); + return this.fullText().length; }; - FixedWidthTokenWithTrailingTrivia.prototype.start = function () { - return this._fullStart; - }; - FixedWidthTokenWithTrailingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - FixedWidthTokenWithTrailingTrivia.prototype.width = function () { return this.text().length; }; + FixedWidthTokenWithTrailingTrivia.prototype.text = function () { return TypeScript.SyntaxFacts.getText(this.tokenKind); }; FixedWidthTokenWithTrailingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; FixedWidthTokenWithTrailingTrivia.prototype.value = function () { @@ -19161,7 +19194,7 @@ var TypeScript; return getTriviaWidth(this._trailingTriviaInfo); }; FixedWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); }; FixedWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { @@ -19228,15 +19261,14 @@ var TypeScript; Syntax.FixedWidthTokenWithTrailingTrivia = FixedWidthTokenWithTrailingTrivia; var FixedWidthTokenWithLeadingAndTrailingTrivia = (function () { - function FixedWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._leadingTriviaInfo = leadingTriviaInfo; this._trailingTriviaInfo = trailingTriviaInfo; } FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { - return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { @@ -19264,23 +19296,17 @@ var TypeScript; }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { - return getTriviaWidth(this._leadingTriviaInfo) + this.width() + getTriviaWidth(this._trailingTriviaInfo); + return this.fullText().length; }; - FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.start = function () { - return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); - }; - FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { return this.text().length; }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { return TypeScript.SyntaxFacts.getText(this.tokenKind); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { @@ -19305,7 +19331,7 @@ var TypeScript; return getTriviaWidth(this._leadingTriviaInfo); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { @@ -19324,7 +19350,7 @@ var TypeScript; return getTriviaWidth(this._trailingTriviaInfo); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { @@ -19396,36 +19422,6 @@ var TypeScript; token.trailingTrivia().collectTextElements(elements); } - function fixedWidthToken(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo) { - if (leadingTriviaInfo === 0) { - if (trailingTriviaInfo === 0) { - return new FixedWidthTokenWithNoTrivia(kind); - } else { - return new FixedWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, trailingTriviaInfo); - } - } else if (trailingTriviaInfo === 0) { - return new FixedWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo); - } else { - return new FixedWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo); - } - } - Syntax.fixedWidthToken = fixedWidthToken; - - function variableWidthToken(sourceText, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo) { - if (leadingTriviaInfo === 0) { - if (trailingTriviaInfo === 0) { - return new VariableWidthTokenWithNoTrivia(sourceText, fullStart, kind, width); - } else { - return new VariableWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, width, trailingTriviaInfo); - } - } else if (trailingTriviaInfo === 0) { - return new VariableWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, width); - } else { - return new VariableWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo); - } - } - Syntax.variableWidthToken = variableWidthToken; - function getTriviaWidth(value) { return value >>> 2 /* TriviaFullWidthShift */; } @@ -19615,7 +19611,7 @@ var TypeScript; case 13 /* carriageReturn */: var nextIndex = i + 1; - if (nextIndex < text.length && text.charCodeAt(nextIndex) == 10 /* lineFeed */) { + if (nextIndex < text.length && text.charCodeAt(nextIndex) === 10 /* lineFeed */) { i++; } continue; @@ -21363,7 +21359,7 @@ var TypeScript; SyntaxWalker.prototype.visitConstructorDeclaration = function (node) { this.visitList(node.modifiers); this.visitToken(node.constructorKeyword); - this.visitNode(node.parameterList); + this.visitNode(node.callSignature); this.visitOptionalNode(node.block); this.visitOptionalToken(node.semicolonToken); }; @@ -21831,7 +21827,7 @@ var TypeScript; ListParsingState[ListParsingState["TypeParameterList_TypeParameters"] = 1 << 19] = "TypeParameterList_TypeParameters"; ListParsingState[ListParsingState["FirstListParsingState"] = ListParsingState.SourceUnit_ModuleElements] = "FirstListParsingState"; - ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeArgumentList_Types] = "LastListParsingState"; + ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeParameterList_TypeParameters] = "LastListParsingState"; })(ListParsingState || (ListParsingState = {})); var SyntaxCursor = (function () { @@ -23200,13 +23196,13 @@ var TypeScript; ParserImpl.prototype.isConstructorDeclaration = function () { var index = this.modifierCount(); - return this.peekToken(index).tokenKind === 62 /* ConstructorKeyword */ && this.peekToken(index + 1).tokenKind === 72 /* OpenParenToken */; + return this.peekToken(index).tokenKind === 62 /* ConstructorKeyword */; }; ParserImpl.prototype.parseConstructorDeclaration = function () { var modifiers = this.parseModifiers(); var constructorKeyword = this.eatKeyword(62 /* ConstructorKeyword */); - var parameterList = this.parseParameterList(); + var callSignature = this.parseCallSignature(false); var semicolonToken = null; var block = null; @@ -23217,7 +23213,7 @@ var TypeScript; semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); } - return this.factory.constructorDeclaration(modifiers, constructorKeyword, parameterList, block, semicolonToken); + return this.factory.constructorDeclaration(modifiers, constructorKeyword, callSignature, block, semicolonToken); }; ParserImpl.prototype.isMemberFunctionDeclaration = function (inErrorRecovery) { @@ -25091,10 +25087,6 @@ var TypeScript; var currentToken = this.currentToken(); var currentTokenKind = currentToken.tokenKind; - if (currentTokenKind === 39 /* TypeOfKeyword */) { - return this.parseTypeQuery(); - } - var type = this.parseNonArrayType(currentToken); while (this.currentToken().tokenKind === 74 /* OpenBracketToken */) { @@ -25137,6 +25129,9 @@ var TypeScript; case 31 /* NewKeyword */: return this.parseConstructorType(); + + case 39 /* TypeOfKeyword */: + return this.parseTypeQuery(); } return this.parseNameOrGenericType(); @@ -25262,7 +25257,7 @@ var TypeScript; ParserImpl.prototype.abortParsingListOrMoveToNextToken = function (currentListType, items, skippedTokens) { this.reportUnexpectedTokenDiagnostic(currentListType); - for (var state = 262144 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { + for (var state = 524288 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { if ((this.listParsingState & state) !== 0) { if (this.isExpectedListTerminator(state) || this.isExpectedListItem(state, true)) { return true; @@ -26098,14 +26093,11 @@ var TypeScript; return true; } - if (this.inAmbientDeclaration) { - this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_cannot_be_used_in_an_ambient_context); - return true; - } else if (this.currentConstructor && !this.currentConstructor.block && this.currentConstructor.parameterList === parameterList) { + if (!this.inAmbientDeclaration && this.currentConstructor && !this.currentConstructor.block && this.currentConstructor.callSignature.parameterList === parameterList) { this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_cannot_be_used_in_a_constructor_overload); return true; - } else if (this.currentConstructor === null || this.currentConstructor.parameterList !== parameterList) { - this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_can_only_be_used_in_constructors); + } else if (this.inAmbientDeclaration || this.currentConstructor === null || this.currentConstructor.callSignature.parameterList !== parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration); return true; } } @@ -26337,9 +26329,22 @@ var TypeScript; inFunctionOverloadChain = functionDeclaration.block === null; functionOverloadChainName = functionDeclaration.identifier.valueText(); - if (lastElement && inFunctionOverloadChain) { - this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); - return true; + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = moduleElements.childAt(i + 1); + if (nextElement.kind() === 129 /* FunctionDeclaration */) { + var nextFunction = nextElement; + + if (nextFunction.identifier.valueText() !== functionOverloadChainName && nextFunction.block === null) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } } } else { inFunctionOverloadChain = false; @@ -26382,9 +26387,10 @@ var TypeScript; this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); return true; } + isStaticOverload = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); if (isStaticOverload !== isInStaticOverloadChain) { - propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); var diagnostic = isInStaticOverloadChain ? TypeScript.DiagnosticCode.Function_overload_must_be_static : TypeScript.DiagnosticCode.Function_overload_must_not_be_static; this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, diagnostic, null); return true; @@ -26403,9 +26409,22 @@ var TypeScript; functionOverloadChainName = memberFunctionDeclaration.propertyName.valueText(); isInStaticOverloadChain = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); - if (lastElement && inFunctionOverloadChain) { - this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); - return true; + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = node.classElements.childAt(i + 1); + if (nextElement.kind() === 135 /* MemberFunctionDeclaration */) { + var nextMemberFunction = nextElement; + + if (nextMemberFunction.propertyName.valueText() !== functionOverloadChainName && nextMemberFunction.block === null) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } } } else if (classElement.kind() === 137 /* ConstructorDeclaration */) { var constructorDeclaration = classElement; @@ -26696,23 +26715,21 @@ var TypeScript; GrammarCheckerWalker.prototype.checkEnumElements = function (node) { var enumElementFullStart = this.childFullStart(node, node.enumElements); - var seenComputedValue = false; + var previousValueWasComputed = false; for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { var child = node.enumElements.childAt(i); if (i % 2 === 0) { var enumElement = child; - if (!enumElement.equalsValueClause && seenComputedValue) { + if (!enumElement.equalsValueClause && previousValueWasComputed) { this.pushDiagnostic1(enumElementFullStart, enumElement, TypeScript.DiagnosticCode.Enum_member_must_have_initializer, null); return true; } if (enumElement.equalsValueClause) { var value = enumElement.equalsValueClause.value; - if (!TypeScript.Syntax.isIntegerLiteral(value)) { - seenComputedValue = true; - } + previousValueWasComputed = !TypeScript.Syntax.isIntegerLiteral(value); } } @@ -26999,7 +27016,7 @@ var TypeScript; }; GrammarCheckerWalker.prototype.visitForInStatement = function (node) { - if (this.checkForStatementInAmbientContxt(node)) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForInStatementVariableDeclaration(node)) { this.skip(node); return; } @@ -27007,6 +27024,17 @@ var TypeScript; _super.prototype.visitForInStatement.call(this, node); }; + GrammarCheckerWalker.prototype.checkForInStatementVariableDeclaration = function (node) { + if (node.variableDeclaration && node.variableDeclaration.variableDeclarators.nonSeparatorCount() > 1) { + var variableDeclarationFullStart = this.childFullStart(node, node.variableDeclaration); + + this.pushDiagnostic1(variableDeclarationFullStart, node.variableDeclaration, TypeScript.DiagnosticCode.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + return true; + } + + return false; + }; + GrammarCheckerWalker.prototype.visitForStatement = function (node) { if (this.checkForStatementInAmbientContxt(node)) { this.skip(node); @@ -27183,7 +27211,7 @@ var TypeScript; }; GrammarCheckerWalker.prototype.visitConstructorDeclaration = function (node) { - if (this.checkClassElementModifiers(node.modifiers) || this.checkConstructorModifiers(node.modifiers)) { + if (this.checkClassElementModifiers(node.modifiers) || this.checkConstructorModifiers(node.modifiers) || this.checkConstructorTypeParameterList(node) || this.checkConstructorTypeAnnotation(node)) { this.skip(node); return; } @@ -27210,6 +27238,32 @@ var TypeScript; return false; }; + GrammarCheckerWalker.prototype.checkConstructorTypeParameterList = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeParameterList) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeParameterListFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(callSignatureFullStart, node.callSignature.typeParameterList, TypeScript.DiagnosticCode.Type_parameters_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeAnnotation = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeAnnotation) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeAnnotationFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(typeAnnotationFullStart, node.callSignature.typeAnnotation, TypeScript.DiagnosticCode.Type_annotation_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + GrammarCheckerWalker.prototype.visitSourceUnit = function (node) { if (this.checkFunctionOverloads(node, node.moduleElements) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { this.skip(node); @@ -27343,7 +27397,9 @@ var TypeScript; var start = (new Date()).getTime(); var result = func(); var end = (new Date()).getTime(); - logger.log(funcDescription + " completed in " + (end - start) + " msec"); + if (logger.information()) { + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + } return result; } TypeScript.timeFunction = timeFunction; @@ -27368,8 +27424,8 @@ var TypeScript; this._lineMap = null; this._declASTMap = []; this._astDeclMap = []; - this._isExternalModule = undefined; this._amdDependencies = undefined; + this._externalModuleIndicatorSpan = undefined; } Document.prototype.invalidate = function () { this._declASTMap.length = 0; @@ -27394,39 +27450,22 @@ var TypeScript; this._lineMap = syntaxTree.lineMap(); var sourceUnit = syntaxTree.sourceUnit(); - var leadingComments = this.getLeadingComments(sourceUnit); + var leadingTrivia = sourceUnit.leadingTrivia(); - this._isExternalModule = this.hasImplicitImport(leadingComments) || this.hasTopLevelImportOrExport(sourceUnit); + this._externalModuleIndicatorSpan = this.getImplicitImportSpan(leadingTrivia) || this.getTopLevelImportOrExportSpan(sourceUnit); var amdDependencies = []; - for (var i = 0, n = leadingComments.length; i < n; i++) { - var trivia = leadingComments[i]; - var amdDependency = this.getAmdDependency(trivia.fullText()); - if (amdDependency) { - amdDependencies.push(amdDependency); - } - } - - this._amdDependencies = amdDependencies; - }; - - Document.prototype.getLeadingComments = function (node) { - var firstToken = node.firstToken(); - var result = []; - - if (firstToken.hasLeadingComment()) { - var leadingTrivia = firstToken.leadingTrivia(); - - for (var i = 0, n = leadingTrivia.count(); i < n; i++) { - var trivia = leadingTrivia.syntaxTriviaAt(i); - - if (trivia.isComment()) { - result.push(trivia); + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.isComment()) { + var amdDependency = this.getAmdDependency(trivia.fullText()); + if (amdDependency) { + amdDependencies.push(amdDependency); } } } - return result; + this._amdDependencies = amdDependencies; }; Document.prototype.getAmdDependency = function (comment) { @@ -27435,49 +27474,60 @@ var TypeScript; return match ? match[2] : null; }; - Document.prototype.hasImplicitImport = function (sourceUnitLeadingComments) { - for (var i = 0, n = sourceUnitLeadingComments.length; i < n; i++) { - var trivia = sourceUnitLeadingComments[i]; + Document.prototype.getImplicitImportSpan = function (sourceUnitLeadingTrivia) { + var position = 0; - if (this.getImplicitImport(trivia.fullText())) { - return true; + for (var i = 0, n = sourceUnitLeadingTrivia.count(); i < n; i++) { + var trivia = sourceUnitLeadingTrivia.syntaxTriviaAt(i); + + if (trivia.isComment()) { + var span = this.getImplicitImportSpanWorker(trivia, position); + if (span) { + return span; + } } + + position += trivia.fullWidth(); } - return false; + return null; }; - Document.prototype.getImplicitImport = function (comment) { + Document.prototype.getImplicitImportSpanWorker = function (trivia, position) { var implicitImportRegEx = /^(\/\/\/\s*/gim; - var match = implicitImportRegEx.exec(comment); + var match = implicitImportRegEx.exec(trivia.fullText()); if (match) { - return true; + return new TypeScript.TextSpan(position, trivia.fullWidth()); } - return false; + return null; }; - Document.prototype.hasTopLevelImportOrExport = function (node) { + Document.prototype.getTopLevelImportOrExportSpan = function (node) { var firstToken; + var position = 0; for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { var moduleElement = node.moduleElements.childAt(i); firstToken = moduleElement.firstToken(); if (firstToken !== null && firstToken.tokenKind === 47 /* ExportKeyword */) { - return true; + return new TypeScript.TextSpan(position + firstToken.leadingTriviaWidth(), firstToken.width()); } if (moduleElement.kind() === 133 /* ImportDeclaration */) { var importDecl = moduleElement; if (importDecl.moduleReference.kind() === 245 /* ExternalModuleReference */) { - return true; + return new TypeScript.TextSpan(position + importDecl.leadingTriviaWidth(), importDecl.width()); } } + + position += moduleElement.fullWidth(); } - return false; + return null; + ; }; Document.prototype.sourceUnit = function () { @@ -27514,12 +27564,16 @@ var TypeScript; }; Document.prototype.isExternalModule = function () { - if (this._isExternalModule === undefined) { + return this.externalModuleIndicatorSpan() !== null; + }; + + Document.prototype.externalModuleIndicatorSpan = function () { + if (this._externalModuleIndicatorSpan === undefined) { this.syntaxTree(); - TypeScript.Debug.assert(this._isExternalModule !== undefined); + TypeScript.Debug.assert(this._externalModuleIndicatorSpan !== undefined); } - return this._isExternalModule; + return this._externalModuleIndicatorSpan; }; Document.prototype.amdDependencies = function () { @@ -27553,7 +27607,7 @@ var TypeScript; if (!this._bloomFilter) { var identifiers = TypeScript.createIntrinsicsObject(); var pre = function (cur) { - if (TypeScript.isValidAstNode(cur)) { + if (TypeScript.ASTHelpers.isValidAstNode(cur)) { if (cur.kind() === 11 /* IdentifierName */) { var nodeText = cur.valueText(); @@ -27859,246 +27913,261 @@ var TypeScript; })(StringHashTable); TypeScript.IdentiferNameHashTable = IdentiferNameHashTable; })(TypeScript || (TypeScript = {})); + var TypeScript; (function (TypeScript) { - function scriptIsElided(sourceUnit) { - return TypeScript.isDTSFile(sourceUnit.fileName()) || moduleMembersAreElided(sourceUnit.moduleElements); - } - TypeScript.scriptIsElided = scriptIsElided; + (function (ASTHelpers) { + function scriptIsElided(sourceUnit) { + return TypeScript.isDTSFile(sourceUnit.fileName()) || moduleMembersAreElided(sourceUnit.moduleElements); + } + ASTHelpers.scriptIsElided = scriptIsElided; - function moduleIsElided(declaration) { - return TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) || moduleMembersAreElided(declaration.moduleElements); - } - TypeScript.moduleIsElided = moduleIsElided; + function moduleIsElided(declaration) { + return TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) || moduleMembersAreElided(declaration.moduleElements); + } + ASTHelpers.moduleIsElided = moduleIsElided; - function moduleMembersAreElided(members) { - for (var i = 0, n = members.childCount(); i < n; i++) { - var member = members.childAt(i); + function moduleMembersAreElided(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); - if (member.kind() === 130 /* ModuleDeclaration */) { - if (!moduleIsElided(member)) { + if (member.kind() === 130 /* ModuleDeclaration */) { + if (!moduleIsElided(member)) { + return false; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */) { return false; } - } else if (member.kind() !== 128 /* InterfaceDeclaration */) { - return false; } - } - return true; - } - - function enumIsElided(declaration) { - if (TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { return true; } - return false; - } - TypeScript.enumIsElided = enumIsElided; - - function importDeclarationIsElided(importDeclAST, semanticInfoChain, compilationSettings) { - if (typeof compilationSettings === "undefined") { compilationSettings = null; } - var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; - var importDecl = semanticInfoChain.getDeclForAST(importDeclAST); - var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); - var isAmdCodeGen = compilationSettings && compilationSettings.moduleGenTarget() == 2 /* Asynchronous */; - - if (!isExternalModuleReference || isExported || !isAmdCodeGen) { - var importSymbol = importDecl.getSymbol(); - if (importDeclAST.moduleReference.kind() !== 245 /* ExternalModuleReference */) { - if (importSymbol.getExportAssignedValueSymbol()) { - return true; - } - var containerSymbol = importSymbol.getExportAssignedContainerSymbol(); - if (containerSymbol && containerSymbol.getInstanceSymbol()) { - return true; - } + function enumIsElided(declaration) { + if (TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + return true; } - return importSymbol.isUsedAsValue(); + return false; } + ASTHelpers.enumIsElided = enumIsElided; - return false; - } - TypeScript.importDeclarationIsElided = importDeclarationIsElided; + function isValidAstNode(ast) { + if (!ast) + return false; - function isValidAstNode(ast) { - if (!ast) - return false; + if (ast.start() === -1 || ast.end() === -1) + return false; - if (ast.start() === -1 || ast.end() === -1) - return false; + return true; + } + ASTHelpers.isValidAstNode = isValidAstNode; - return true; - } - TypeScript.isValidAstNode = isValidAstNode; + function getAstAtPosition(script, pos, useTrailingTriviaAsLimChar, forceInclusive) { + if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } + if (typeof forceInclusive === "undefined") { forceInclusive = false; } + var top = null; - function getAstAtPosition(script, pos, useTrailingTriviaAsLimChar, forceInclusive) { - if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } - if (typeof forceInclusive === "undefined") { forceInclusive = false; } - var top = null; + var pre = function (cur, walker) { + if (isValidAstNode(cur)) { + var isInvalid1 = cur.kind() === 149 /* ExpressionStatement */ && cur.width() === 0; - var pre = function (cur, walker) { - if (isValidAstNode(cur)) { - var isInvalid1 = cur.kind() === 149 /* ExpressionStatement */ && cur.width() === 0; + if (isInvalid1) { + walker.options.goChildren = false; + } else { + var inclusive = forceInclusive || cur.kind() === 11 /* IdentifierName */ || cur.kind() === 212 /* MemberAccessExpression */ || cur.kind() === 121 /* QualifiedName */ || cur.kind() === 224 /* VariableDeclaration */ || cur.kind() === 225 /* VariableDeclarator */ || cur.kind() === 213 /* InvocationExpression */ || pos === script.end() + script.trailingTriviaWidth(); - if (isInvalid1) { - walker.options.goChildren = false; - } else { - var inclusive = forceInclusive || cur.kind() === 11 /* IdentifierName */ || cur.kind() === 212 /* MemberAccessExpression */ || cur.kind() === 121 /* QualifiedName */ || cur.kind() === 224 /* VariableDeclaration */ || cur.kind() === 225 /* VariableDeclarator */ || cur.kind() === 213 /* InvocationExpression */ || pos === script.end() + script.trailingTriviaWidth(); - - var minChar = cur.start(); - var limChar = cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0) + (inclusive ? 1 : 0); - if (pos >= minChar && pos < limChar) { - if ((cur.kind() !== 1 /* List */ && cur.kind() !== 2 /* SeparatedList */) || cur.end() > cur.start()) { - if (top === null) { - top = cur; - } else if (cur.start() >= top.start() && (cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0)) <= (top.end() + (useTrailingTriviaAsLimChar ? top.trailingTriviaWidth() : 0))) { - if (top.width() !== 0 || cur.width() !== 0) { + var minChar = cur.start(); + var limChar = cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0) + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + if ((cur.kind() !== 1 /* List */ && cur.kind() !== 2 /* SeparatedList */) || cur.end() > cur.start()) { + if (top === null) { top = cur; + } else if (cur.start() >= top.start() && (cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0)) <= (top.end() + (useTrailingTriviaAsLimChar ? top.trailingTriviaWidth() : 0))) { + if (top.width() !== 0 || cur.width() !== 0) { + top = cur; + } } } } - } - walker.options.goChildren = (minChar <= pos && pos <= limChar); + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + }; + + TypeScript.getAstWalkerFactory().walk(script, pre); + return top; + } + ASTHelpers.getAstAtPosition = getAstAtPosition; + + function getExtendsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 230 /* ExtendsHeritageClause */; + }); + } + ASTHelpers.getExtendsHeritageClause = getExtendsHeritageClause; + + function getImplementsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 231 /* ImplementsHeritageClause */; + }); + } + ASTHelpers.getImplementsHeritageClause = getImplementsHeritageClause; + + function isCallExpression(ast) { + return (ast && ast.kind() === 213 /* InvocationExpression */) || (ast && ast.kind() === 216 /* ObjectCreationExpression */); + } + ASTHelpers.isCallExpression = isCallExpression; + + function isCallExpressionTarget(ast) { + if (!ast) { + return false; + } + + var current = ast; + + while (current && current.parent) { + if (current.parent.kind() === 212 /* MemberAccessExpression */ && current.parent.name === current) { + current = current.parent; + continue; + } + + break; + } + + if (current && current.parent) { + if (current.parent.kind() === 213 /* InvocationExpression */ || current.parent.kind() === 216 /* ObjectCreationExpression */) { + return current === current.parent.expression; } } - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - return top; - } - TypeScript.getAstAtPosition = getAstAtPosition; - - function getExtendsHeritageClause(clauses) { - if (!clauses) { - return null; + return false; } + ASTHelpers.isCallExpressionTarget = isCallExpressionTarget; - return clauses.firstOrDefault(function (c) { - return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 230 /* ExtendsHeritageClause */; - }); - } - TypeScript.getExtendsHeritageClause = getExtendsHeritageClause; + function isNameOfSomeDeclaration(ast) { + if (ast === null || ast.parent === null) { + return false; + } + if (ast.kind() !== 11 /* IdentifierName */) { + return false; + } - function getImplementsHeritageClause(clauses) { - if (!clauses) { - return null; - } + switch (ast.parent.kind()) { + case 131 /* ClassDeclaration */: + return ast.parent.identifier === ast; + case 128 /* InterfaceDeclaration */: + return ast.parent.identifier === ast; + case 132 /* EnumDeclaration */: + return ast.parent.identifier === ast; + case 130 /* ModuleDeclaration */: + return ast.parent.name === ast || ast.parent.stringLiteral === ast; + case 225 /* VariableDeclarator */: + return ast.parent.propertyName === ast; + case 129 /* FunctionDeclaration */: + return ast.parent.identifier === ast; + case 135 /* MemberFunctionDeclaration */: + return ast.parent.propertyName === ast; + case 242 /* Parameter */: + return ast.parent.identifier === ast; + case 238 /* TypeParameter */: + return ast.parent.identifier === ast; + case 240 /* SimplePropertyAssignment */: + return ast.parent.propertyName === ast; + case 241 /* FunctionPropertyAssignment */: + return ast.parent.propertyName === ast; + case 243 /* EnumElement */: + return ast.parent.propertyName === ast; + case 133 /* ImportDeclaration */: + return ast.parent.identifier === ast; + } - return clauses.firstOrDefault(function (c) { - return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 231 /* ImplementsHeritageClause */; - }); - } - TypeScript.getImplementsHeritageClause = getImplementsHeritageClause; - - function isCallExpression(ast) { - return (ast && ast.kind() === 213 /* InvocationExpression */) || (ast && ast.kind() === 216 /* ObjectCreationExpression */); - } - TypeScript.isCallExpression = isCallExpression; - - function isCallExpressionTarget(ast) { - if (!ast) { return false; } - var current = ast; + function isDeclarationASTOrDeclarationNameAST(ast) { + return isNameOfSomeDeclaration(ast) || isDeclarationAST(ast); + } + ASTHelpers.isDeclarationASTOrDeclarationNameAST = isDeclarationASTOrDeclarationNameAST; + + function getEnclosingParameterForInitializer(ast) { + var current = ast; + while (current) { + switch (current.kind()) { + case 232 /* EqualsValueClause */: + if (current.parent && current.parent.kind() === 242 /* Parameter */) { + return current.parent; + } + break; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } - while (current && current.parent) { - if (current.parent.kind() === 212 /* MemberAccessExpression */ && current.parent.name === current) { current = current.parent; - continue; + } + return null; + } + ASTHelpers.getEnclosingParameterForInitializer = getEnclosingParameterForInitializer; + + function getEnclosingMemberVariableDeclaration(ast) { + var current = ast; + + while (current) { + switch (current.kind()) { + case 136 /* MemberVariableDeclaration */: + return current; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + current = current.parent; } - break; + return null; } + ASTHelpers.getEnclosingMemberVariableDeclaration = getEnclosingMemberVariableDeclaration; - if (current && current.parent) { - if (current.parent.kind() === 213 /* InvocationExpression */ || current.parent.kind() === 216 /* ObjectCreationExpression */) { - return current === current.parent.expression; + function isNameOfFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 129 /* FunctionDeclaration */ && ast.parent.identifier === ast; + } + ASTHelpers.isNameOfFunction = isNameOfFunction; + + function isNameOfMemberFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 135 /* MemberFunctionDeclaration */ && ast.parent.propertyName === ast; + } + ASTHelpers.isNameOfMemberFunction = isNameOfMemberFunction; + + function isNameOfMemberAccessExpression(ast) { + if (ast && ast.parent && ast.parent.kind() === 212 /* MemberAccessExpression */ && ast.parent.name === ast) { + return true; } - } - return false; - } - TypeScript.isCallExpressionTarget = isCallExpressionTarget; - - function isNameOfSomeDeclaration(ast) { - if (ast === null || ast.parent === null) { return false; } - if (ast.kind() !== 11 /* IdentifierName */) { + ASTHelpers.isNameOfMemberAccessExpression = isNameOfMemberAccessExpression; + + function isRightSideOfQualifiedName(ast) { + if (ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast) { + return true; + } + return false; } + ASTHelpers.isRightSideOfQualifiedName = isRightSideOfQualifiedName; - switch (ast.parent.kind()) { - case 131 /* ClassDeclaration */: - return ast.parent.identifier === ast; - case 128 /* InterfaceDeclaration */: - return ast.parent.identifier === ast; - case 132 /* EnumDeclaration */: - return ast.parent.identifier === ast; - case 130 /* ModuleDeclaration */: - return ast.parent.name === ast || ast.parent.stringLiteral === ast; - case 225 /* VariableDeclarator */: - return ast.parent.propertyName === ast; - case 129 /* FunctionDeclaration */: - return ast.parent.identifier === ast; - case 135 /* MemberFunctionDeclaration */: - return ast.parent.propertyName === ast; - case 242 /* Parameter */: - return ast.parent.identifier === ast; - case 238 /* TypeParameter */: - return ast.parent.identifier === ast; - case 240 /* SimplePropertyAssignment */: - return ast.parent.propertyName === ast; - case 241 /* FunctionPropertyAssignment */: - return ast.parent.propertyName === ast; - case 243 /* EnumElement */: - return ast.parent.propertyName === ast; - case 133 /* ImportDeclaration */: - return ast.parent.identifier === ast; - } - - return false; - } - - function isDeclarationASTOrDeclarationNameAST(ast) { - return isNameOfSomeDeclaration(ast) || isDeclarationAST(ast); - } - TypeScript.isDeclarationASTOrDeclarationNameAST = isDeclarationASTOrDeclarationNameAST; - - function isNameOfFunction(ast) { - return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 129 /* FunctionDeclaration */ && ast.parent.identifier === ast; - } - TypeScript.isNameOfFunction = isNameOfFunction; - - function isNameOfMemberFunction(ast) { - return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 135 /* MemberFunctionDeclaration */ && ast.parent.propertyName === ast; - } - TypeScript.isNameOfMemberFunction = isNameOfMemberFunction; - - function isNameOfMemberAccessExpression(ast) { - if (ast && ast.parent && ast.parent.kind() === 212 /* MemberAccessExpression */ && ast.parent.name === ast) { - return true; - } - - return false; - } - TypeScript.isNameOfMemberAccessExpression = isNameOfMemberAccessExpression; - - function isRightSideOfQualifiedName(ast) { - if (ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast) { - return true; - } - - return false; - } - TypeScript.isRightSideOfQualifiedName = isRightSideOfQualifiedName; - - (function (Parameters) { - function fromIdentifier(id) { + function parametersFromIdentifier(id) { return { length: 1, lastParameterIsRest: function () { @@ -28122,9 +28191,9 @@ var TypeScript; } }; } - Parameters.fromIdentifier = fromIdentifier; + ASTHelpers.parametersFromIdentifier = parametersFromIdentifier; - function fromParameter(parameter) { + function parametersFromParameter(parameter) { return { length: 1, lastParameterIsRest: function () { @@ -28138,7 +28207,7 @@ var TypeScript; return parameter.identifier; }, typeAt: function (index) { - return TypeScript.getType(parameter); + return getType(parameter); }, initializerAt: function (index) { return parameter.equalsValueClause; @@ -28148,13 +28217,13 @@ var TypeScript; } }; } - Parameters.fromParameter = fromParameter; + ASTHelpers.parametersFromParameter = parametersFromParameter; function parameterIsOptional(parameter) { return parameter.questionToken !== null || parameter.equalsValueClause !== null; } - function fromParameterList(list) { + function parametersFromParameterList(list) { return { length: list.parameters.nonSeparatorCount(), lastParameterIsRest: function () { @@ -28168,7 +28237,7 @@ var TypeScript; return list.parameters.nonSeparatorAt(index).identifier; }, typeAt: function (index) { - return TypeScript.getType(list.parameters.nonSeparatorAt(index)); + return getType(list.parameters.nonSeparatorAt(index)); }, initializerAt: function (index) { return list.parameters.nonSeparatorAt(index).equalsValueClause; @@ -28178,240 +28247,251 @@ var TypeScript; } }; } - Parameters.fromParameterList = fromParameterList; - })(TypeScript.Parameters || (TypeScript.Parameters = {})); - var Parameters = TypeScript.Parameters; + ASTHelpers.parametersFromParameterList = parametersFromParameterList; - function isDeclarationAST(ast) { - switch (ast.kind()) { - case 225 /* VariableDeclarator */: - return getVariableStatement(ast) !== null; + function isDeclarationAST(ast) { + switch (ast.kind()) { + case 225 /* VariableDeclarator */: + return getVariableStatement(ast) !== null; - case 133 /* ImportDeclaration */: - case 131 /* ClassDeclaration */: - case 128 /* InterfaceDeclaration */: - case 242 /* Parameter */: - case 219 /* SimpleArrowFunctionExpression */: - case 218 /* ParenthesizedArrowFunctionExpression */: - case 144 /* IndexSignature */: - case 129 /* FunctionDeclaration */: - case 130 /* ModuleDeclaration */: - case 124 /* ArrayType */: - case 122 /* ObjectType */: - case 238 /* TypeParameter */: - case 137 /* ConstructorDeclaration */: - case 135 /* MemberFunctionDeclaration */: - case 139 /* GetAccessor */: - case 140 /* SetAccessor */: - case 136 /* MemberVariableDeclaration */: - case 138 /* IndexMemberDeclaration */: - case 132 /* EnumDeclaration */: - case 243 /* EnumElement */: - case 240 /* SimplePropertyAssignment */: - case 241 /* FunctionPropertyAssignment */: - case 222 /* FunctionExpression */: - case 142 /* CallSignature */: - case 143 /* ConstructSignature */: - case 145 /* MethodSignature */: - case 141 /* PropertySignature */: - return true; - default: - return false; + case 133 /* ImportDeclaration */: + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 242 /* Parameter */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 144 /* IndexSignature */: + case 129 /* FunctionDeclaration */: + case 130 /* ModuleDeclaration */: + case 124 /* ArrayType */: + case 122 /* ObjectType */: + case 238 /* TypeParameter */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + case 138 /* IndexMemberDeclaration */: + case 132 /* EnumDeclaration */: + case 243 /* EnumElement */: + case 240 /* SimplePropertyAssignment */: + case 241 /* FunctionPropertyAssignment */: + case 222 /* FunctionExpression */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + case 145 /* MethodSignature */: + case 141 /* PropertySignature */: + return true; + default: + return false; + } } - } - TypeScript.isDeclarationAST = isDeclarationAST; + ASTHelpers.isDeclarationAST = isDeclarationAST; - function docComments(ast) { - if (isDeclarationAST(ast)) { - var preComments = ast.kind() === 225 /* VariableDeclarator */ ? getVariableStatement(ast).preComments() : ast.preComments(); + function docComments(ast) { + if (isDeclarationAST(ast)) { + var preComments = ast.kind() === 225 /* VariableDeclarator */ ? getVariableStatement(ast).preComments() : ast.preComments(); - if (preComments && preComments.length > 0) { - var preCommentsLength = preComments.length; - var docComments = new Array(); - for (var i = preCommentsLength - 1; i >= 0; i--) { - if (isDocComment(preComments[i])) { - docComments.push(preComments[i]); - continue; + if (preComments && preComments.length > 0) { + var preCommentsLength = preComments.length; + var docComments = new Array(); + for (var i = preCommentsLength - 1; i >= 0; i--) { + if (isDocComment(preComments[i])) { + docComments.push(preComments[i]); + continue; + } + + break; } - break; + return docComments.reverse(); + } + } + + return TypeScript.sentinelEmptyArray; + } + ASTHelpers.docComments = docComments; + + function isDocComment(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + var fullText = comment.fullText(); + return fullText.charAt(2) === "*" && fullText.charAt(3) !== "/"; + } + + return false; + } + + function getParameterList(ast) { + if (ast) { + switch (ast.kind()) { + case 137 /* ConstructorDeclaration */: + return getParameterList(ast.callSignature); + case 129 /* FunctionDeclaration */: + return getParameterList(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getParameterList(ast.callSignature); + case 143 /* ConstructSignature */: + return getParameterList(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getParameterList(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getParameterList(ast.callSignature); + case 222 /* FunctionExpression */: + return getParameterList(ast.callSignature); + case 145 /* MethodSignature */: + return getParameterList(ast.callSignature); + case 125 /* ConstructorType */: + return ast.parameterList; + case 123 /* FunctionType */: + return ast.parameterList; + case 142 /* CallSignature */: + return ast.parameterList; + case 139 /* GetAccessor */: + return ast.parameterList; + case 140 /* SetAccessor */: + return ast.parameterList; + } + } + + return null; + } + ASTHelpers.getParameterList = getParameterList; + + function getType(ast) { + if (ast) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + return getType(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getType(ast.callSignature); + case 143 /* ConstructSignature */: + return getType(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getType(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getType(ast.callSignature); + case 222 /* FunctionExpression */: + return getType(ast.callSignature); + case 145 /* MethodSignature */: + return getType(ast.callSignature); + case 142 /* CallSignature */: + return getType(ast.typeAnnotation); + case 144 /* IndexSignature */: + return getType(ast.typeAnnotation); + case 141 /* PropertySignature */: + return getType(ast.typeAnnotation); + case 139 /* GetAccessor */: + return getType(ast.typeAnnotation); + case 242 /* Parameter */: + return getType(ast.typeAnnotation); + case 136 /* MemberVariableDeclaration */: + return getType(ast.variableDeclarator); + case 225 /* VariableDeclarator */: + return getType(ast.typeAnnotation); + case 236 /* CatchClause */: + return getType(ast.typeAnnotation); + case 125 /* ConstructorType */: + return ast.type; + case 123 /* FunctionType */: + return ast.type; + case 244 /* TypeAnnotation */: + return ast.type; + } + } + + return null; + } + ASTHelpers.getType = getType; + + function getVariableStatement(variableDeclarator) { + if (variableDeclarator && variableDeclarator.parent && variableDeclarator.parent.parent && variableDeclarator.parent.parent.parent && variableDeclarator.parent.kind() === 2 /* SeparatedList */ && variableDeclarator.parent.parent.kind() === 224 /* VariableDeclaration */ && variableDeclarator.parent.parent.parent.kind() === 148 /* VariableStatement */) { + return variableDeclarator.parent.parent.parent; + } + + return null; + } + + function getVariableDeclaratorModifiers(variableDeclarator) { + var variableStatement = getVariableStatement(variableDeclarator); + return variableStatement ? variableStatement.modifiers : TypeScript.sentinelEmptyArray; + } + ASTHelpers.getVariableDeclaratorModifiers = getVariableDeclaratorModifiers; + + function isIntegerLiteralAST(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.kind() === 13 /* NumericLiteral */ && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + ASTHelpers.isIntegerLiteralAST = isIntegerLiteralAST; + + function getEnclosingModuleDeclaration(ast) { + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + return ast; } - return docComments.reverse(); - } - } - - return TypeScript.sentinelEmptyArray; - } - TypeScript.docComments = docComments; - - function isDocComment(comment) { - if (comment.kind() === 6 /* MultiLineCommentTrivia */) { - var fullText = comment.fullText(); - return fullText.charAt(2) === "*" && fullText.charAt(3) !== "/"; - } - - return false; - } - - function getParameterList(ast) { - if (ast) { - switch (ast.kind()) { - case 137 /* ConstructorDeclaration */: - return ast.parameterList; - case 129 /* FunctionDeclaration */: - return getParameterList(ast.callSignature); - case 218 /* ParenthesizedArrowFunctionExpression */: - return getParameterList(ast.callSignature); - case 143 /* ConstructSignature */: - return getParameterList(ast.callSignature); - case 135 /* MemberFunctionDeclaration */: - return getParameterList(ast.callSignature); - case 241 /* FunctionPropertyAssignment */: - return getParameterList(ast.callSignature); - case 222 /* FunctionExpression */: - return getParameterList(ast.callSignature); - case 145 /* MethodSignature */: - return getParameterList(ast.callSignature); - case 125 /* ConstructorType */: - return ast.parameterList; - case 123 /* FunctionType */: - return ast.parameterList; - case 142 /* CallSignature */: - return ast.parameterList; - case 139 /* GetAccessor */: - return ast.parameterList; - case 140 /* SetAccessor */: - return ast.parameterList; - } - } - - return null; - } - TypeScript.getParameterList = getParameterList; - - function getType(ast) { - if (ast) { - switch (ast.kind()) { - case 129 /* FunctionDeclaration */: - return getType(ast.callSignature); - case 218 /* ParenthesizedArrowFunctionExpression */: - return getType(ast.callSignature); - case 143 /* ConstructSignature */: - return getType(ast.callSignature); - case 135 /* MemberFunctionDeclaration */: - return getType(ast.callSignature); - case 241 /* FunctionPropertyAssignment */: - return getType(ast.callSignature); - case 222 /* FunctionExpression */: - return getType(ast.callSignature); - case 145 /* MethodSignature */: - return getType(ast.callSignature); - case 142 /* CallSignature */: - return getType(ast.typeAnnotation); - case 144 /* IndexSignature */: - return getType(ast.typeAnnotation); - case 141 /* PropertySignature */: - return getType(ast.typeAnnotation); - case 139 /* GetAccessor */: - return getType(ast.typeAnnotation); - case 242 /* Parameter */: - return getType(ast.typeAnnotation); - case 136 /* MemberVariableDeclaration */: - return getType(ast.variableDeclarator); - case 225 /* VariableDeclarator */: - return getType(ast.typeAnnotation); - case 236 /* CatchClause */: - return getType(ast.typeAnnotation); - case 125 /* ConstructorType */: - return ast.type; - case 123 /* FunctionType */: - return ast.type; - case 244 /* TypeAnnotation */: - return ast.type; - } - } - - return null; - } - TypeScript.getType = getType; - - function getVariableStatement(variableDeclarator) { - if (variableDeclarator && variableDeclarator.parent && variableDeclarator.parent.parent && variableDeclarator.parent.parent.parent && variableDeclarator.parent.kind() === 2 /* SeparatedList */ && variableDeclarator.parent.parent.kind() === 224 /* VariableDeclaration */ && variableDeclarator.parent.parent.parent.kind() === 148 /* VariableStatement */) { - return variableDeclarator.parent.parent.parent; - } - - return null; - } - - function getVariableDeclaratorModifiers(variableDeclarator) { - var variableStatement = getVariableStatement(variableDeclarator); - return variableStatement ? variableStatement.modifiers : TypeScript.sentinelEmptyArray; - } - TypeScript.getVariableDeclaratorModifiers = getVariableDeclaratorModifiers; - - function isIntegerLiteralAST(expression) { - if (expression) { - switch (expression.kind()) { - case 164 /* PlusExpression */: - case 165 /* NegateExpression */: - expression = expression.operand; - return expression.kind() === 13 /* NumericLiteral */ && TypeScript.IntegerUtilities.isInteger(expression.text()); - - case 13 /* NumericLiteral */: - var text = expression.text(); - return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); - } - } - - return false; - } - TypeScript.isIntegerLiteralAST = isIntegerLiteralAST; - - function getEnclosingModuleDeclaration(ast) { - while (ast) { - if (ast.kind() === 130 /* ModuleDeclaration */) { - return ast; + ast = ast.parent; } - ast = ast.parent; + return null; } + ASTHelpers.getEnclosingModuleDeclaration = getEnclosingModuleDeclaration; - return null; - } - TypeScript.getEnclosingModuleDeclaration = getEnclosingModuleDeclaration; + function isLastNameOfModule(ast, astName) { + if (ast) { + if (ast.stringLiteral) { + return astName === ast.stringLiteral; + } else { + var moduleNames = TypeScript.getModuleNames(ast.name); + var nameIndex = moduleNames.indexOf(astName); - function isLastNameOfModule(ast, astName) { - if (ast) { - if (ast.stringLiteral) { - return astName === ast.stringLiteral; + return nameIndex === (moduleNames.length - 1); + } + } + + return false; + } + ASTHelpers.isLastNameOfModule = isLastNameOfModule; + + function isAnyNameOfModule(ast, astName) { + if (ast) { + if (ast.stringLiteral) { + return ast.stringLiteral === astName; + } else { + var moduleNames = TypeScript.getModuleNames(ast.name); + var nameIndex = moduleNames.indexOf(astName); + + return nameIndex >= 0; + } + } + + return false; + } + ASTHelpers.isAnyNameOfModule = isAnyNameOfModule; + + function getNameOfIdenfierOrQualifiedName(name) { + if (name.kind() === 11 /* IdentifierName */) { + return name.text(); } else { - var moduleNames = TypeScript.getModuleNames(ast.name); - var nameIndex = moduleNames.indexOf(astName); - - return nameIndex === (moduleNames.length - 1); + TypeScript.Debug.assert(name.kind() == 121 /* QualifiedName */); + var dotExpr = name; + return getNameOfIdenfierOrQualifiedName(dotExpr.left) + "." + getNameOfIdenfierOrQualifiedName(dotExpr.right); } } - - return false; - } - TypeScript.isLastNameOfModule = isLastNameOfModule; - - function isAnyNameOfModule(ast, astName) { - if (ast) { - if (ast.stringLiteral) { - return ast.stringLiteral === astName; - } else { - var moduleNames = TypeScript.getModuleNames(ast.name); - var nameIndex = moduleNames.indexOf(astName); - - return nameIndex >= 0; - } - } - - return false; - } - TypeScript.isAnyNameOfModule = isAnyNameOfModule; + ASTHelpers.getNameOfIdenfierOrQualifiedName = getNameOfIdenfierOrQualifiedName; + })(TypeScript.ASTHelpers || (TypeScript.ASTHelpers = {})); + var ASTHelpers = TypeScript.ASTHelpers; })(TypeScript || (TypeScript = {})); var TypeScript; (function (TypeScript) { @@ -28619,7 +28699,7 @@ var TypeScript; } function walkConstructorDeclarationChildren(preAst, walker) { - walker.walk(preAst.parameterList); + walker.walk(preAst.callSignature); walker.walk(preAst.block); } @@ -29412,9 +29492,17 @@ var TypeScript; var settings = compiler.compilationSettings(); this._settings = settings; - if (settings.moduleGenTarget() === 0 /* Unspecified */ && compiler._isDynamicModuleCompilation()) { - this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_compile_external_modules_unless_the_module_flag_is_provided, null); - return; + if (settings.moduleGenTarget() === 0 /* Unspecified */) { + var fileNames = compiler.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = compiler.getDocument(fileNames[i]); + if (!document.isDeclareFile() && document.isExternalModule()) { + var errorSpan = document.externalModuleIndicatorSpan(); + this._diagnostic = new TypeScript.Diagnostic(document.fileName, document.lineMap(), errorSpan.start(), errorSpan.length(), TypeScript.DiagnosticCode.Cannot_compile_external_modules_unless_the_module_flag_is_provided); + + return; + } + } } if (!settings.mapSourceFiles()) { @@ -29496,7 +29584,7 @@ var TypeScript; updatedPath = true; if (j === 0) { - if (this._outputDirectory || this._sourceRootDirectory || (this._sourceMapRootDirectory && (!this._sharedOutputFile || compiler._isDynamicModuleCompilation()))) { + if (this._outputDirectory || this._sourceMapRootDirectory) { this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_find_the_common_subdirectory_path_for_the_input_files, null); return; } @@ -29573,10 +29661,10 @@ var TypeScript; this.sourceMapper = null; this.captureThisStmtString = "var _this = this;"; this.declStack = []; - this.exportAssignmentIdentifier = null; + this.exportAssignment = null; this.inWithBlock = false; this.document = null; - this.copyrightElement = null; + this.detachedCommentsElement = null; } Emitter.prototype.pushDecl = function (decl) { if (decl) { @@ -29596,12 +29684,12 @@ var TypeScript; return enclosingDecl; }; - Emitter.prototype.setExportAssignmentIdentifier = function (id) { - this.exportAssignmentIdentifier = id; + Emitter.prototype.setExportAssignment = function (exportAssignment) { + this.exportAssignment = exportAssignment; }; - Emitter.prototype.getExportAssignmentIdentifier = function () { - return this.exportAssignmentIdentifier; + Emitter.prototype.getExportAssignment = function () { + return this.exportAssignment; }; Emitter.prototype.setDocument = function (document) { @@ -29609,14 +29697,46 @@ var TypeScript; }; Emitter.prototype.shouldEmitImportDeclaration = function (importDeclAST) { - return TypeScript.importDeclarationIsElided(importDeclAST, this.semanticInfoChain, this.emitOptions.compilationSettings()); + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + if (isExternalModuleReference && !isExported && isAmdCodeGen) { + return false; + } + + var importSymbol = importDecl.getSymbol(); + if (importSymbol.isUsedAsValue()) { + return true; + } + + if (importDeclAST.moduleReference.kind() !== 245 /* ExternalModuleReference */) { + var canBeUsedExternally = isExported || importSymbol.typeUsedExternally() || importSymbol.isUsedInExportedAlias(); + if (!canBeUsedExternally && !this.document.isExternalModule()) { + canBeUsedExternally = TypeScript.hasFlag(importDecl.getParentDecl().kind, 1 /* Script */ | 32 /* DynamicModule */); + } + + if (canBeUsedExternally) { + if (importSymbol.getExportAssignedValueSymbol()) { + return true; + } + + var containerSymbol = importSymbol.getExportAssignedContainerSymbol(); + if (containerSymbol && containerSymbol.getInstanceSymbol()) { + return true; + } + } + } + + return false; }; Emitter.prototype.emitImportDeclaration = function (importDeclAST) { var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); - var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() == 2 /* Asynchronous */; + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; this.emitComments(importDeclAST, true); @@ -29631,12 +29751,12 @@ var TypeScript; var usePropertyAssignmentInsteadOfVarDecl = false; var moduleNamePrefix; - if (isExported && (parentKind == 4 /* Container */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */)) { + if (isExported && (parentKind === 4 /* Container */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */)) { if (importSymbol.getExportAssignedTypeSymbol() || importSymbol.getExportAssignedContainerSymbol()) { needsPropertyAssignment = true; } else { var valueSymbol = importSymbol.getExportAssignedValueSymbol(); - if (valueSymbol && (valueSymbol.kind == 65536 /* Method */ || valueSymbol.kind == 16384 /* Function */)) { + if (valueSymbol && (valueSymbol.kind === 65536 /* Method */ || valueSymbol.kind === 16384 /* Function */)) { needsPropertyAssignment = true; } else { usePropertyAssignmentInsteadOfVarDecl = true; @@ -29783,14 +29903,14 @@ var TypeScript; this.writeLineToOutput(""); } - if (!trailing && emitColumn != 0) { + if (!trailing && emitColumn !== 0) { this.emitIndent(); } }; Emitter.prototype.emitComments = function (ast, pre, onlyPinnedOrTripleSlashComments) { - if (typeof onlyPinnedOrTripleSlashComments === "undefined") { onlyPinnedOrTripleSlashComments = false; } var _this = this; + if (typeof onlyPinnedOrTripleSlashComments === "undefined") { onlyPinnedOrTripleSlashComments = false; } if (ast && ast.kind() !== 146 /* Block */) { if (ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ || ast.parent.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { return; @@ -29800,12 +29920,13 @@ var TypeScript; if (pre) { var preComments = ast.preComments(); - if (preComments && ast === this.copyrightElement) { - var copyrightComments = this.getCopyrightComments(); - preComments = preComments.slice(copyrightComments.length); + if (preComments && ast === this.detachedCommentsElement) { + var detachedComments = this.getDetachedComments(ast); + preComments = preComments.slice(detachedComments.length); + this.detachedCommentsElement = null; } - if (onlyPinnedOrTripleSlashComments) { + if (preComments && onlyPinnedOrTripleSlashComments) { preComments = TypeScript.ArrayUtilities.where(preComments, function (c) { return _this.isPinnedOrTripleSlash(c); }); @@ -29946,7 +30067,7 @@ var TypeScript; Emitter.prototype.emitParameterList = function (list) { this.writeToOutput("("); this.emitCommentsArray(list.openParenTrailingComments, true); - this.emitFunctionParameters(TypeScript.Parameters.fromParameterList(list)); + this.emitFunctionParameters(TypeScript.ASTHelpers.parametersFromParameterList(list)); this.writeToOutput(")"); }; @@ -29984,15 +30105,19 @@ var TypeScript; this.indenter.increaseIndent(); - if (parameterList) { - this.emitDefaultValueAssignments(parameterList); - this.emitRestParameterInitializer(parameterList); + if (block) { + this.emitDetachedComments(block.statements); } if (this.shouldCaptureThis(funcDecl)) { this.writeCaptureThisStatement(funcDecl); } + if (parameterList) { + this.emitDefaultValueAssignments(parameterList); + this.emitRestParameterInitializer(parameterList); + } + if (block) { this.emitList(block.statements); this.emitCommentsArray(block.closeBraceLeadingComments, false); @@ -30243,12 +30368,24 @@ var TypeScript; return null; }; - Emitter.prototype.hasChildNameCollision = function (moduleName, childDecls) { + Emitter.prototype.hasChildNameCollision = function (moduleName, parentDecl) { var _this = this; + var childDecls = parentDecl.getChildDecls(); return TypeScript.ArrayUtilities.any(childDecls, function (childDecl) { - if (childDecl.name == moduleName) { - var childAST = _this.semanticInfoChain.getASTForDecl(childDecl); - if (_this.shouldEmit(childAST)) { + var childAST = _this.semanticInfoChain.getASTForDecl(childDecl); + + if (childDecl.kind != 67108864 /* EnumMember */ && _this.shouldEmit(childAST)) { + if (childDecl.name === moduleName) { + if (parentDecl.kind != 8 /* Class */) { + return true; + } + + if (!(childDecl.kind == 65536 /* Method */ || childDecl.kind == 4096 /* Property */ || childDecl.kind == 524288 /* SetAccessor */ || childDecl.kind == 262144 /* GetAccessor */)) { + return true; + } + } + + if (_this.hasChildNameCollision(moduleName, childDecl)) { return true; } } @@ -30261,10 +30398,8 @@ var TypeScript; var moduleDisplayName = moduleDecl.getDisplayName(); moduleDecl = this.getModuleDeclToVerifyChildNameCollision(moduleDecl, changeNameIfAnyDeclarationInContext); - if (moduleDecl) { - var childDecls = moduleDecl.getChildDecls(); - - while (this.hasChildNameCollision(moduleName, childDecls)) { + if (moduleDecl && moduleDecl.kind != 64 /* Enum */) { + while (this.hasChildNameCollision(moduleName, moduleDecl)) { moduleName = "_" + moduleName; moduleDisplayName = "_" + moduleDisplayName; } @@ -30283,7 +30418,7 @@ var TypeScript; }; Emitter.prototype.emitSingleModuleDeclaration = function (moduleDecl, moduleName) { - var isLastName = TypeScript.isLastNameOfModule(moduleDecl, moduleName); + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDecl, moduleName); if (isLastName) { this.emitComments(moduleDecl, true); @@ -30444,11 +30579,11 @@ var TypeScript; }; Emitter.prototype.emitSimpleArrowFunctionExpression = function (arrowFunction) { - this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.Parameters.fromIdentifier(arrowFunction.identifier), arrowFunction.block, arrowFunction.expression); + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), arrowFunction.block, arrowFunction.expression); }; Emitter.prototype.emitParenthesizedArrowFunctionExpression = function (arrowFunction) { - this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.Parameters.fromParameterList(arrowFunction.callSignature.parameterList), arrowFunction.block, arrowFunction.expression); + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), arrowFunction.block, arrowFunction.expression); }; Emitter.prototype.emitAnyArrowFunctionExpression = function (arrowFunction, funcName, parameters, block, expression) { @@ -30500,7 +30635,7 @@ var TypeScript; this.writeToOutput("function "); this.writeToOutput(this.thisClassNode.identifier.text()); this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(funcDecl.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); this.emitFunctionParameters(parameters); this.writeLineToOutput(") {"); @@ -30554,7 +30689,7 @@ var TypeScript; this.writeToOutput("("); this.writeToOutput(")"); - this.emitFunctionBodyStatements(null, accessor, TypeScript.Parameters.fromParameterList(accessor.parameterList), accessor.block, null); + this.emitFunctionBodyStatements(null, accessor, TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList), accessor.block, null); this.recordSourceMappingEnd(accessor); @@ -30586,7 +30721,7 @@ var TypeScript; this.writeToOutput(accessor.propertyName.text()); this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(accessor.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList); this.emitFunctionParameters(parameters); this.writeToOutput(")"); @@ -30625,7 +30760,7 @@ var TypeScript; this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); this.emitFunctionParameters(parameters); this.writeToOutput(")"); @@ -30680,7 +30815,7 @@ var TypeScript; this.emitParameterList(funcDecl.callSignature.parameterList); - var parameters = TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); this.emitFunctionBodyStatements(funcDecl.identifier.text(), funcDecl, parameters, funcDecl.block, null); this.recordSourceMappingEnd(funcDecl); @@ -30953,7 +31088,7 @@ var TypeScript; if (pullSymbol && pullSymbolAlias) { var symbolToCompare = TypeScript.isTypesOnlyLocation(ast) ? pullSymbolAlias.getExportAssignedTypeSymbol() : pullSymbolAlias.getExportAssignedValueSymbol(); - if (pullSymbol == symbolToCompare) { + if (pullSymbol === symbolToCompare) { pullSymbol = pullSymbolAlias; pullSymbolAlias = null; } @@ -30972,7 +31107,7 @@ var TypeScript; } var pullSymbolAlias = symbolForEmit.aliasSymbol; var pullSymbolKind = pullSymbol.kind; - var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() == this.getEnclosingDecl()); + var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() === this.getEnclosingDecl()); if (addThis && (this.emitState.container !== 6 /* Args */) && pullSymbol) { var pullSymbolContainer = pullSymbol.getContainer(); @@ -31017,19 +31152,19 @@ var TypeScript; if (name) { if (this.sourceMapper.currentNameIndex.length > 0) { var parentNameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; - if (parentNameIndex != -1) { + if (parentNameIndex !== -1) { name = this.sourceMapper.names[parentNameIndex] + "." + name; } } var nameIndex = this.sourceMapper.names.length - 1; for (nameIndex; nameIndex >= 0; nameIndex--) { - if (this.sourceMapper.names[nameIndex] == name) { + if (this.sourceMapper.names[nameIndex] === name) { break; } } - if (nameIndex == -1) { + if (nameIndex === -1) { nameIndex = this.sourceMapper.names.length; this.sourceMapper.names.push(name); } @@ -31045,7 +31180,7 @@ var TypeScript; }; Emitter.prototype.recordSourceMappingStart = function (ast) { - if (this.sourceMapper && TypeScript.isValidAstNode(ast)) { + if (this.sourceMapper && TypeScript.ASTHelpers.isValidAstNode(ast)) { var lineCol = { line: -1, character: -1 }; var sourceMapping = new TypeScript.SourceMapping(); sourceMapping.start.emittedColumn = this.emitState.column; @@ -31078,7 +31213,7 @@ var TypeScript; }; Emitter.prototype.recordSourceMappingEnd = function (ast) { - if (this.sourceMapper && TypeScript.isValidAstNode(ast)) { + if (this.sourceMapper && TypeScript.ASTHelpers.isValidAstNode(ast)) { this.sourceMapper.currentMappings.pop(); var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; @@ -31108,9 +31243,9 @@ var TypeScript; Emitter.prototype.emitParameterPropertyAndMemberVariableAssignments = function () { var constructorDecl = getLastConstructor(this.thisClassNode); - if (constructorDecl && constructorDecl.parameterList) { - for (var i = 0, n = constructorDecl.parameterList.parameters.nonSeparatorCount(); i < n; i++) { - var parameter = constructorDecl.parameterList.parameters.nonSeparatorAt(i); + if (constructorDecl) { + for (var i = 0, n = constructorDecl.callSignature.parameterList.parameters.nonSeparatorCount(); i < n; i++) { + var parameter = constructorDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { this.emitIndent(); @@ -31270,12 +31405,12 @@ var TypeScript; } }; - Emitter.prototype.getCopyrightComments = function () { - var preComments = this.copyrightElement.preComments(); + Emitter.prototype.getDetachedComments = function (element) { + var preComments = element.preComments(); if (preComments) { var lineMap = this.document.lineMap(); - var copyrightComments = []; + var detachedComments = []; var lastComment = null; for (var i = 0, n = preComments.length; i < n; i++) { @@ -31286,18 +31421,18 @@ var TypeScript; var commentLine = lineMap.getLineNumberFromPosition(comment.start()); if (commentLine >= lastCommentLine + 2) { - return copyrightComments; + return detachedComments; } } - copyrightComments.push(comment); + detachedComments.push(comment); lastComment = comment; } - var lastCommentLine = lineMap.getLineNumberFromPosition(TypeScript.ArrayUtilities.last(copyrightComments).end()); - var astLine = lineMap.getLineNumberFromPosition(this.copyrightElement.start()); + var lastCommentLine = lineMap.getLineNumberFromPosition(TypeScript.ArrayUtilities.last(detachedComments).end()); + var astLine = lineMap.getLineNumberFromPosition(element.start()); if (astLine >= lastCommentLine + 2) { - return copyrightComments; + return detachedComments; } } @@ -31305,12 +31440,15 @@ var TypeScript; }; Emitter.prototype.emitPossibleCopyrightHeaders = function (script) { - var list = script.moduleElements; + this.emitDetachedComments(script.moduleElements); + }; + + Emitter.prototype.emitDetachedComments = function (list) { if (list.childCount() > 0) { var firstElement = list.childAt(0); - this.copyrightElement = firstElement; - this.emitCommentsArray(this.getCopyrightComments(), false); + this.detachedCommentsElement = firstElement; + this.emitCommentsArray(this.getDetachedComments(this.detachedCommentsElement), false); } }; @@ -31333,7 +31471,7 @@ var TypeScript; this.emitPrologue(sourceUnit); var isExternalModule = this.document.isExternalModule(); - var isNonElidedExternalModule = isExternalModule && !TypeScript.scriptIsElided(sourceUnit); + var isNonElidedExternalModule = isExternalModule && !TypeScript.ASTHelpers.scriptIsElided(sourceUnit); if (isNonElidedExternalModule) { this.recordSourceMappingStart(sourceUnit); @@ -31358,7 +31496,7 @@ var TypeScript; this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); } - this.setExportAssignmentIdentifier(null); + this.setExportAssignment(null); if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { this.indenter.increaseIndent(); @@ -31381,20 +31519,23 @@ var TypeScript; } if (isNonElidedExternalModule) { - var exportAssignmentIdentifier = this.getExportAssignmentIdentifier(); + var exportAssignment = this.getExportAssignment(); + var exportAssignmentIdentifierText = exportAssignment ? exportAssignment.identifier.text() : null; var exportAssignmentValueSymbol = externalModule.getSymbol().getExportAssignedValueSymbol(); if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { - if (exportAssignmentIdentifier && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { this.indenter.increaseIndent(); this.emitIndent(); - this.writeLineToOutput("return " + exportAssignmentIdentifier + ";"); + this.writeToOutputWithSourceMapRecord("return " + exportAssignmentIdentifierText, exportAssignment); + this.writeLineToOutput(";"); this.indenter.decreaseIndent(); } this.writeToOutput("});"); - } else if (exportAssignmentIdentifier && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + } else if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { this.emitIndent(); - this.writeToOutput("module.exports = " + exportAssignmentIdentifier + ";"); + this.writeToOutputWithSourceMapRecord("module.exports = " + exportAssignmentIdentifierText, exportAssignment); + this.writeToOutput(";"); } this.recordSourceMappingEnd(sourceUnit); @@ -31416,7 +31557,7 @@ var TypeScript; this.emitComments(list, true); - var emitPropertyAssignmentsAfterSuperCall = TypeScript.getExtendsHeritageClause(this.thisClassNode.heritageClauses) !== null; + var emitPropertyAssignmentsAfterSuperCall = TypeScript.ASTHelpers.getExtendsHeritageClause(this.thisClassNode.heritageClauses) !== null; var propertyAssignmentIndex = emitPropertyAssignmentsAfterSuperCall ? 1 : 0; var lastEmittedNode = null; @@ -31523,7 +31664,7 @@ var TypeScript; this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(parameterList); this.emitFunctionParameters(parameters); this.writeToOutput(")"); @@ -31548,7 +31689,7 @@ var TypeScript; this.recordSourceMappingStart(classDecl); this.writeToOutput("var " + className); - var hasBaseClass = TypeScript.getExtendsHeritageClause(classDecl.heritageClauses) !== null; + var hasBaseClass = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses) !== null; var baseTypeReference = null; var varDecl = null; @@ -31562,9 +31703,10 @@ var TypeScript; this.indenter.increaseIndent(); if (hasBaseClass) { - baseTypeReference = TypeScript.getExtendsHeritageClause(classDecl.heritageClauses).typeNames.nonSeparatorAt(0); + baseTypeReference = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses).typeNames.nonSeparatorAt(0); this.emitIndent(); - this.writeLineToOutput("__extends(" + className + ", _super);"); + this.writeToOutputWithSourceMapRecord("__extends(" + className + ", _super)", baseTypeReference); + this.writeLineToOutput(";"); } this.emitIndent(); @@ -31582,7 +31724,8 @@ var TypeScript; this.recordSourceMappingNameStart("constructor"); if (hasBaseClass) { this.emitIndent(); - this.writeLineToOutput("_super.apply(this, arguments);"); + this.writeToOutputWithSourceMapRecord("_super.apply(this, arguments)", baseTypeReference); + this.writeLineToOutput(";"); } if (this.shouldCaptureThis(classDecl)) { @@ -31593,7 +31736,8 @@ var TypeScript; this.indenter.decreaseIndent(); this.emitIndent(); - this.writeLineToOutput("}"); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.writeLineToOutput(""); this.recordSourceMappingNameEnd(); this.recordSourceMappingEnd(classDecl); @@ -31715,7 +31859,7 @@ var TypeScript; this.emitParameterList(funcDecl.callSignature.parameterList); - var parameters = TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); this.emitFunctionBodyStatements(funcDecl.propertyName.text(), funcDecl, parameters, funcDecl.block, null); this.recordSourceMappingEnd(funcDecl); @@ -31741,7 +31885,7 @@ var TypeScript; } else if (moduleElement.kind() === 131 /* ClassDeclaration */) { var classDeclaration = moduleElement; - if (!TypeScript.hasModifier(classDeclaration.modifiers, 8 /* Ambient */) && TypeScript.getExtendsHeritageClause(classDeclaration.heritageClauses) !== null) { + if (!TypeScript.hasModifier(classDeclaration.modifiers, 8 /* Ambient */) && TypeScript.ASTHelpers.getExtendsHeritageClause(classDeclaration.heritageClauses) !== null) { return true; } } @@ -31921,13 +32065,13 @@ var TypeScript; Emitter.prototype.canEmitDottedNameMemberAccessExpression = function (expression) { var memberExpressionNodeType = expression.expression.kind(); - if (memberExpressionNodeType == 11 /* IdentifierName */ || memberExpressionNodeType == 212 /* MemberAccessExpression */) { + if (memberExpressionNodeType === 11 /* IdentifierName */ || memberExpressionNodeType == 212 /* MemberAccessExpression */) { var memberAccessSymbol = this.getSymbolForEmit(expression).symbol; var memberAccessExpressionSymbol = this.getSymbolForEmit(expression.expression).symbol; if (memberAccessSymbol && memberAccessExpressionSymbol && !this.semanticInfoChain.getAliasSymbolForAST(expression.expression) && (TypeScript.PullHelpers.symbolIsModule(memberAccessExpressionSymbol) || memberAccessExpressionSymbol.kind === 64 /* Enum */ || memberAccessExpressionSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */))) { var memberAccessSymbolKind = memberAccessSymbol.kind; if (memberAccessSymbolKind === 4096 /* Property */ || memberAccessSymbolKind === 67108864 /* EnumMember */ || (memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && memberAccessSymbolKind === 512 /* Variable */ && !memberAccessSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) || ((memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && !this.symbolIsUsedInItsEnclosingContainer(memberAccessSymbol)))) { - if (memberExpressionNodeType == 212 /* MemberAccessExpression */) { + if (memberExpressionNodeType === 212 /* MemberAccessExpression */) { return this.canEmitDottedNameMemberAccessExpression(expression.expression); } @@ -31941,7 +32085,7 @@ var TypeScript; Emitter.prototype.emitDottedNameMemberAccessExpressionWorker = function (expression, potentialPath, startingIndex, lastIndex) { this.recordSourceMappingStart(expression); - if (expression.expression.kind() == 212 /* MemberAccessExpression */) { + if (expression.expression.kind() === 212 /* MemberAccessExpression */) { this.emitDottedNameMemberAccessExpressionRecurse(expression.expression, potentialPath, startingIndex, lastIndex - 1); } else { this.emitComments(expression.expression, true); @@ -32058,7 +32202,7 @@ var TypeScript; this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(funcProp.callSignature.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList); this.emitFunctionParameters(parameters); this.writeToOutput(")"); @@ -32074,8 +32218,6 @@ var TypeScript; this.setContainer(temp); this.inArrowFunction = savedInArrowFunction; - - this.recordSourceMappingEnd(funcProp); }; Emitter.prototype.emitConditionalExpression = function (expression) { @@ -32396,15 +32538,17 @@ var TypeScript; this.pushDecl(pullDecl); this.emitScriptElements(sourceUnit); this.popDecl(pullDecl); + + this.emitCommentsArray(sourceUnit.endOfFileTokenLeadingComments, false); } }; Emitter.prototype.shouldEmitEnumDeclaration = function (declaration) { - return declaration.preComments() !== null || !TypeScript.enumIsElided(declaration); + return declaration.preComments() !== null || !TypeScript.ASTHelpers.enumIsElided(declaration); }; Emitter.prototype.emitEnumDeclaration = function (declaration) { - if (!TypeScript.enumIsElided(declaration)) { + if (!TypeScript.ASTHelpers.enumIsElided(declaration)) { this.emitComments(declaration, true); this.emitEnum(declaration); this.emitComments(declaration, false); @@ -32414,11 +32558,11 @@ var TypeScript; }; Emitter.prototype.shouldEmitModuleDeclaration = function (declaration) { - return declaration.preComments() !== null || !TypeScript.moduleIsElided(declaration); + return declaration.preComments() !== null || !TypeScript.ASTHelpers.moduleIsElided(declaration); }; Emitter.prototype.emitModuleDeclaration = function (declaration) { - if (!TypeScript.moduleIsElided(declaration)) { + if (!TypeScript.ASTHelpers.moduleIsElided(declaration)) { this.emitModuleDeclarationWorker(declaration); } else { this.emitComments(declaration, true, true); @@ -32514,7 +32658,7 @@ var TypeScript; case 133 /* ImportDeclaration */: return this.emitImportDeclaration(ast); case 134 /* ExportAssignment */: - return this.setExportAssignmentIdentifier(ast.identifier.text()); + return this.setExportAssignment(ast); case 131 /* ClassDeclaration */: return this.emitClassDeclaration(ast); case 128 /* InterfaceDeclaration */: @@ -33253,10 +33397,10 @@ var TypeScript; var dtsFile = normalizedPath + ".d.ts"; var tsFile = normalizedPath + ".ts"; - if (this.host.fileExists(dtsFile)) { - normalizedPath = dtsFile; - } else { + if (this.host.fileExists(tsFile)) { normalizedPath = tsFile; + } else { + normalizedPath = dtsFile; } } @@ -33286,13 +33430,13 @@ var TypeScript; var start = new Date().getTime(); do { - var currentFilePath = this.host.resolveRelativePath(dtsFileName, parentDirectory); + currentFilePath = this.host.resolveRelativePath(tsFilePath, parentDirectory); if (this.host.fileExists(currentFilePath)) { searchFilePath = currentFilePath; break; } - currentFilePath = this.host.resolveRelativePath(tsFilePath, parentDirectory); + var currentFilePath = this.host.resolveRelativePath(dtsFileName, parentDirectory); if (this.host.fileExists(currentFilePath)) { searchFilePath = currentFilePath; break; @@ -33544,7 +33688,7 @@ var TypeScript; var declAST = this.semanticInfoChain.getASTForDecl(pullDecl); var container = this.getEnclosingContainer(declAST); - if (container.kind() === 130 /* ModuleDeclaration */ && TypeScript.isAnyNameOfModule(container, declAST)) { + if (container.kind() === 130 /* ModuleDeclaration */ && TypeScript.ASTHelpers.isAnyNameOfModule(container, declAST)) { container = this.getEnclosingContainer(container); } @@ -33555,8 +33699,8 @@ var TypeScript; emitDeclare = true; } - if (isExternalModule || container.kind() == 120 /* SourceUnit */) { - if (emitDeclare && typeString !== "interface" && typeString != "import") { + if (isExternalModule || container.kind() === 120 /* SourceUnit */) { + if (emitDeclare && typeString !== "interface" && typeString !== "import") { result += "declare "; } } @@ -33625,7 +33769,9 @@ var TypeScript; var declarationPullSymbol = declarationContainerDecl.getSymbol(); TypeScript.declarationEmitTypeSignatureTime += new Date().getTime() - start; - var typeNameMembers = type.getScopedNameEx(declarationPullSymbol); + var isNotAGenericType = ast.kind() !== 126 /* GenericType */; + + var typeNameMembers = type.getScopedNameEx(declarationPullSymbol, false, false, false, false, false, isNotAGenericType); this.emitTypeNamesMember(typeNameMembers); }; @@ -33659,7 +33805,7 @@ var TypeScript; return; } - var declComments = astOrSymbol.docComments ? astOrSymbol.docComments() : TypeScript.docComments(astOrSymbol); + var declComments = astOrSymbol.docComments ? astOrSymbol.docComments() : TypeScript.ASTHelpers.docComments(astOrSymbol); this.writeDeclarationComments(declComments, endLine); }; @@ -33718,7 +33864,7 @@ var TypeScript; this.declFile.Write(varDecl.propertyName.text()); - if (!TypeScript.hasModifier(TypeScript.getVariableDeclaratorModifiers(varDecl), 2 /* Private */)) { + if (!TypeScript.hasModifier(TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), 2 /* Private */)) { this.emitTypeOfVariableDeclaratorOrParameter(varDecl); } @@ -33770,7 +33916,7 @@ var TypeScript; DeclarationEmitter.prototype.emitDeclarationsForVariableDeclaration = function (variableDeclaration) { var varListCount = variableDeclaration.declarators.nonSeparatorCount(); for (var i = 0; i < varListCount; i++) { - this.emitVariableDeclarator(variableDeclaration.declarators.nonSeparatorAt(i), i == 0, i == varListCount - 1); + this.emitVariableDeclarator(variableDeclaration.declarators.nonSeparatorAt(i), i === 0, i === varListCount - 1); } }; @@ -33825,14 +33971,14 @@ var TypeScript; this.declFile.Write("constructor"); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); this.declFile.Write(")"); this.declFile.WriteLine(";"); }; DeclarationEmitter.prototype.emitParameterList = function (isPrivate, parameterList) { this.declFile.Write("("); - this.emitParameters(isPrivate, TypeScript.Parameters.fromParameterList(parameterList)); + this.emitParameters(isPrivate, TypeScript.ASTHelpers.parametersFromParameterList(parameterList)); this.declFile.Write(")"); }; @@ -33923,7 +34069,7 @@ var TypeScript; this.emitIndent(); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList)); this.declFile.Write(")"); var returnType = funcSignature.returnType; @@ -33954,7 +34100,7 @@ var TypeScript; this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); this.declFile.Write(")"); var returnType = funcSignature.returnType; @@ -33988,7 +34134,7 @@ var TypeScript; this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); this.declFile.Write(")"); var returnType = funcSignature.returnType; @@ -34038,7 +34184,7 @@ var TypeScript; this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); this.declFile.Write(")"); var returnType = funcSignature.returnType; @@ -34065,7 +34211,7 @@ var TypeScript; this.emitIndent(); this.declFile.Write("["); - this.emitParameters(false, TypeScript.Parameters.fromParameter(funcDecl.parameter)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter)); this.declFile.Write("]"); var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); @@ -34104,10 +34250,10 @@ var TypeScript; var comments = []; if (accessors.getter) { - comments = comments.concat(TypeScript.docComments(accessors.getter)); + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.getter)); } if (accessors.setter) { - comments = comments.concat(TypeScript.docComments(accessors.setter)); + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.setter)); } this.writeDeclarationComments(comments); @@ -34144,27 +34290,25 @@ var TypeScript; }; DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { - if (funcDecl.parameterList) { - var argsLen = funcDecl.parameterList.parameters.nonSeparatorCount(); - if (TypeScript.lastParameterIsRest(funcDecl.parameterList)) { - argsLen--; - } + var argsLen = funcDecl.callSignature.parameterList.parameters.nonSeparatorCount(); + if (TypeScript.lastParameterIsRest(funcDecl.callSignature.parameterList)) { + argsLen--; + } - for (var i = 0; i < argsLen; i++) { - var parameter = funcDecl.parameterList.parameters.nonSeparatorAt(i); - var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); - if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { - var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); - this.emitDeclarationComments(parameter); - this.declFile.Write(this.getIndentString()); - this.emitClassElementModifiers(parameter.modifiers); - this.declFile.Write(parameter.identifier.text()); + for (var i = 0; i < argsLen; i++) { + var parameter = funcDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.emitDeclarationComments(parameter); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(parameter.modifiers); + this.declFile.Write(parameter.identifier.text()); - if (!TypeScript.hasModifier(parameter.modifiers, 2 /* Private */)) { - this.emitTypeOfVariableDeclaratorOrParameter(parameter); - } - this.declFile.WriteLine(";"); + if (!TypeScript.hasModifier(parameter.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(parameter); } + this.declFile.WriteLine(";"); } } }; @@ -34296,20 +34440,11 @@ var TypeScript; if (importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { this.declFile.WriteLine("require(" + importDeclAST.moduleReference.stringLiteral.text() + ");"); } else { - this.declFile.WriteLine(this.getFullName(importDeclAST.moduleReference.moduleName) + ";"); + this.declFile.WriteLine(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(importDeclAST.moduleReference.moduleName) + ";"); } } }; - DeclarationEmitter.prototype.getFullName = function (name) { - if (name.kind() === 11 /* IdentifierName */) { - return name.text(); - } else { - var dotExpr = name; - return this.getFullName(dotExpr.left) + "." + this.getFullName(dotExpr.right); - } - }; - DeclarationEmitter.prototype.emitDeclarationsForEnumDeclaration = function (moduleDecl) { if (!this.canEmitDeclarations(moduleDecl)) { return; @@ -34329,7 +34464,7 @@ var TypeScript; this.emitDeclarationComments(enumElement); this.emitIndent(); this.declFile.Write(enumElement.propertyName.text()); - if (enumElementDecl.constantValue != null) { + if (enumElementDecl.constantValue !== null) { this.declFile.Write(" = " + enumElementDecl.constantValue); } this.declFile.WriteLine(","); @@ -34354,7 +34489,7 @@ var TypeScript; if (moduleDecl.stringLiteral) { this.declFile.Write(moduleDecl.stringLiteral.text()); } else { - this.declFile.Write(this.getFullName(moduleDecl.name)); + this.declFile.Write(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(moduleDecl.name)); } this.declFile.WriteLine(" {"); @@ -34417,12 +34552,12 @@ var TypeScript; if (document && (document.isDeclareFile() || document.isExternalModule())) { for (var k = 0; k < documents.length; k++) { - if (documents[k] == document) { + if (documents[k] === document) { break; } } - if (k == documents.length) { + if (k === documents.length) { documents = documents.concat(document); } } @@ -34522,16 +34657,16 @@ var TypeScript; }; BloomFilter.prototype.isEquivalent = function (filter) { - return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount == filter.hashFunctionCount; + return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount === filter.hashFunctionCount; }; BloomFilter.isEquivalent = function (array1, array2) { - if (array1.length != array2.length) { + if (array1.length !== array2.length) { return false; } for (var i = 0; i < array1.length; i++) { - if (array1[i] != array2[i]) { + if (array1[i] !== array2[i]) { return false; } } @@ -34580,13 +34715,14 @@ var TypeScript; this.useCaseSensitiveFileResolution = false; this.gatherDiagnostics = false; this.codepage = null; + this.createFileLog = false; } return CompilationSettings; })(); TypeScript.CompilationSettings = CompilationSettings; var ImmutableCompilationSettings = (function () { - function ImmutableCompilationSettings(propagateEnumConstants, removeComments, watch, noResolve, allowAutomaticSemicolonInsertion, noImplicitAny, noLib, codeGenTarget, moduleGenTarget, outFileOption, outDirOption, mapSourceFiles, mapRoot, sourceRoot, generateDeclarationFiles, useCaseSensitiveFileResolution, gatherDiagnostics, codepage) { + function ImmutableCompilationSettings(propagateEnumConstants, removeComments, watch, noResolve, allowAutomaticSemicolonInsertion, noImplicitAny, noLib, codeGenTarget, moduleGenTarget, outFileOption, outDirOption, mapSourceFiles, mapRoot, sourceRoot, generateDeclarationFiles, useCaseSensitiveFileResolution, gatherDiagnostics, codepage, createFileLog) { this._propagateEnumConstants = propagateEnumConstants; this._removeComments = removeComments; this._watch = watch; @@ -34605,6 +34741,7 @@ var TypeScript; this._useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; this._gatherDiagnostics = gatherDiagnostics; this._codepage = codepage; + this._createFileLog = createFileLog; } ImmutableCompilationSettings.prototype.propagateEnumConstants = function () { return this._propagateEnumConstants; @@ -34660,6 +34797,9 @@ var TypeScript; ImmutableCompilationSettings.prototype.codepage = function () { return this._codepage; }; + ImmutableCompilationSettings.prototype.createFileLog = function () { + return this._createFileLog; + }; ImmutableCompilationSettings.defaultSettings = function () { if (!ImmutableCompilationSettings._defaultSettings) { @@ -34670,15 +34810,17 @@ var TypeScript; }; ImmutableCompilationSettings.fromCompilationSettings = function (settings) { - return new ImmutableCompilationSettings(settings.propagateEnumConstants, settings.removeComments, settings.watch, settings.noResolve, settings.allowAutomaticSemicolonInsertion, settings.noImplicitAny, settings.noLib, settings.codeGenTarget, settings.moduleGenTarget, settings.outFileOption, settings.outDirOption, settings.mapSourceFiles, settings.mapRoot, settings.sourceRoot, settings.generateDeclarationFiles, settings.useCaseSensitiveFileResolution, settings.gatherDiagnostics, settings.codepage); + return new ImmutableCompilationSettings(settings.propagateEnumConstants, settings.removeComments, settings.watch, settings.noResolve, settings.allowAutomaticSemicolonInsertion, settings.noImplicitAny, settings.noLib, settings.codeGenTarget, settings.moduleGenTarget, settings.outFileOption, settings.outDirOption, settings.mapSourceFiles, settings.mapRoot, settings.sourceRoot, settings.generateDeclarationFiles, settings.useCaseSensitiveFileResolution, settings.gatherDiagnostics, settings.codepage, settings.createFileLog); }; ImmutableCompilationSettings.prototype.toCompilationSettings = function () { var result = new CompilationSettings(); + var thisAsIndexable = this; + var resultAsIndexable = result; for (var name in this) { if (this.hasOwnProperty(name) && TypeScript.StringUtilities.startsWith(name, "_")) { - result[name.substr(1)] = this[name]; + resultAsIndexable[name.substr(1)] = thisAsIndexable[name]; } } @@ -34784,7 +34926,7 @@ var TypeScript; PullElementKind[PullElementKind["SomeValue"] = PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.EnumMember | PullElementKind.SomeFunction] = "SomeValue"; - PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter] = "SomeType"; + PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.ObjectLiteral | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter] = "SomeType"; PullElementKind[PullElementKind["AcceptableAlias"] = PullElementKind.Variable | PullElementKind.SomeFunction | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Container | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "AcceptableAlias"; @@ -34800,17 +34942,18 @@ var TypeScript; })(TypeScript || (TypeScript = {})); var TypeScript; (function (TypeScript) { - TypeScript.pullDeclID = 0; + var pullDeclID = 0; var sentinelEmptyPullDeclArray = []; var PullDecl = (function () { - function PullDecl(declName, displayName, kind, declFlags, span) { - this.declID = TypeScript.pullDeclID++; + function PullDecl(declName, displayName, kind, declFlags, semanticInfoChain) { + this.declID = pullDeclID++; this.flags = 0 /* None */; this.declGroups = null; this.childDecls = null; this.typeParameters = null; this.synthesizedValDecl = null; + this.containerDecl = null; this.childDeclTypeCache = null; this.childDeclValueCache = null; this.childDeclNamespaceCache = null; @@ -34818,7 +34961,7 @@ var TypeScript; this.name = declName; this.kind = kind; this.flags = declFlags; - this.span = span; + this.semanticInfoChain = semanticInfoChain; if (displayName !== this.name) { this.declDisplayName = displayName; @@ -34836,10 +34979,6 @@ var TypeScript; throw TypeScript.Errors.abstract(); }; - PullDecl.prototype.semanticInfoChain = function () { - throw TypeScript.Errors.abstract(); - }; - PullDecl.prototype.isExternalModule = function () { throw TypeScript.Errors.abstract(); }; @@ -34872,44 +35011,42 @@ var TypeScript; }; PullDecl.prototype.setSymbol = function (symbol) { - this.semanticInfoChain().setSymbolForDecl(this, symbol); + this.semanticInfoChain.setSymbolForDecl(this, symbol); }; - PullDecl.prototype.ensureSymbolIsBound = function (bindSignatureSymbol) { - if (typeof bindSignatureSymbol === "undefined") { bindSignatureSymbol = false; } - if (!((bindSignatureSymbol && this.hasSignatureSymbol()) || this.hasSymbol()) && this.kind != 1 /* Script */) { - var binder = this.semanticInfoChain().getBinder(); + PullDecl.prototype.ensureSymbolIsBound = function () { + if (!this.hasBeenBound() && this.kind !== 1 /* Script */) { + var binder = this.semanticInfoChain.getBinder(); binder.bindDeclToPullSymbol(this); } }; PullDecl.prototype.getSymbol = function () { - if (this.kind == 1 /* Script */) { + if (this.kind === 1 /* Script */) { return null; } this.ensureSymbolIsBound(); - return this.semanticInfoChain().getSymbolForDecl(this); + return this.semanticInfoChain.getSymbolForDecl(this); }; PullDecl.prototype.hasSymbol = function () { - var symbol = this.semanticInfoChain().getSymbolForDecl(this); + var symbol = this.semanticInfoChain.getSymbolForDecl(this); return !!symbol; }; PullDecl.prototype.setSignatureSymbol = function (signatureSymbol) { - this.semanticInfoChain().setSignatureSymbolForDecl(this, signatureSymbol); + this.semanticInfoChain.setSignatureSymbolForDecl(this, signatureSymbol); }; PullDecl.prototype.getSignatureSymbol = function () { - this.ensureSymbolIsBound(true); - - return this.semanticInfoChain().getSignatureSymbolForDecl(this); + this.ensureSymbolIsBound(); + return this.semanticInfoChain.getSignatureSymbolForDecl(this); }; PullDecl.prototype.hasSignatureSymbol = function () { - var signatureSymbol = this.semanticInfoChain().getSignatureSymbolForDecl(this); + var signatureSymbol = this.semanticInfoChain.getSignatureSymbolForDecl(this); return !!signatureSymbol; }; @@ -34921,20 +35058,17 @@ var TypeScript; this.flags |= flags; }; - PullDecl.prototype.getSpan = function () { - return this.span; - }; - PullDecl.prototype.setValueDecl = function (valDecl) { this.synthesizedValDecl = valDecl; + valDecl.containerDecl = this; }; PullDecl.prototype.getValueDecl = function () { return this.synthesizedValDecl; }; - PullDecl.prototype.isEqual = function (other) { - return (this.name === other.name) && (this.kind === other.kind) && (this.flags === other.flags) && (this.fileName() === other.fileName()) && (this.span.start() === other.span.start()) && (this.span.end() === other.span.end()); + PullDecl.prototype.getContainerDecl = function () { + return this.containerDecl; }; PullDecl.prototype.getChildDeclCache = function (declKind) { @@ -34950,7 +35084,7 @@ var TypeScript; } return this.childDeclNamespaceCache; - } else if (TypeScript.hasFlag(declKind, 58728539 /* SomeType */)) { + } else if (TypeScript.hasFlag(declKind, 58728795 /* SomeType */)) { if (!this.childDeclTypeCache) { this.childDeclTypeCache = TypeScript.createIntrinsicsObject(); } @@ -34995,7 +35129,7 @@ var TypeScript; PullDecl.prototype.searchChildDecls = function (declName, searchKind) { var cacheVal = null; - if (searchKind & 58728539 /* SomeType */) { + if (searchKind & 58728795 /* SomeType */) { cacheVal = this.childDeclTypeCache ? this.childDeclTypeCache[declName] : null; } else if (searchKind & 164 /* SomeContainer */) { cacheVal = this.childDeclNamespaceCache ? this.childDeclNamespaceCache[declName] : null; @@ -35006,7 +35140,7 @@ var TypeScript; if (cacheVal) { return cacheVal; } else { - if (searchKind & 58728539 /* SomeType */) { + if (searchKind & 58728795 /* SomeType */) { cacheVal = this.childDeclTypeParameterCache ? this.childDeclTypeParameterCache[declName] : null; if (cacheVal) { @@ -35019,11 +35153,11 @@ var TypeScript; }; PullDecl.prototype.getChildDecls = function () { - return this.childDecls ? this.childDecls : sentinelEmptyPullDeclArray; + return this.childDecls || sentinelEmptyPullDeclArray; }; PullDecl.prototype.getTypeParameters = function () { - return this.typeParameters ? this.typeParameters : sentinelEmptyPullDeclArray; + return this.typeParameters || sentinelEmptyPullDeclArray; }; PullDecl.prototype.addVariableDeclToGroup = function (decl) { @@ -35056,7 +35190,7 @@ var TypeScript; } } - return declGroups ? declGroups : sentinelEmptyPullDeclArray; + return declGroups || sentinelEmptyPullDeclArray; }; PullDecl.prototype.hasBeenBound = function () { @@ -35068,8 +35202,11 @@ var TypeScript; }; PullDecl.prototype.ast = function () { - var semanticInfoChain = this.semanticInfoChain(); - return semanticInfoChain ? semanticInfoChain.getASTForDecl(this) : null; + return this.semanticInfoChain.getASTForDecl(this); + }; + + PullDecl.prototype.isRootDecl = function () { + throw TypeScript.Errors.abstract(); }; return PullDecl; })(); @@ -35077,9 +35214,9 @@ var TypeScript; var RootPullDecl = (function (_super) { __extends(RootPullDecl, _super); - function RootPullDecl(name, fileName, kind, declFlags, span, semanticInfoChain, isExternalModule) { - _super.call(this, name, name, kind, declFlags, span); - this._semanticInfoChain = semanticInfoChain; + function RootPullDecl(name, fileName, kind, declFlags, semanticInfoChain, isExternalModule) { + _super.call(this, name, name, kind, declFlags, semanticInfoChain); + this.semanticInfoChain = semanticInfoChain; this._isExternalModule = isExternalModule; this._fileName = fileName; } @@ -35095,10 +35232,6 @@ var TypeScript; return null; }; - RootPullDecl.prototype.semanticInfoChain = function () { - return this._semanticInfoChain; - }; - RootPullDecl.prototype.isExternalModule = function () { return this._isExternalModule; }; @@ -35106,15 +35239,18 @@ var TypeScript; RootPullDecl.prototype.getEnclosingDecl = function () { return this; }; + RootPullDecl.prototype.isRootDecl = function () { + return true; + }; return RootPullDecl; })(PullDecl); TypeScript.RootPullDecl = RootPullDecl; var NormalPullDecl = (function (_super) { __extends(NormalPullDecl, _super); - function NormalPullDecl(declName, displayName, kind, declFlags, parentDecl, span, addToParent) { + function NormalPullDecl(declName, displayName, kind, declFlags, parentDecl, addToParent) { if (typeof addToParent === "undefined") { addToParent = true; } - _super.call(this, declName, displayName, kind, declFlags, span); + _super.call(this, declName, displayName, kind, declFlags, parentDecl ? parentDecl.semanticInfoChain : null); this.parentDecl = null; this.parentPath = null; @@ -35122,9 +35258,20 @@ var TypeScript; if (addToParent) { parentDecl.addChildDecl(this); } + + if (this.parentDecl) { + if (this.parentDecl.isRootDecl()) { + this._rootDecl = this.parentDecl; + } else { + this._rootDecl = this.parentDecl._rootDecl; + } + } else { + TypeScript.Debug.assert(this.isSynthesized()); + this._rootDecl = null; + } } NormalPullDecl.prototype.fileName = function () { - return this.parentDecl ? this.parentDecl.fileName() : ""; + return this._rootDecl.fileName(); }; NormalPullDecl.prototype.getParentDecl = function () { @@ -35137,7 +35284,7 @@ var TypeScript; var parentDecl = this.parentDecl; while (parentDecl) { - if (parentDecl && path[path.length - 1] != parentDecl && !(parentDecl.kind & 256 /* ObjectLiteral */)) { + if (parentDecl && path[path.length - 1] !== parentDecl && !(parentDecl.kind & (256 /* ObjectLiteral */ | 8388608 /* ObjectType */))) { path.unshift(parentDecl); } @@ -35150,11 +35297,6 @@ var TypeScript; return this.parentPath; }; - NormalPullDecl.prototype.semanticInfoChain = function () { - var parent = this.getParentDecl(); - return parent ? parent.semanticInfoChain() : null; - }; - NormalPullDecl.prototype.isExternalModule = function () { return false; }; @@ -35162,14 +35304,18 @@ var TypeScript; NormalPullDecl.prototype.getEnclosingDecl = function () { return this.parentDecl && this.parentDecl._getEnclosingDeclFromParentDecl(); }; + + NormalPullDecl.prototype.isRootDecl = function () { + return false; + }; return NormalPullDecl; })(PullDecl); TypeScript.NormalPullDecl = NormalPullDecl; var PullEnumElementDecl = (function (_super) { __extends(PullEnumElementDecl, _super); - function PullEnumElementDecl(declName, displayName, parentDecl, span) { - _super.call(this, declName, displayName, 67108864 /* EnumMember */, 4 /* Public */, parentDecl, span); + function PullEnumElementDecl(declName, displayName, parentDecl) { + _super.call(this, declName, displayName, 67108864 /* EnumMember */, 4 /* Public */, parentDecl); this.constantValue = null; } return PullEnumElementDecl; @@ -35178,9 +35324,9 @@ var TypeScript; var PullFunctionExpressionDecl = (function (_super) { __extends(PullFunctionExpressionDecl, _super); - function PullFunctionExpressionDecl(expressionName, declFlags, parentDecl, span, displayName) { + function PullFunctionExpressionDecl(expressionName, declFlags, parentDecl, displayName) { if (typeof displayName === "undefined") { displayName = ""; } - _super.call(this, "", displayName, 131072 /* FunctionExpression */, declFlags, parentDecl, span); + _super.call(this, "", displayName, 131072 /* FunctionExpression */, declFlags, parentDecl); this.functionExpressionName = expressionName; } PullFunctionExpressionDecl.prototype.getFunctionExpressionName = function () { @@ -35192,17 +35338,17 @@ var TypeScript; var PullSynthesizedDecl = (function (_super) { __extends(PullSynthesizedDecl, _super); - function PullSynthesizedDecl(declName, displayName, kind, declFlags, parentDecl, span, semanticInfoChain) { - _super.call(this, declName, displayName, kind, declFlags, parentDecl, span, false); - this._semanticInfoChain = semanticInfoChain; + function PullSynthesizedDecl(declName, displayName, kind, declFlags, parentDecl, semanticInfoChain) { + _super.call(this, declName, displayName, kind, declFlags, parentDecl, false); + this.semanticInfoChain = semanticInfoChain; } - PullSynthesizedDecl.prototype.semanticInfoChain = function () { - return this._semanticInfoChain; - }; - PullSynthesizedDecl.prototype.isSynthesized = function () { return true; }; + + PullSynthesizedDecl.prototype.fileName = function () { + return this._rootDecl ? this._rootDecl.fileName() : ""; + }; return PullSynthesizedDecl; })(NormalPullDecl); TypeScript.PullSynthesizedDecl = PullSynthesizedDecl; @@ -35228,12 +35374,11 @@ var TypeScript; var TypeScript; (function (TypeScript) { TypeScript.pullSymbolID = 0; - TypeScript.globalTyvarID = 0; TypeScript.sentinelEmptyArray = []; var PullSymbol = (function () { function PullSymbol(name, declKind) { - this.pullSymbolID = TypeScript.pullSymbolID++; + this.pullSymbolID = ++TypeScript.pullSymbolID; this._container = null; this.type = null; this._declarations = null; @@ -35254,7 +35399,7 @@ var TypeScript; }; PullSymbol.prototype.isType = function () { - return (this.kind & 58728539 /* SomeType */) != 0; + return (this.kind & 58728795 /* SomeType */) !== 0; }; PullSymbol.prototype.isTypeReference = function () { @@ -35262,7 +35407,7 @@ var TypeScript; }; PullSymbol.prototype.isSignature = function () { - return (this.kind & 7340032 /* SomeSignature */) != 0; + return (this.kind & 7340032 /* SomeSignature */) !== 0; }; PullSymbol.prototype.isArrayNamedTypeReference = function () { @@ -35323,7 +35468,7 @@ var TypeScript; return aliasSymbols; } - if (!skipScopeSymbolAliasesLookIn && this.isExternalModuleReferenceAlias(symbol) && (!symbol.assignedContainer().hasExportAssignment() || (symbol.assignedContainer().getExportAssignedContainerSymbol() && symbol.assignedContainer().getExportAssignedContainerSymbol().kind == 32 /* DynamicModule */))) { + if (!skipScopeSymbolAliasesLookIn && this.isExternalModuleReferenceAlias(symbol) && (!symbol.assignedContainer().hasExportAssignment() || (symbol.assignedContainer().getExportAssignedContainerSymbol() && symbol.assignedContainer().getExportAssignedContainerSymbol().kind === 32 /* DynamicModule */))) { scopeSymbolAliasesToLookIn.push(symbol); } } @@ -35366,11 +35511,11 @@ var TypeScript; return false; } - if (aliasSymbol.assignedType() && aliasSymbol.assignedType() != aliasSymbol.assignedContainer()) { + if (aliasSymbol.assignedType() && aliasSymbol.assignedType() !== aliasSymbol.assignedContainer()) { return false; } - if (aliasSymbol.assignedContainer() && aliasSymbol.assignedContainer().kind != 32 /* DynamicModule */) { + if (aliasSymbol.assignedContainer() && aliasSymbol.assignedContainer().kind !== 32 /* DynamicModule */) { return false; } @@ -35382,12 +35527,12 @@ var TypeScript; PullSymbol.prototype.getExportedInternalAliasSymbol = function (scopeSymbol) { if (scopeSymbol) { - if (this.kind != 128 /* TypeAlias */) { + if (this.kind !== 128 /* TypeAlias */) { var scopePath = scopeSymbol.pathToRoot(); for (var i = 0; i < scopePath.length; i++) { var internalAliases = this.findAliasedType(scopeSymbol, true, true); if (internalAliases) { - TypeScript.Debug.assert(internalAliases.length == 1); + TypeScript.Debug.assert(internalAliases.length === 1); return internalAliases[0]; } } @@ -35408,11 +35553,14 @@ var TypeScript; var externalAliases = this.getExternalAliasedSymbols(scopeSymbol); if (externalAliases && this.isExternalModuleReferenceAlias(externalAliases[externalAliases.length - 1])) { - var aliasFullName = ""; + var aliasFullName = aliasNameGetter(externalAliases[0]); + if (!aliasFullName) { + return null; + } for (var i = 1, symbolsLen = externalAliases.length; i < symbolsLen; i++) { aliasFullName = aliasFullName + "." + aliasPartsNameGetter(externalAliases[i]); } - return aliasNameGetter(externalAliases[0]) + aliasFullName; + return aliasFullName; } return null; @@ -35420,7 +35568,7 @@ var TypeScript; PullSymbol.prototype._getResolver = function () { TypeScript.Debug.assert(this._declarations && this._declarations.length > 0); - return this._declarations[0].semanticInfoChain().getResolver(); + return this._declarations[0].semanticInfoChain.getResolver(); }; PullSymbol.prototype._resolveDeclaredSymbol = function () { @@ -35433,11 +35581,7 @@ var TypeScript; }, function (symbol) { return symbol.getName(); }); - if (aliasName != null) { - return aliasName; - } - - return this.name; + return aliasName || this.name; }; PullSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { @@ -35446,7 +35590,7 @@ var TypeScript; }, function (symbol) { return symbol.getDisplayName(); }, skipInternalAliasName); - if (aliasDisplayName != null) { + if (aliasDisplayName) { return aliasDisplayName; } @@ -35472,10 +35616,14 @@ var TypeScript; PullSymbol.prototype.setIsSynthesized = function (value) { if (typeof value === "undefined") { value = true; } + TypeScript.Debug.assert(this.rootSymbol == null); this.isSynthesized = value; }; PullSymbol.prototype.getIsSynthesized = function () { + if (this.rootSymbol) { + return this.rootSymbol.getIsSynthesized(); + } return this.isSynthesized; }; @@ -35585,7 +35733,7 @@ var TypeScript; } path[path.length] = node; var nodeKind = node.kind; - if (nodeKind == 2048 /* Parameter */) { + if (nodeKind === 2048 /* Parameter */) { break; } else { node = node.getContainer(); @@ -35594,54 +35742,61 @@ var TypeScript; return path; }; - PullSymbol.prototype.findCommonAncestorPath = function (b) { - var aPath = this.pathToRoot(); - if (aPath.length === 1) { - return aPath; - } + PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope = function (symbol, scopePath, endScopePathIndex) { + var declPath = scopePath[0].getDeclarations()[0].getParentPath(); + for (var i = 0, declIndex = declPath.length - 1; i <= endScopePathIndex; i++, declIndex--) { + if (symbol.isContainer() && scopePath[i].isContainer()) { + var scopeType = scopePath[i]; - var bPath; - if (b) { - bPath = b.pathToRoot(); - } else { - return aPath; - } + var memberSymbol = scopeType.findContainedNonMemberContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } - var commonNodeIndex = -1; - for (var i = 0, aLen = aPath.length; i < aLen; i++) { - var aNode = aPath[i]; - for (var j = 0, bLen = bPath.length; j < bLen; j++) { - var bNode = bPath[j]; - if (aNode === bNode) { - var aDecl = null; - if (i > 0) { - var decls = aPath[i - 1].getDeclarations(); - if (decls.length) { - aDecl = decls[0].getParentDecl(); - } - } - var bDecl = null; - if (j > 0) { - var decls = bPath[j - 1].getDeclarations(); - if (decls.length) { - bDecl = decls[0].getParentDecl(); - } - } - if (!aDecl || !bDecl || aDecl == bDecl) { - commonNodeIndex = i; - break; - } + var memberSymbol = scopeType.findNestedContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol) { + return true; } } - if (commonNodeIndex >= 0) { - break; + } + + return false; + }; + + PullSymbol.prototype.findQualifyingSymbolPathInScopeSymbol = function (scopeSymbol) { + var thisPath = this.pathToRoot(); + if (thisPath.length === 1) { + return thisPath; + } + + var scopeSymbolPath; + if (scopeSymbol) { + scopeSymbolPath = scopeSymbol.pathToRoot(); + } else { + return thisPath; + } + + var thisCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(thisPath, function (thisNode) { + return TypeScript.ArrayUtilities.contains(scopeSymbolPath, thisNode); + }); + if (thisCommonAncestorIndex > 0) { + var thisCommonAncestor = thisPath[thisCommonAncestorIndex]; + var scopeCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(scopeSymbolPath, function (scopeNode) { + return scopeNode === thisCommonAncestor; + }); + TypeScript.Debug.assert(thisPath.length - thisCommonAncestorIndex === scopeSymbolPath.length - scopeCommonAncestorIndex); + + for (; thisCommonAncestorIndex < thisPath.length; thisCommonAncestorIndex++, scopeCommonAncestorIndex++) { + if (!PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope(thisPath[thisCommonAncestorIndex - 1], scopeSymbolPath, scopeCommonAncestorIndex)) { + break; + } } } - if (commonNodeIndex >= 0) { - return aPath.slice(0, commonNodeIndex); + if (thisCommonAncestorIndex >= 0 && thisCommonAncestorIndex < thisPath.length) { + return thisPath.slice(0, thisCommonAncestorIndex); } else { - return aPath; + return thisPath; } }; @@ -35655,6 +35810,7 @@ var TypeScript; }; PullSymbol.prototype.fullName = function (scopeSymbol) { + var _this = this; var path = this.pathToRoot(); var fullName = ""; @@ -35663,23 +35819,23 @@ var TypeScript; }, function (symbol) { return symbol.getNamePartForFullName(); }); - if (aliasFullName != null) { + if (aliasFullName) { return aliasFullName; } for (var i = 1; i < path.length; i++) { var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { - return symbol.fullName(scopeSymbol); + return symbol === _this ? null : symbol.fullName(scopeSymbol); }, function (symbol) { return symbol.getNamePartForFullName(); }); - if (aliasFullName != null) { + if (aliasFullName) { fullName = aliasFullName + "." + fullName; break; } var scopedName = path[i].getNamePartForFullName(); - if (path[i].kind == 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { + if (path[i].kind === 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { break; } @@ -35695,7 +35851,7 @@ var TypeScript; }; PullSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { - var path = this.findCommonAncestorPath(scopeSymbol); + var path = this.findQualifyingSymbolPathInScopeSymbol(scopeSymbol); var fullName = ""; var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { @@ -35703,7 +35859,7 @@ var TypeScript; }, function (symbol) { return symbol.getNamePartForFullName(); }, skipInternalAliasName); - if (aliasFullName != null) { + if (aliasFullName) { return aliasFullName; } @@ -35715,7 +35871,7 @@ var TypeScript; }, function (symbol) { return symbol.getNamePartForFullName(); }, skipInternalAliasName); - if (aliasFullName != null) { + if (aliasFullName) { fullName = aliasFullName + "." + fullName; break; } @@ -35762,9 +35918,9 @@ var TypeScript; PullSymbol.prototype.getTypeNameForFunctionSignature = function (prefix, scopeSymbol, getPrettyTypeName) { var type = this.type; - if (type && !type.isNamedTypeSymbol() && this.kind != 4096 /* Property */ && this.kind != 512 /* Variable */ && this.kind != 2048 /* Parameter */) { + if (type && !type.isNamedTypeSymbol() && this.kind !== 4096 /* Property */ && this.kind !== 512 /* Variable */ && this.kind !== 2048 /* Parameter */) { var signatures = type.getCallSignatures(); - if (signatures.length == 1 || (getPrettyTypeName && signatures.length)) { + if (signatures.length === 1 || (getPrettyTypeName && signatures.length)) { var typeName = new TypeScript.MemberNameArray(); var signatureName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, prefix, false, false, scopeSymbol, getPrettyTypeName); typeName.addAll(signatureName); @@ -35881,7 +36037,7 @@ var TypeScript; var parentDecl = decls[0].getParentDecl(); if (parentDecl) { var parentSymbol = parentDecl.getSymbol(); - if (!parentSymbol || parentDecl.kind == 1 /* Script */) { + if (!parentSymbol || parentDecl.kind === 1 /* Script */) { return true; } @@ -35892,14 +36048,14 @@ var TypeScript; return true; } - if (container.kind == 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().kind == 32 /* DynamicModule */)) { - var containerSymbol = container.kind == 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); + if (container.kind === 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().kind === 32 /* DynamicModule */)) { + var containerSymbol = container.kind === 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); if (PullContainerSymbol.usedAsSymbol(containerSymbol, this)) { return true; } } - if (!this.anyDeclHasFlag(1 /* Exported */) && kind != 4096 /* Property */ && kind != 65536 /* Method */) { + if (!this.anyDeclHasFlag(1 /* Exported */) && kind !== 4096 /* Property */ && kind !== 65536 /* Method */) { return false; } @@ -35910,13 +36066,13 @@ var TypeScript; var ast = decl.ast(); if (ast) { - var enclosingModuleDeclaration = TypeScript.getEnclosingModuleDeclaration(ast); - if (TypeScript.isLastNameOfModule(enclosingModuleDeclaration, ast)) { - return TypeScript.docComments(enclosingModuleDeclaration); + var enclosingModuleDeclaration = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(ast); + if (TypeScript.ASTHelpers.isLastNameOfModule(enclosingModuleDeclaration, ast)) { + return TypeScript.ASTHelpers.docComments(enclosingModuleDeclaration); } - if (ast.kind() != 130 /* ModuleDeclaration */ || decl.kind != 512 /* Variable */) { - return TypeScript.docComments(ast); + if (ast.kind() !== 130 /* ModuleDeclaration */ || decl.kind !== 512 /* Variable */) { + return TypeScript.ASTHelpers.docComments(ast); } } @@ -35929,10 +36085,10 @@ var TypeScript; return docComments; } - var isParameter = symbol.kind == 2048 /* Parameter */; + var isParameter = symbol.kind === 2048 /* Parameter */; var decls = symbol.getDeclarations(); for (var i = 0; i < decls.length; i++) { - if (isParameter && decls[i].kind == 4096 /* Property */) { + if (isParameter && decls[i].kind === 4096 /* Property */) { continue; } docComments = docComments.concat(this.getDocCommentsOfDecl(decls[i])); @@ -35968,14 +36124,14 @@ var TypeScript; PullSymbol.prototype.docComments = function (useConstructorAsClass) { var decls = this.getDeclarations(); - if (useConstructorAsClass && decls.length && decls[0].kind == 32768 /* ConstructorMethod */) { + if (useConstructorAsClass && decls.length && decls[0].kind === 32768 /* ConstructorMethod */) { var classDecl = decls[0].getParentDecl(); return this.getDocCommentText(this.getDocCommentsOfDecl(classDecl)); } if (this._docComments === null) { var docComments = ""; - if (!useConstructorAsClass && this.kind == 2097152 /* ConstructSignature */ && decls.length && decls[0].kind == 8 /* Class */) { + if (!useConstructorAsClass && this.kind === 2097152 /* ConstructSignature */ && decls.length && decls[0].kind === 8 /* Class */) { var classSymbol = this.returnType; var extendedTypes = classSymbol.getExtendedTypes(); if (extendedTypes.length) { @@ -35983,7 +36139,7 @@ var TypeScript; } else { docComments = ""; } - } else if (this.kind == 2048 /* Parameter */) { + } else if (this.kind === 2048 /* Parameter */) { var parameterComments = []; var funcContainer = this.getEnclosingSignature(); @@ -36000,7 +36156,7 @@ var TypeScript; docComments = parameterComments.join("\n"); } else { var getSymbolComments = true; - if (this.kind == 16777216 /* FunctionType */) { + if (this.kind === 16777216 /* FunctionType */) { var functionSymbol = this.getFunctionSymbol(); if (functionSymbol) { @@ -36016,10 +36172,10 @@ var TypeScript; } if (getSymbolComments) { docComments = this.getDocCommentText(this.getDocCommentArray(this)); - if (docComments == "") { - if (this.kind == 1048576 /* CallSignature */) { + if (docComments === "") { + if (this.kind === 1048576 /* CallSignature */) { var callTypeSymbol = this.functionType; - if (callTypeSymbol && callTypeSymbol.getCallSignatures().length == 1) { + if (callTypeSymbol && callTypeSymbol.getCallSignatures().length === 1) { docComments = callTypeSymbol.docComments(); } } @@ -36230,34 +36386,41 @@ var TypeScript; })(); TypeScript.PullSymbol = PullSymbol; + + var PullSignatureSymbol = (function (_super) { __extends(PullSignatureSymbol, _super); - function PullSignatureSymbol(kind) { + function PullSignatureSymbol(kind, _isDefinition) { + if (typeof _isDefinition === "undefined") { _isDefinition = false; } _super.call(this, "", kind); + this._isDefinition = _isDefinition; this._memberTypeParameterNameCache = null; this._stringConstantOverload = undefined; this.parameters = TypeScript.sentinelEmptyArray; - this.typeParameters = null; + this._typeParameters = null; this.returnType = null; this.functionType = null; this.hasOptionalParam = false; this.nonOptionalParamCount = 0; this.hasVarArgs = false; - this.hasAGenericParameter = false; + this._allowedToReferenceTypeParameters = null; + this._instantiationCache = null; this.hasBeenChecked = false; this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; } PullSignatureSymbol.prototype.isDefinition = function () { - return false; + return this._isDefinition; }; PullSignatureSymbol.prototype.isGeneric = function () { - return this.hasAGenericParameter || (this.typeParameters && this.typeParameters.length != 0); + var typeParameters = this.getTypeParameters(); + return !!typeParameters && typeParameters.length !== 0; }; PullSignatureSymbol.prototype.addParameter = function (parameter, isOptional) { if (typeof isOptional === "undefined") { isOptional = false; } - if (this.parameters == TypeScript.sentinelEmptyArray) { + if (this.parameters === TypeScript.sentinelEmptyArray) { this.parameters = []; } @@ -36274,25 +36437,32 @@ var TypeScript; }; PullSignatureSymbol.prototype.addTypeParameter = function (typeParameter) { - if (!this.typeParameters) { - this.typeParameters = []; + if (!this._typeParameters) { + this._typeParameters = []; } if (!this._memberTypeParameterNameCache) { this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); } - this.typeParameters[this.typeParameters.length] = typeParameter; + this._typeParameters[this._typeParameters.length] = typeParameter; this._memberTypeParameterNameCache[typeParameter.getName()] = typeParameter; }; + PullSignatureSymbol.prototype.addTypeParametersFromReturnType = function () { + var typeParameters = this.returnType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addTypeParameter(typeParameters[i]); + } + }; + PullSignatureSymbol.prototype.getTypeParameters = function () { - if (!this.typeParameters) { - this.typeParameters = []; + if (!this._typeParameters) { + this._typeParameters = []; } - return this.typeParameters; + return this._typeParameters; }; PullSignatureSymbol.prototype.findTypeParameter = function (name) { @@ -36301,10 +36471,8 @@ var TypeScript; if (!this._memberTypeParameterNameCache) { this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); - if (this.typeParameters) { - for (var i = 0; i < this.typeParameters.length; i++) { - this._memberTypeParameterNameCache[this.typeParameters[i].getName()] = this.typeParameters[i]; - } + for (var i = 0; i < this.getTypeParameters().length; i++) { + this._memberTypeParameterNameCache[this._typeParameters[i].getName()] = this._typeParameters[i]; } } @@ -36313,6 +36481,38 @@ var TypeScript; return memberSymbol; }; + PullSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullSignatureSymbol.prototype.addSpecialization = function (specializedVersionOfThisSignature, typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + this._instantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisSignature; + }; + + PullSignatureSymbol.prototype.getSpecialization = function (typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + return null; + } + + var result = this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + }; + PullSignatureSymbol.prototype.isStringConstantOverloadSignature = function () { if (this._stringConstantOverload === undefined) { var params = this.parameters; @@ -36328,6 +36528,20 @@ var TypeScript; return this._stringConstantOverload; }; + PullSignatureSymbol.prototype.getParameterTypeAtIndex = function (iParam) { + if (iParam < this.parameters.length - 1 || (iParam < this.parameters.length && !this.hasVarArgs)) { + return this.parameters[iParam].type; + } else if (this.hasVarArgs) { + var paramType = this.parameters[this.parameters.length - 1].type; + if (paramType.isArrayNamedTypeReference()) { + paramType = paramType.getElementType(); + } + return paramType; + } + + return null; + }; + PullSignatureSymbol.getSignatureTypeMemberName = function (candidateSignature, signatures, scopeSymbol) { var allMemberNames = new TypeScript.MemberNameArray(); var signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, "", false, false, scopeSymbol, true, candidateSignature); @@ -36455,75 +36669,110 @@ var TypeScript; return builder; }; + PullSignatureSymbol.prototype.forAllParameterTypes = function (length, predicate) { + if (this.parameters.length < length && !this.hasVarArgs) { + length = this.parameters.length; + } + + for (var i = 0; i < length; i++) { + var paramType = this.getParameterTypeAtIndex(i); + if (!predicate(paramType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.forAllCorrespondingParameterTypesInThisAndOtherSignature = function (otherSignature, predicate) { + var length; + if (this.hasVarArgs) { + length = otherSignature.hasVarArgs ? Math.max(this.parameters.length, otherSignature.parameters.length) : otherSignature.parameters.length; + } else { + length = otherSignature.hasVarArgs ? this.parameters.length : Math.min(this.parameters.length, otherSignature.parameters.length); + } + + for (var i = 0; i < length; i++) { + var thisParamType = this.getParameterTypeAtIndex(i); + var otherParamType = otherSignature.getParameterTypeAtIndex(i); + if (!predicate(thisParamType, otherParamType, i)) { + return false; + } + } + + return true; + }; + PullSignatureSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap) !== 0; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap) { var signature = this; if (signature.inWrapCheck) { - return false; + return 0; } + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap); + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap) { + var signature = this; signature.inWrapCheck = true; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(signature); + var wrappingTypeParameterID = signature.returnType ? signature.returnType.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; - var wrapsSomeTypeParameter = false; - - if (signature.returnType && signature.returnType.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - } - - if (!wrapsSomeTypeParameter) { - var parameters = signature.parameters; - - for (var i = 0; i < parameters.length; i++) { - if (!parameters[i].type) { - parameters[i]._resolveDeclaredSymbol(); - } - - if (parameters[i].type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } + var parameters = signature.parameters; + for (var i = 0; !wrappingTypeParameterID && i < parameters.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(parameters[i]); + wrappingTypeParameterID = parameters[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); } signature.inWrapCheck = false; - return wrapsSomeTypeParameter; + return wrappingTypeParameterID; }; - PullSignatureSymbol.prototype.wrapsSomeNestedTypeIntoInfiniteExpansion = function (typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap) { - if (this.inWrapCheck) { - return isCheckingTypeArgumentList; + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; } - if (knownWrapMap.valueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID) != undefined) { - return knownWrapMap.valueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID); + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; } - knownWrapMap.setValueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID, isCheckingTypeArgumentList); + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; - this.inWrapCheck = true; + return wrapsIntoInfinitelyExpandingTypeReference; + }; - var wrapsSomeWrappedTypeParameter = false; - - if (this.returnType && this.returnType._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - wrapsSomeWrappedTypeParameter = true; + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + if (this.returnType && this.returnType._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; } - if (!wrapsSomeWrappedTypeParameter) { - var parameters = this.parameters; + var parameters = this.parameters; - for (var i = 0; i < parameters.length; i++) { - if (parameters[i].type && parameters[i].type._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - wrapsSomeWrappedTypeParameter = true; - break; - } + for (var i = 0; i < parameters.length; i++) { + if (parameters[i].type && parameters[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; } } - knownWrapMap.setValueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID, wrapsSomeWrappedTypeParameter); - - this.inWrapCheck = false; - - return wrapsSomeWrappedTypeParameter; + return false; }; return PullSignatureSymbol; })(PullSymbol); @@ -36537,6 +36786,7 @@ var TypeScript; this._enclosedMemberTypes = null; this._enclosedMemberContainers = null; this._typeParameters = null; + this._allowedToReferenceTypeParameters = null; this._specializedVersionsOfThisType = null; this._arrayVersionOfThisType = null; this._implementedTypes = null; @@ -36548,6 +36798,7 @@ var TypeScript; this._constructSignatures = null; this._indexSignatures = null; this._allIndexSignatures = null; + this._allIndexSignaturesOfAugmentedType = null; this._memberNameCache = null; this._enclosedTypeNameCache = null; this._enclosedContainerCache = null; @@ -36568,7 +36819,9 @@ var TypeScript; this._inMemberTypeNameEx = false; this.inSymbolPrivacyCheck = false; this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; this.typeReference = null; + this._widenedType = null; this._isArrayNamedTypeReference = undefined; this.type = this; } @@ -36583,7 +36836,6 @@ var TypeScript; PullTypeSymbol.prototype.computeIsArrayNamedTypeReference = function () { var typeArgs = this.getTypeArguments(); if (typeArgs && this.getTypeArguments().length === 1 && this.name === "Array") { - var container = this.getContainer(); var declaration = this.getDeclarations()[0]; if (declaration && declaration.getParentDecl() && declaration.getParentDecl().getParentDecl() === null) { @@ -36598,13 +36850,13 @@ var TypeScript; return true; }; PullTypeSymbol.prototype.isClass = function () { - return this.kind == 8 /* Class */ || (this._constructorMethod != null); + return this.kind === 8 /* Class */ || (this._constructorMethod !== null); }; PullTypeSymbol.prototype.isFunction = function () { - return (this.kind & (33554432 /* ConstructorType */ | 16777216 /* FunctionType */)) != 0; + return (this.kind & (33554432 /* ConstructorType */ | 16777216 /* FunctionType */)) !== 0; }; PullTypeSymbol.prototype.isConstructor = function () { - return this.kind == 33554432 /* ConstructorType */; + return this.kind === 33554432 /* ConstructorType */; }; PullTypeSymbol.prototype.isTypeParameter = function () { return false; @@ -36616,7 +36868,7 @@ var TypeScript; return false; }; PullTypeSymbol.prototype.isEnum = function () { - return this.kind == 64 /* Enum */; + return this.kind === 64 /* Enum */; }; PullTypeSymbol.prototype.getTypeParameterArgumentMap = function () { @@ -36624,7 +36876,11 @@ var TypeScript; }; PullTypeSymbol.prototype.isObject = function () { - return TypeScript.hasFlag(this.kind, 8 /* Class */ | 33554432 /* ConstructorType */ | 64 /* Enum */ | 16777216 /* FunctionType */ | 16 /* Interface */ | 8388608 /* ObjectType */); + return TypeScript.hasFlag(this.kind, 8 /* Class */ | 33554432 /* ConstructorType */ | 64 /* Enum */ | 16777216 /* FunctionType */ | 16 /* Interface */ | 8388608 /* ObjectType */ | 256 /* ObjectLiteral */); + }; + + PullTypeSymbol.prototype.isFunctionType = function () { + return this.getCallSignatures().length > 0 || this.getConstructSignatures().length > 0; }; PullTypeSymbol.prototype.getKnownBaseTypeCount = function () { @@ -36645,7 +36901,7 @@ var TypeScript; }; PullTypeSymbol.prototype.hasMembers = function () { - if (this._members != TypeScript.sentinelEmptyArray) { + if (this._members !== TypeScript.sentinelEmptyArray) { return true; } @@ -36720,8 +36976,8 @@ var TypeScript; var nonMemberSymbol = this._containedNonMemberTypeNameCache[typeName]; - if (nonMemberSymbol && kind != 0 /* None */) { - nonMemberSymbol = ((nonMemberSymbol.kind & kind) != 0) ? nonMemberSymbol : null; + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; } return nonMemberSymbol; @@ -36735,8 +36991,8 @@ var TypeScript; var nonMemberSymbol = this._containedNonMemberContainerCache[containerName]; - if (nonMemberSymbol && kind != 0 /* None */) { - nonMemberSymbol = ((nonMemberSymbol.kind & kind) != 0) ? nonMemberSymbol : null; + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; } return nonMemberSymbol; @@ -36862,16 +37118,6 @@ var TypeScript; this._typeParameterNameCache[typeParameter.getName()] = typeParameter; }; - PullTypeSymbol.prototype.addConstructorTypeParameter = function (typeParameter) { - this.addTypeParameter(typeParameter); - - var constructSignatures = this.getConstructSignatures(); - - for (var i = 0; i < constructSignatures.length; i++) { - constructSignatures[i].addTypeParameter(typeParameter); - } - }; - PullTypeSymbol.prototype.getMembers = function () { return this._members; }; @@ -36901,31 +37147,52 @@ var TypeScript; return this._typeParameters; }; + PullTypeSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + if (!!(this.kind && 8216 /* SomeInstantiatableType */) && this.isNamedTypeSymbol() && !this.isTypeParameter()) { + return this.getTypeParameters(); + } + + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + PullTypeSymbol.prototype.isGeneric = function () { return (this._typeParameters && this._typeParameters.length > 0) || this._hasGenericSignature || this._hasGenericMember || this.isArrayNamedTypeReference(); }; - PullTypeSymbol.prototype.canUseSimpleInstantiationCache = function (substitutingTypes) { - return substitutingTypes.length === 1 && substitutingTypes[0].kind !== 8388608 /* ObjectType */; - }; - - PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, substitutingTypes) { - if (!substitutingTypes || !substitutingTypes.length) { - return; + PullTypeSymbol.prototype.canUseSimpleInstantiationCache = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return true; } - if (this.canUseSimpleInstantiationCache(substitutingTypes)) { + var typeParameters = this.getTypeParameters(); + return typeArgumentMap && this.isNamedTypeSymbol() && typeParameters.length === 1 && typeArgumentMap[typeParameters[0].pullSymbolID].kind !== 8388608 /* ObjectType */; + }; + + PullTypeSymbol.prototype.getSimpleInstantiationCacheId = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return typeArgumentMap[0].pullSymbolID; + } + + return typeArgumentMap[this.getTypeParameters()[0].pullSymbolID].pullSymbolID; + }; + + PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { if (!this._simpleInstantiationCache) { this._simpleInstantiationCache = []; } - this._simpleInstantiationCache[substitutingTypes[0].pullSymbolID] = specializedVersionOfThisType; + this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)] = specializedVersionOfThisType; } else { if (!this._complexInstantiationCache) { this._complexInstantiationCache = TypeScript.createIntrinsicsObject(); } - this._complexInstantiationCache[getIDForTypeSubstitutions(substitutingTypes)] = specializedVersionOfThisType; + this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisType; } if (!this._specializedVersionsOfThisType) { @@ -36935,25 +37202,25 @@ var TypeScript; this._specializedVersionsOfThisType.push(specializedVersionOfThisType); }; - PullTypeSymbol.prototype.getSpecialization = function (substitutingTypes) { - if (!substitutingTypes || !substitutingTypes.length) { - return null; - } - - if (this.canUseSimpleInstantiationCache(substitutingTypes)) { + PullTypeSymbol.prototype.getSpecialization = function (typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { if (!this._simpleInstantiationCache) { return null; } - var result = this._simpleInstantiationCache[substitutingTypes[0].pullSymbolID]; - return result ? result : null; + var result = this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)]; + return result || null; } else { if (!this._complexInstantiationCache) { return null; } - var result = this._complexInstantiationCache[getIDForTypeSubstitutions(substitutingTypes)]; - return result ? result : null; + if (this.getAllowedToReferenceTypeParameters().length == 0) { + return this; + } + + var result = this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; } }; @@ -36973,13 +37240,11 @@ var TypeScript; return this.getTypeParameters(); }; - PullTypeSymbol.prototype.addCallSignature = function (callSignature) { + PullTypeSymbol.prototype.addCallSignaturePrerequisite = function (callSignature) { if (!this._callSignatures) { this._callSignatures = []; } - this._callSignatures[this._callSignatures.length] = callSignature; - if (callSignature.isGeneric()) { this._hasGenericSignature = true; } @@ -36987,13 +37252,26 @@ var TypeScript; callSignature.functionType = this; }; - PullTypeSymbol.prototype.addConstructSignature = function (constructSignature) { + PullTypeSymbol.prototype.appendCallSignature = function (callSignature) { + this.addCallSignaturePrerequisite(callSignature); + this._callSignatures.push(callSignature); + }; + + PullTypeSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + this.addCallSignaturePrerequisite(callSignature); + TypeScript.Debug.assert(index <= this._callSignatures.length); + if (index === this._callSignatures.length) { + this._callSignatures.push(callSignature); + } else { + this._callSignatures.splice(index, 0, callSignature); + } + }; + + PullTypeSymbol.prototype.addConstructSignaturePrerequisite = function (constructSignature) { if (!this._constructSignatures) { this._constructSignatures = []; } - this._constructSignatures[this._constructSignatures.length] = constructSignature; - if (constructSignature.isGeneric()) { this._hasGenericSignature = true; } @@ -37001,6 +37279,21 @@ var TypeScript; constructSignature.functionType = this; }; + PullTypeSymbol.prototype.appendConstructSignature = function (constructSignature) { + this.addConstructSignaturePrerequisite(constructSignature); + this._constructSignatures.push(constructSignature); + }; + + PullTypeSymbol.prototype.insertConstructSignatureAtIndex = function (constructSignature, index) { + this.addConstructSignaturePrerequisite(constructSignature); + TypeScript.Debug.assert(index <= this._constructSignatures.length); + if (index === this._constructSignatures.length) { + this._constructSignatures.push(constructSignature); + } else { + this._constructSignatures.splice(index, 0, constructSignature); + } + }; + PullTypeSymbol.prototype.addIndexSignature = function (indexSignature) { if (!this._indexSignatures) { this._indexSignatures = []; @@ -37015,30 +37308,14 @@ var TypeScript; indexSignature.functionType = this; }; - PullTypeSymbol.prototype.addUnhiddenSignaturesFromBaseType = function (derivedTypeSignatures, baseTypeSignatures, signaturesBeingAggregated) { - if (!derivedTypeSignatures) { - signaturesBeingAggregated.push.apply(signaturesBeingAggregated, baseTypeSignatures); - return; - } - - var resolver = this._getResolver(); - for (var i = 0; i < baseTypeSignatures.length; i++) { - var baseSignature = baseTypeSignatures[i]; - - var signatureIsHidden = TypeScript.ArrayUtilities.any(derivedTypeSignatures, function (sig) { - return resolver.signaturesAreIdentical(baseSignature, sig, false); - }); - - if (!signatureIsHidden) { - signaturesBeingAggregated.push(baseSignature); - } - } - }; - PullTypeSymbol.prototype.hasOwnCallSignatures = function () { return this._callSignatures !== null; }; + PullTypeSymbol.prototype.getOwnCallSignatures = function () { + return this._callSignatures || TypeScript.sentinelEmptyArray; + }; + PullTypeSymbol.prototype.getCallSignatures = function () { if (this._allCallSignatures) { return this._allCallSignatures; @@ -37056,7 +37333,7 @@ var TypeScript; continue; } - this.addUnhiddenSignaturesFromBaseType(this._callSignatures, this._extendedTypes[i].getCallSignatures(), signatures); + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._callSignatures, this._extendedTypes[i].getCallSignatures(), signatures); } } @@ -37069,6 +37346,10 @@ var TypeScript; return this._constructSignatures !== null; }; + PullTypeSymbol.prototype.getOwnConstructSignatures = function () { + return this._constructSignatures || TypeScript.sentinelEmptyArray; + }; + PullTypeSymbol.prototype.getConstructSignatures = function () { var signatures = []; @@ -37082,7 +37363,7 @@ var TypeScript; continue; } - this.addUnhiddenSignaturesFromBaseType(this._constructSignatures, this._extendedTypes[i].getConstructSignatures(), signatures); + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._constructSignatures, this._extendedTypes[i].getConstructSignatures(), signatures); } } @@ -37114,7 +37395,7 @@ var TypeScript; continue; } - this.addUnhiddenSignaturesFromBaseType(this._indexSignatures, this._extendedTypes[i].getIndexSignatures(), signatures); + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._indexSignatures, this._extendedTypes[i].getIndexSignatures(), signatures); } } @@ -37123,6 +37404,45 @@ var TypeScript; return signatures; }; + PullTypeSymbol.prototype.getIndexSignaturesOfAugmentedType = function (resolver, globalFunctionInterface, globalObjectInterface) { + if (!this._allIndexSignaturesOfAugmentedType) { + var initialIndexSignatures = this.getIndexSignatures(); + var shouldAddFunctionSignatures = false; + var shouldAddObjectSignatures = false; + + if (globalFunctionInterface && this.isFunctionType() && this !== globalFunctionInterface) { + var functionIndexSignatures = globalFunctionInterface.getIndexSignatures(); + if (functionIndexSignatures.length) { + shouldAddFunctionSignatures = true; + } + } + + if (globalObjectInterface && this !== globalObjectInterface) { + var objectIndexSignatures = globalObjectInterface.getIndexSignatures(); + if (objectIndexSignatures.length) { + shouldAddObjectSignatures = true; + } + } + + if (shouldAddFunctionSignatures || shouldAddObjectSignatures) { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures.slice(0); + if (shouldAddFunctionSignatures) { + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, functionIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + if (shouldAddObjectSignatures) { + if (shouldAddFunctionSignatures) { + initialIndexSignatures = initialIndexSignatures.concat(functionIndexSignatures); + } + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, objectIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + } else { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures; + } + } + + return this._allIndexSignaturesOfAugmentedType; + }; + PullTypeSymbol.prototype.addImplementedType = function (implementedType) { if (!implementedType) { return; @@ -37293,8 +37613,8 @@ var TypeScript; memberSymbol = this._enclosedTypeNameCache[name]; - if (memberSymbol && kind != 0 /* None */) { - memberSymbol = ((memberSymbol.kind & kind) != 0) ? memberSymbol : null; + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; } return memberSymbol; @@ -37310,8 +37630,8 @@ var TypeScript; memberSymbol = this._enclosedContainerCache[name]; - if (memberSymbol && kind != 0 /* None */) { - memberSymbol = ((memberSymbol.kind & kind) != 0) ? memberSymbol : null; + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; } return memberSymbol; @@ -37320,7 +37640,7 @@ var TypeScript; PullTypeSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { var allMembers = []; - if (this._members != TypeScript.sentinelEmptyArray) { + if (this._members !== TypeScript.sentinelEmptyArray) { for (var i = 0, n = this._members.length; i < n; i++) { var member = this._members[i]; if ((member.kind & searchDeclKind) && (memberVisiblity !== 2 /* externallyVisible */ || !member.anyDeclHasFlag(2 /* Private */))) { @@ -37386,7 +37706,7 @@ var TypeScript; PullTypeSymbol.prototype.isNamedTypeSymbol = function () { var kind = this.kind; - if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 128 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.name != "")) { + if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 128 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.name !== "")) { return true; } @@ -37398,8 +37718,9 @@ var TypeScript; return s; }; - PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) { - if (this.isArrayNamedTypeReference()) { + PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName, shouldAllowArrayType) { + if (typeof shouldAllowArrayType === "undefined") { shouldAllowArrayType = true; } + if (this.isArrayNamedTypeReference() && shouldAllowArrayType) { var elementType = this.getElementType(); var elementMemberName = elementType ? (elementType.isArrayNamedTypeReference() || elementType.isNamedTypeSymbol() ? elementType.getScopedNameEx(scopeSymbol, false, false, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) : elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName)) : TypeScript.MemberName.create("any"); return TypeScript.MemberName.create(elementMemberName, "", "[]"); @@ -37436,8 +37757,8 @@ var TypeScript; } var functionSymbol = this.getFunctionSymbol(); - if (functionSymbol && functionSymbol.kind == 16384 /* Function */ && !TypeScript.PullHelpers.isSymbolLocal(functionSymbol)) { - return functionSymbol; + if (functionSymbol && functionSymbol.kind === 16384 /* Function */ && !TypeScript.PullHelpers.isSymbolLocal(functionSymbol)) { + return TypeScript.PullHelpers.isExportedSymbolInClodule(functionSymbol) ? null : functionSymbol; } return null; @@ -37463,10 +37784,10 @@ var TypeScript; this._inMemberTypeNameEx = true; var allMemberNames = new TypeScript.MemberNameArray(); - var curlies = !topLevel || indexSignatures.length != 0; + var curlies = !topLevel || indexSignatures.length !== 0; var delim = "; "; for (var i = 0; i < members.length; i++) { - if (members[i].kind == 65536 /* Method */ && members[i].type.hasOnlyOverloadCallSignatures()) { + if (members[i].kind === 65536 /* Method */ && members[i].type.hasOnlyOverloadCallSignatures()) { var methodCallSignatures = members[i].type.getCallSignatures(); var nameStr = members[i].getDisplayName(scopeSymbol) + (members[i].isOptional ? "?" : ""); ; @@ -37524,32 +37845,55 @@ var TypeScript; return 2 /* Closed */; }; - PullTypeSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap) { + PullTypeSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap, skipTypeArgumentCheck) != 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap, skipTypeArgumentCheck) { var type = this; - var wrapsSomeTypeParameter = false; - if (type.isTypeParameter()) { - if (typeParameterArgumentMap[type.pullSymbolID]) { - return true; + if (typeParameterArgumentMap[type.pullSymbolID] || typeParameterArgumentMap[type.getRootSymbol().pullSymbolID]) { + return type.pullSymbolID; } var constraint = type.getConstraint(); - - if (constraint && constraint.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - return true; - } - - return false; + var wrappingTypeParameterID = constraint ? constraint.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + return wrappingTypeParameterID; } if (type.inWrapCheck) { - return wrapsSomeTypeParameter; + return 0; } - type.inWrapCheck = true; + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap, skipTypeArgumentCheck); + + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDFromSignatures = function (signatures, typeParameterArgumentMap) { + for (var i = 0; i < signatures.length; i++) { + var wrappingTypeParameterID = signatures[i].getWrappingTypeParameterID(typeParameterArgumentMap); + if (wrappingTypeParameterID !== 0) { + return wrappingTypeParameterID; + } + } + + return 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + var wrappingTypeParameterID = 0; + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = true; - if (!wrapsSomeTypeParameter) { var typeArguments = type.getTypeArguments(); if (type.isGeneric() && !typeArguments) { @@ -37557,217 +37901,131 @@ var TypeScript; } if (typeArguments) { - for (var i = 0; i < typeArguments.length; i++) { - if (typeArguments[i].wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } + for (var i = 0; !wrappingTypeParameterID && i < typeArguments.length; i++) { + wrappingTypeParameterID = typeArguments[i].getWrappingTypeParameterID(typeParameterArgumentMap); } } } - if (!(type.kind & 8216 /* SomeInstantiatableType */) || !type.name) { - if (!wrapsSomeTypeParameter) { - var members = type.getAllMembers(68147712 /* SomeValue */, 0 /* all */); - - for (var i = 0; i < members.length; i++) { - if (members[i].type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } + if (skipTypeArgumentCheck || !(type.kind & 8216 /* SomeInstantiatableType */) || !type.name) { + var members = type.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; !wrappingTypeParameterID && i < members.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(members[i]); + wrappingTypeParameterID = members[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); } - if (!wrapsSomeTypeParameter) { - var sigs = type.getCallSignatures(); - - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } - } - - if (!wrapsSomeTypeParameter) { - sigs = type.getConstructSignatures(); - - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } - } - - if (!wrapsSomeTypeParameter) { - sigs = type.getIndexSignatures(); - - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } - } + wrappingTypeParameterID = wrappingTypeParameterID || this.getWrappingTypeParameterIDFromSignatures(type.getCallSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getConstructSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getIndexSignatures(), typeParameterArgumentMap); } - type.inWrapCheck = false; + if (!skipTypeArgumentCheck) { + type.inWrapCheck = false; + } - return wrapsSomeTypeParameter; + return wrappingTypeParameterID; }; - PullTypeSymbol.prototype.wrapsSomeNestedTypeIntoInfiniteExpansion = function (typeBeingWrapped) { - if (!this.isArrayNamedTypeReference() && this.isNamedTypeSymbol()) { - var knownWrapMap = TypeScript.BitMatrix.getBitMatrix(true); - var result = this._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, false, knownWrapMap); - knownWrapMap.release(); - - return result; - } - - return false; + PullTypeSymbol.prototype.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType) { + TypeScript.Debug.assert(this.isNamedTypeSymbol()); + TypeScript.Debug.assert(TypeScript.PullHelpers.getRootType(enclosingType) == enclosingType); + var knownWrapMap = TypeScript.BitMatrix.getBitMatrix(true); + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap); + knownWrapMap.release(); + return wrapsIntoInfinitelyExpandingTypeReference; }; - PullTypeSymbol.prototype.isTypeEquivalentToRootSymbol = function () { - if (this.isTypeReference()) { - if (this.getIsSpecialized()) { - var typeArguments = this.getTypeArguments(); - var rootTypeArguments = this.getRootSymbol().getTypeArguments(); - if (typeArguments) { - for (var i = 0; i < typeArguments.length; i++) { - if (!typeArguments[i].isTypeParameter() && !(rootTypeArguments && rootTypeArguments[i] == typeArguments[i].getRootSymbol())) { - return false; - } - } - return true; - } - - return false; - } else { - return true; - } + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; } - return false; - }; - - PullTypeSymbol.prototype.isTypeBeingWrapped = function (typeBeingWrapped) { - if (this.inWrapCheck || this == typeBeingWrapped) { - return true; - } - - if (typeBeingWrapped.isTypeEquivalentToRootSymbol()) { - return this.isTypeBeingWrapped(typeBeingWrapped.getRootSymbol()); - } - - return false; - }; - - PullTypeSymbol.prototype.anyRootTypeBeingWrapped = function (typeBeingWrapped) { - var prevRootType = this; - var rootType = this.getRootSymbol(); - while (rootType != prevRootType) { - if (rootType.isTypeBeingWrapped(typeBeingWrapped)) { - return true; - } - - prevRootType = rootType; - rootType = rootType.getRootSymbol(); - } - - return false; - }; - - PullTypeSymbol.prototype._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse = function (typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap) { - if (this.isArrayNamedTypeReference()) { - return this.getElementType()._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap); - } - - if (this.isTypeBeingWrapped(typeBeingWrapped)) { - return isCheckingTypeArgumentList; - } - - if (knownWrapMap.valueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID) != undefined) { - return knownWrapMap.valueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID); - } - - if (this.isPrimitive() || this.isTypeParameter()) { + if (this.inWrapInfiniteExpandingReferenceCheck) { return false; } - this.inWrapCheck = true; + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; - var wrapsSomeWrappedTypeParameter = false; - - knownWrapMap.setValueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID, false); - - wrapsSomeWrappedTypeParameter = this._wrapsSomeNestedTypeIntoInfiniteExpansionWorker(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap); - - knownWrapMap.setValueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID, wrapsSomeWrappedTypeParameter); - - this.inWrapCheck = false; - - return wrapsSomeWrappedTypeParameter; + return wrapsIntoInfinitelyExpandingTypeReference; }; - PullTypeSymbol.prototype._wrapsSomeNestedTypeIntoInfiniteExpansionWorker = function (typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap) { + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + var thisRootType = TypeScript.PullHelpers.getRootType(this); + + if (thisRootType != enclosingType) { + var thisIsNamedType = this.isNamedTypeSymbol(); + + if (thisIsNamedType) { + if (thisRootType.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + thisRootType.inWrapInfiniteExpandingReferenceCheck = true; + } + + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure(enclosingType, knownWrapMap); + + if (thisIsNamedType) { + thisRootType.inWrapInfiniteExpandingReferenceCheck = false; + } + + return wrapsIntoInfinitelyExpandingTypeReference; + } + + var enclosingTypeParameters = enclosingType.getTypeParameters(); var typeArguments = this.getTypeArguments(); - if (typeArguments) { - for (var i = 0; i < typeArguments.length; i++) { - if (typeArguments[i]._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, true, knownWrapMap)) { - return true; - } + for (var i = 0; i < typeArguments.length; i++) { + if (TypeScript.ArrayUtilities.contains(enclosingTypeParameters, typeArguments[i])) { + continue; } - } - if (this.anyRootTypeBeingWrapped(typeBeingWrapped)) { - if (isCheckingTypeArgumentList && this.isTypeReference() && !this.getIsSpecialized()) { + if (typeArguments[i].wrapsSomeTypeParameter(this.getTypeParameterArgumentMap())) { return true; } - - return false; - } else if (!this.isNamedTypeSymbol() || this.isGeneric()) { - var isTypeEquivalentToRootSymbol = this.isTypeEquivalentToRootSymbol(); - var rootType = TypeScript.PullHelpers.getRootType(this); - if (isTypeEquivalentToRootSymbol) { - rootType.inWrapCheck = true; - } - - var members = this.getAllMembers(68147712 /* SomeValue */, 0 /* all */); - for (var i = 0; i < members.length; i++) { - if (members[i].type && members[i].type._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - return true; - } - } - - var sigs = this.getCallSignatures(); - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeNestedTypeIntoInfiniteExpansion(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - return true; - } - } - - sigs = this.getConstructSignatures(); - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeNestedTypeIntoInfiniteExpansion(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - return true; - } - } - - sigs = this.getIndexSignatures(); - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeNestedTypeIntoInfiniteExpansion(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - return true; - } - } - - if (isTypeEquivalentToRootSymbol) { - rootType.inWrapCheck = false; - } - - return false; } + + return false; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure = function (enclosingType, knownWrapMap) { + var members = this.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; i < members.length; i++) { + if (members[i].type && members[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + var sigs = this.getCallSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getConstructSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getIndexSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.widenedType = function (resolver, ast, context) { + if (!this._widenedType) { + this._widenedType = resolver.widenType(this, ast, context); + } + return this._widenedType; }; return PullTypeSymbol; })(PullSymbol); @@ -37781,7 +38039,15 @@ var TypeScript; this.isResolved = true; } PullPrimitiveTypeSymbol.prototype.isAny = function () { - return this.name === "any"; + return !this.isStringConstant() && this.name === "any"; + }; + + PullPrimitiveTypeSymbol.prototype.isNull = function () { + return !this.isStringConstant() && this.name === "null"; + }; + + PullPrimitiveTypeSymbol.prototype.isUndefined = function () { + return !this.isStringConstant() && this.name === "undefined"; }; PullPrimitiveTypeSymbol.prototype.isStringConstant = function () { @@ -37790,6 +38056,14 @@ var TypeScript; PullPrimitiveTypeSymbol.prototype.setUnresolved = function () { }; + + PullPrimitiveTypeSymbol.prototype.getDisplayName = function () { + if (this.isNull() || this.isUndefined()) { + return "any"; + } else { + return _super.prototype.getDisplayName.call(this); + } + }; return PullPrimitiveTypeSymbol; })(PullTypeSymbol); TypeScript.PullPrimitiveTypeSymbol = PullPrimitiveTypeSymbol; @@ -37808,26 +38082,31 @@ var TypeScript; var PullErrorTypeSymbol = (function (_super) { __extends(PullErrorTypeSymbol, _super); - function PullErrorTypeSymbol(anyType, name) { + function PullErrorTypeSymbol(_anyType, name) { _super.call(this, name); - this.anyType = anyType; + this._anyType = _anyType; + TypeScript.Debug.assert(this._anyType); this.isResolved = true; } PullErrorTypeSymbol.prototype.isError = function () { return true; }; + PullErrorTypeSymbol.prototype._getResolver = function () { + return this._anyType._getResolver(); + }; + PullErrorTypeSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { - return this.anyType.getName(scopeSymbol, useConstraintInName); + return this._anyType.getName(scopeSymbol, useConstraintInName); }; PullErrorTypeSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { - return this.anyType.getName(scopeSymbol, useConstraintInName); + return this._anyType.getName(scopeSymbol, useConstraintInName); }; PullErrorTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { - return this.anyType.getName(scopeSymbol, useConstraintInName); + return this._anyType.getName(scopeSymbol, useConstraintInName); }; return PullErrorTypeSymbol; })(PullPrimitiveTypeSymbol); @@ -37887,7 +38166,7 @@ var TypeScript; return false; } - if (!containerSymbol.isAlias() && containerSymbol.type == symbol) { + if (!containerSymbol.isAlias() && containerSymbol.type === symbol) { return true; } @@ -37896,7 +38175,7 @@ var TypeScript; var typeExportSymbol = moduleSymbol.getExportAssignedTypeSymbol(); var containerExportSymbol = moduleSymbol.getExportAssignedContainerSymbol(); if (valueExportSymbol || typeExportSymbol || containerExportSymbol) { - return valueExportSymbol == symbol || typeExportSymbol == symbol || containerExportSymbol == symbol || PullContainerSymbol.usedAsSymbol(containerExportSymbol, symbol); + return valueExportSymbol === symbol || typeExportSymbol == symbol || containerExportSymbol == symbol || PullContainerSymbol.usedAsSymbol(containerExportSymbol, symbol); } return false; @@ -37918,8 +38197,15 @@ var TypeScript; this._assignedContainer = null; this._isUsedAsValue = false; this._typeUsedExternally = false; + this._isUsedInExportAlias = false; this.retrievingExportAssignment = false; + this.linkedAliasSymbols = null; } + PullTypeAliasSymbol.prototype.isUsedInExportedAlias = function () { + this._resolveDeclaredSymbol(); + return this._isUsedInExportAlias; + }; + PullTypeAliasSymbol.prototype.typeUsedExternally = function () { this._resolveDeclaredSymbol(); return this._typeUsedExternally; @@ -37930,19 +38216,33 @@ var TypeScript; return this._isUsedAsValue; }; - PullTypeAliasSymbol.prototype.setTypeUsedExternally = function (value) { - this._typeUsedExternally = value; + PullTypeAliasSymbol.prototype.setTypeUsedExternally = function () { + this._typeUsedExternally = true; }; - PullTypeAliasSymbol.prototype.setIsUsedAsValue = function (value) { - this._isUsedAsValue = value; + PullTypeAliasSymbol.prototype.setIsUsedInExportedAlias = function () { + this._isUsedInExportAlias = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedInExportedAlias(); + }); + } + }; - this._resolveDeclaredSymbol(); - var resolver = this._getResolver(); - var importDeclStatement = resolver.semanticInfoChain.getASTForDecl(this.getDeclarations()[0]); - var aliasSymbol = resolver.semanticInfoChain.getAliasSymbolForAST(importDeclStatement.moduleReference); - if (aliasSymbol) { - aliasSymbol.setIsUsedAsValue(value); + PullTypeAliasSymbol.prototype.addLinkedAliasSymbol = function (contingentValueSymbol) { + if (!this.linkedAliasSymbols) { + this.linkedAliasSymbols = [contingentValueSymbol]; + } else { + this.linkedAliasSymbols.push(contingentValueSymbol); + } + }; + + PullTypeAliasSymbol.prototype.setIsUsedAsValue = function () { + this._isUsedAsValue = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedAsValue(); + }); } }; @@ -38005,7 +38305,7 @@ var TypeScript; this.retrievingExportAssignment = true; var sym = this._assignedType.getExportAssignedTypeSymbol(); this.retrievingExportAssignment = false; - } else if (this._assignedType != this._assignedContainer) { + } else if (this._assignedType !== this._assignedContainer) { return this._assignedType; } } @@ -38110,31 +38410,15 @@ var TypeScript; })(PullTypeSymbol); TypeScript.PullTypeAliasSymbol = PullTypeAliasSymbol; - var PullDefinitionSignatureSymbol = (function (_super) { - __extends(PullDefinitionSignatureSymbol, _super); - function PullDefinitionSignatureSymbol() { - _super.apply(this, arguments); - } - PullDefinitionSignatureSymbol.prototype.isDefinition = function () { - return true; - }; - return PullDefinitionSignatureSymbol; - })(PullSignatureSymbol); - TypeScript.PullDefinitionSignatureSymbol = PullDefinitionSignatureSymbol; - var PullTypeParameterSymbol = (function (_super) { __extends(PullTypeParameterSymbol, _super); - function PullTypeParameterSymbol(name, _isFunctionTypeParameter) { + function PullTypeParameterSymbol(name) { _super.call(this, name, 8192 /* TypeParameter */); - this._isFunctionTypeParameter = _isFunctionTypeParameter; this._constraint = null; } PullTypeParameterSymbol.prototype.isTypeParameter = function () { return true; }; - PullTypeParameterSymbol.prototype.isFunctionTypeParameter = function () { - return this._isFunctionTypeParameter; - }; PullTypeParameterSymbol.prototype.setConstraint = function (constraintType) { this._constraint = constraintType; @@ -38144,6 +38428,34 @@ var TypeScript; return this._constraint; }; + PullTypeParameterSymbol.prototype.getBaseConstraint = function (semanticInfoChain) { + var preBaseConstraint = this.getConstraintRecursively({}); + TypeScript.Debug.assert(preBaseConstraint === null || !preBaseConstraint.isTypeParameter()); + return preBaseConstraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getConstraintRecursively = function (visitedTypeParameters) { + var constraint = this.getConstraint(); + + if (constraint) { + if (constraint.isTypeParameter()) { + var constraintAsTypeParameter = constraint; + if (!visitedTypeParameters[constraintAsTypeParameter.pullSymbolID]) { + visitedTypeParameters[constraintAsTypeParameter.pullSymbolID] = constraintAsTypeParameter; + return constraintAsTypeParameter.getConstraintRecursively(visitedTypeParameters); + } + } else { + return constraint; + } + } + + return null; + }; + + PullTypeParameterSymbol.prototype.getDefaultConstraint = function (semanticInfoChain) { + return this._constraint || semanticInfoChain.emptyTypeSymbol; + }; + PullTypeParameterSymbol.prototype.getCallSignatures = function () { if (this._constraint) { return this._constraint.getCallSignatures(); @@ -38264,80 +38576,79 @@ var TypeScript; })(PullSymbol); TypeScript.PullAccessorSymbol = PullAccessorSymbol; - function getIDForTypeSubstitutions(types) { + function getIDForTypeSubstitutions(instantiatingTypeOrSignature, typeArgumentMap) { var substitution = ""; var members = null; - for (var i = 0; i < types.length; i++) { - if (types[i].kind !== 8388608 /* ObjectType */) { - substitution += types[i].pullSymbolID + "#"; - } else { - var structure = getIDForTypeSubstitutionsFromObjectType(types[i]); - - if (structure) { - substitution += structure; - } else { - substitution += types[i].pullSymbolID + "#"; - } + var allowedToReferenceTypeParameters = instantiatingTypeOrSignature.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedToReferenceTypeParameters.length; i++) { + var typeParameter = allowedToReferenceTypeParameters[i]; + var typeParameterID = typeParameter.pullSymbolID; + var typeArg = typeArgumentMap[typeParameterID]; + if (!typeArg) { + typeArg = typeParameter; } + substitution += typeParameterID + ":" + getIDForTypeSubstitutionsOfType(typeArg); } return substitution; } TypeScript.getIDForTypeSubstitutions = getIDForTypeSubstitutions; - function getIDForTypeSubstitutionsFromObjectType(type) { - var structure = ""; - - if (type.isResolved) { - var members = type.getMembers(); - if (members && members.length) { - for (var j = 0; j < members.length; j++) { - structure += members[j].name + "@" + getIDForTypeSubstitutions([members[j].type]); - } - } - - var callSignatures = type.getCallSignatures(); - if (callSignatures && callSignatures.length) { - for (var j = 0; j < callSignatures.length; j++) { - structure += getIDForTypeSubstitutionFromSignature(callSignatures[j]); - } - } - - var constructSignatures = type.getConstructSignatures(); - if (constructSignatures && constructSignatures.length) { - for (var j = 0; j < constructSignatures.length; j++) { - structure += "new" + getIDForTypeSubstitutionFromSignature(constructSignatures[j]); - } - } - - var indexSignatures = type.getIndexSignatures(); - if (indexSignatures && indexSignatures.length) { - for (var j = 0; j < indexSignatures.length; j++) { - structure += "[]" + getIDForTypeSubstitutionFromSignature(indexSignatures[j]); - } - } + function getIDForTypeSubstitutionsOfType(type) { + var structure; + if (type.isError()) { + structure = "E" + getIDForTypeSubstitutionsOfType(type._anyType); + } else if (!type.isNamedTypeSymbol()) { + structure = getIDForTypeSubstitutionsFromObjectType(type); } - if (structure !== "") { - return "{" + structure + "}"; + if (!structure) { + structure = type.pullSymbolID + "#"; + } + + return structure; + } + + function getIDForTypeSubstitutionsFromObjectType(type) { + if (type.isResolved) { + var getIDForTypeSubStitutionWalker = new GetIDForTypeSubStitutionWalker(); + TypeScript.PullHelpers.walkPullTypeSymbolStructure(type, getIDForTypeSubStitutionWalker); } return null; } - function getIDForTypeSubstitutionFromSignature(signature) { - var structure = "("; - var parameters = signature.parameters; - if (parameters && parameters.length) { - for (var k = 0; k < parameters.length; k++) { - structure += parameters[k].name + "@" + getIDForTypeSubstitutions([parameters[k].type]); - } + var GetIDForTypeSubStitutionWalker = (function () { + function GetIDForTypeSubStitutionWalker() { + this.structure = ""; } - - structure += ")" + getIDForTypeSubstitutions([signature.returnType]); - return structure; - } + GetIDForTypeSubStitutionWalker.prototype.memberSymbolWalk = function (memberSymbol) { + this.structure += memberSymbol.name + "@" + getIDForTypeSubstitutionsOfType(memberSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.callSignatureWalk = function (signatureSymbol) { + this.structure += "("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.constructSignatureWalk = function (signatureSymbol) { + this.structure += "new("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.indexSignatureWalk = function (signatureSymbol) { + this.structure += "[]("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureParameterWalk = function (parameterSymbol) { + this.structure += parameterSymbol.name + "@" + getIDForTypeSubstitutionsOfType(parameterSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureReturnTypeWalk = function (returnType) { + this.structure += ")" + getIDForTypeSubstitutionsOfType(returnType); + return true; + }; + return GetIDForTypeSubStitutionWalker; + })(); (function (GetAllMembersVisiblity) { GetAllMembersVisiblity[GetAllMembersVisiblity["all"] = 0] = "all"; @@ -38349,38 +38660,311 @@ var TypeScript; var GetAllMembersVisiblity = TypeScript.GetAllMembersVisiblity; })(TypeScript || (TypeScript = {})); var TypeScript; +(function (TypeScript) { + var PullTypeEnclosingTypeWalker = (function () { + function PullTypeEnclosingTypeWalker() { + this.currentSymbols = null; + } + PullTypeEnclosingTypeWalker.prototype.getEnclosingType = function () { + if (this.currentSymbols && this.currentSymbols.length > 0) { + return this.currentSymbols[0]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype._canWalkStructure = function () { + var enclosingType = this.getEnclosingType(); + return !!enclosingType && enclosingType.isGeneric(); + }; + + PullTypeEnclosingTypeWalker.prototype._getCurrentSymbol = function () { + if (this.currentSymbols && this.currentSymbols.length) { + return this.currentSymbols[this.currentSymbols.length - 1]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.getGenerativeClassification = function () { + if (this._canWalkStructure()) { + var currentType = this.currentSymbols[this.currentSymbols.length - 1]; + if (!currentType) { + return 0 /* Unknown */; + } + + var variableNeededToFixNodeJitterBug = this.getEnclosingType(); + + return currentType.getGenerativeTypeClassification(variableNeededToFixNodeJitterBug); + } + + return 2 /* Closed */; + }; + + PullTypeEnclosingTypeWalker.prototype._pushSymbol = function (symbol) { + return this.currentSymbols.push(symbol); + }; + + PullTypeEnclosingTypeWalker.prototype._popSymbol = function () { + return this.currentSymbols.pop(); + }; + + PullTypeEnclosingTypeWalker.prototype._setEnclosingTypeOfParentDecl = function (decl, setSignature) { + var parentDecl = decl.getParentDecl(); + if (parentDecl) { + if (parentDecl.kind & 8216 /* SomeInstantiatableType */) { + this._setEnclosingTypeWorker(parentDecl.getSymbol(), true); + } else { + this._setEnclosingTypeOfParentDecl(parentDecl, true); + } + + if (this._canWalkStructure()) { + var symbol = decl.getSymbol(); + if (symbol) { + if (symbol.kind == 2048 /* Parameter */ || symbol.kind == 4096 /* Property */ || symbol.kind == 65536 /* Method */ || symbol.kind == 32768 /* ConstructorMethod */ || symbol.kind == 131072 /* FunctionExpression */) { + symbol = symbol.type; + } + + this._pushSymbol(symbol); + } + + if (setSignature) { + var signature = decl.getSignatureSymbol(); + if (signature) { + this._pushSymbol(signature); + } + } + } + } + }; + + PullTypeEnclosingTypeWalker.prototype._setEnclosingTypeWorker = function (symbol, setSignature) { + if (symbol.isType() && symbol.isNamedTypeSymbol()) { + this.currentSymbols = [TypeScript.PullHelpers.getRootType(symbol)]; + return; + } + + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + this._setEnclosingTypeOfParentDecl(decl, setSignature); + if (this._canWalkStructure()) { + return; + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.setCurrentSymbol = function (symbol) { + TypeScript.Debug.assert(this._canWalkStructure()); + this.currentSymbols[this.currentSymbols.length - 1] = symbol; + }; + + PullTypeEnclosingTypeWalker.prototype.startWalkingType = function (symbol) { + var currentSymbols = this.currentSymbols; + + var setEnclosingType = !this.getEnclosingType() || symbol.isNamedTypeSymbol(); + if (setEnclosingType) { + this.currentSymbols = null; + this.setEnclosingType(symbol); + } + return currentSymbols; + }; + + PullTypeEnclosingTypeWalker.prototype.endWalkingType = function (currentSymbolsWhenStartedWalkingTypes) { + this.currentSymbols = currentSymbolsWhenStartedWalkingTypes; + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingType = function (symbol) { + TypeScript.Debug.assert(!this.getEnclosingType()); + this._setEnclosingTypeWorker(symbol, symbol.isSignature()); + }; + + PullTypeEnclosingTypeWalker.prototype.walkMemberType = function (memberName, resolver) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var memberSymbol = currentType ? resolver._getNamedPropertySymbolOfAugmentedType(memberName, currentType) : null; + this._pushSymbol(memberSymbol ? memberSymbol.type : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkMemberType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkSignature = function (kind, index) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var signatures; + if (currentType) { + if (kind == 1048576 /* CallSignature */) { + signatures = currentType.getCallSignatures(); + } else if (kind == 2097152 /* ConstructSignature */) { + signatures = currentType.getConstructSignatures(); + } else { + signatures = currentType.getIndexSignatures(); + } + } + + this._pushSymbol(signatures ? signatures[index] : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkSignature = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeArgument = function (index) { + if (this._canWalkStructure()) { + var typeArgument = null; + var currentType = this._getCurrentSymbol(); + if (currentType) { + var typeArguments = currentType.getTypeArguments(); + typeArgument = typeArguments ? typeArguments[index] : null; + } + this._pushSymbol(typeArgument); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeArgument = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeParameterConstraint = function (index) { + if (this._canWalkStructure()) { + var typeParameters; + var currentSymbol = this._getCurrentSymbol(); + if (currentSymbol) { + if (currentSymbol.isSignature()) { + typeParameters = currentSymbol.getTypeParameters(); + } else { + TypeScript.Debug.assert(currentSymbol.isType()); + typeParameters = currentSymbol.getTypeParameters(); + } + } + this._pushSymbol(typeParameters ? typeParameters[index].getConstraint() : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeParameterConstraint = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkReturnType = function () { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.returnType : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkReturnType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkParameterType = function (iParam) { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.getParameterTypeAtIndex(iParam) : null); + } + }; + PullTypeEnclosingTypeWalker.prototype.postWalkParameterType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.getBothKindOfIndexSignatures = function (resolver, context, includeAugmentedType) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (currentType) { + return resolver._getBothKindsOfIndexSignatures(currentType, context, includeAugmentedType); + } + } + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.walkIndexSignatureReturnType = function (indexSigInfo, useStringIndexSignature, onlySignature) { + if (this._canWalkStructure()) { + var indexSig = indexSigInfo ? (useStringIndexSignature ? indexSigInfo.stringSignature : indexSigInfo.numericSignature) : null; + this._pushSymbol(indexSig); + if (!onlySignature) { + this._pushSymbol(indexSig ? indexSig.returnType : null); + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkIndexSignatureReturnType = function (onlySignature) { + if (this._canWalkStructure()) { + if (!onlySignature) { + this._popSymbol(); + } + this._popSymbol(); + } + }; + return PullTypeEnclosingTypeWalker; + })(); + TypeScript.PullTypeEnclosingTypeWalker = PullTypeEnclosingTypeWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; (function (TypeScript) { var CandidateInferenceInfo = (function () { function CandidateInferenceInfo() { this.typeParameter = null; - this.isFixed = false; + this._inferredTypeAfterFixing = null; this.inferenceCandidates = []; } CandidateInferenceInfo.prototype.addCandidate = function (candidate) { - if (!this.isFixed) { + if (!this._inferredTypeAfterFixing) { this.inferenceCandidates[this.inferenceCandidates.length] = candidate; } }; + + CandidateInferenceInfo.prototype.isFixed = function () { + return !!this._inferredTypeAfterFixing; + }; + + CandidateInferenceInfo.prototype.fixTypeParameter = function (resolver, context) { + var _this = this; + if (!this._inferredTypeAfterFixing) { + var collection = { + getLength: function () { + return _this.inferenceCandidates.length; + }, + getTypeAtIndex: function (index) { + return _this.inferenceCandidates[index].type; + } + }; + + var bestCommonType = resolver.findBestCommonType(collection, context, new TypeScript.TypeComparisonInfo()); + this._inferredTypeAfterFixing = bestCommonType.widenedType(resolver, null, context); + } + }; return CandidateInferenceInfo; })(); TypeScript.CandidateInferenceInfo = CandidateInferenceInfo; - var ArgumentInferenceContext = (function () { - function ArgumentInferenceContext(resolver, argumentsOrParameters) { + var TypeArgumentInferenceContext = (function () { + function TypeArgumentInferenceContext(resolver, context, signatureBeingInferred) { + this.resolver = resolver; + this.context = context; + this.signatureBeingInferred = signatureBeingInferred; this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); this.candidateCache = []; - this.fixedParameterTypes = null; - this.resolver = null; - this.argumentASTs = null; - this.resolver = resolver; - - if (argumentsOrParameters.nonSeparatorAt != undefined) { - this.argumentASTs = argumentsOrParameters; - } else { - this.fixedParameterTypes = argumentsOrParameters; + var typeParameters = signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addInferenceRoot(typeParameters[i]); } } - ArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { + TypeArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { if (this.inferenceCache.valueAt(objectType.pullSymbolID, parameterType.pullSymbolID)) { return true; } else { @@ -38389,12 +38973,12 @@ var TypeScript; } }; - ArgumentInferenceContext.prototype.resetRelationshipCache = function () { + TypeArgumentInferenceContext.prototype.resetRelationshipCache = function () { this.inferenceCache.release(); this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); }; - ArgumentInferenceContext.prototype.addInferenceRoot = function (param) { + TypeArgumentInferenceContext.prototype.addInferenceRoot = function (param) { var info = this.candidateCache[param.pullSymbolID]; if (!info) { @@ -38404,116 +38988,121 @@ var TypeScript; } }; - ArgumentInferenceContext.prototype.getInferenceInfo = function (param) { + TypeArgumentInferenceContext.prototype.getInferenceInfo = function (param) { return this.candidateCache[param.pullSymbolID]; }; - ArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate, fix) { + TypeArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate) { var info = this.getInferenceInfo(param); - if (info) { - if (candidate) { - info.addCandidate(candidate); - } - - if (!info.isFixed) { - info.isFixed = fix; - } + if (info && candidate && info.inferenceCandidates.indexOf(candidate) < 0) { + info.addCandidate(candidate); } }; - ArgumentInferenceContext.prototype.getInferenceArgumentCount = function () { - if (this.fixedParameterTypes) { - return this.fixedParameterTypes.length; - } else { - return this.argumentASTs.nonSeparatorCount(); + TypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + throw TypeScript.Errors.abstract(); + }; + + TypeArgumentInferenceContext.prototype.fixTypeParameter = function (typeParameter) { + var candidateInfo = this.candidateCache[typeParameter.pullSymbolID]; + if (candidateInfo) { + candidateInfo.fixTypeParameter(this.resolver, this.context); } }; - ArgumentInferenceContext.prototype.getArgumentTypeSymbolAtIndex = function (i, context) { - TypeScript.Debug.assert(i >= 0, "invalid inference argument position"); - - if (this.fixedParameterTypes && i < this.getInferenceArgumentCount()) { - return this.fixedParameterTypes[i]; - } else if (i < this.getInferenceArgumentCount()) { - return this.resolver.resolveAST(this.argumentASTs.nonSeparatorAt(i), true, context).type; - } - - return null; - }; - - ArgumentInferenceContext.prototype.getInferenceCandidates = function () { - var inferenceCandidates = []; - - for (var infoKey in this.candidateCache) { - if (this.candidateCache.hasOwnProperty(infoKey)) { - var info = this.candidateCache[infoKey]; - - for (var i = 0; i < info.inferenceCandidates.length; i++) { - var val = []; - val[info.typeParameter.pullSymbolID] = info.inferenceCandidates[i]; - inferenceCandidates.push(val); - } - } - } - - return inferenceCandidates; - }; - - ArgumentInferenceContext.prototype.inferArgumentTypes = function (resolver, context) { - var collection; - - var bestCommonType; - + TypeArgumentInferenceContext.prototype._finalizeInferredTypeArguments = function () { var results = []; + var typeParameters = this.signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + var info = this.candidateCache[typeParameters[i].pullSymbolID]; - var unfit = false; + info.fixTypeParameter(this.resolver, this.context); - for (var infoKey in this.candidateCache) { - if (this.candidateCache.hasOwnProperty(infoKey)) { - var info = this.candidateCache[infoKey]; - - if (!info.inferenceCandidates.length) { - results[results.length] = { param: info.typeParameter, type: null }; - continue; + for (var i = 0; i < results.length; i++) { + if (results[i].type === info.typeParameter) { + results[i].type = info._inferredTypeAfterFixing; } - - collection = { - getLength: function () { - return info.inferenceCandidates.length; - }, - getTypeAtIndex: function (index) { - return info.inferenceCandidates[index].type; - } - }; - - bestCommonType = resolver.widenType(resolver.findBestCommonType(collection, context, new TypeScript.TypeComparisonInfo())); - - if (!bestCommonType) { - unfit = true; - } else { - for (var i = 0; i < results.length; i++) { - if (results[i].type == info.typeParameter) { - results[i].type = bestCommonType; - } - } - } - - results[results.length] = { param: info.typeParameter, type: bestCommonType }; } + + results.push(info._inferredTypeAfterFixing); } - return { results: results, unfit: unfit }; + return results; }; - return ArgumentInferenceContext; + + TypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + throw TypeScript.Errors.abstract(); + }; + return TypeArgumentInferenceContext; })(); - TypeScript.ArgumentInferenceContext = ArgumentInferenceContext; + TypeScript.TypeArgumentInferenceContext = TypeArgumentInferenceContext; + + var InvocationTypeArgumentInferenceContext = (function (_super) { + __extends(InvocationTypeArgumentInferenceContext, _super); + function InvocationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, argumentASTs) { + _super.call(this, resolver, context, signatureBeingInferred); + this.argumentASTs = argumentASTs; + } + InvocationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return true; + }; + + InvocationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + this.signatureBeingInferred.forAllParameterTypes(this.argumentASTs.nonSeparatorCount(), function (parameterType, argumentIndex) { + var argumentAST = _this.argumentASTs.nonSeparatorAt(argumentIndex); + + _this.context.pushInferentialType(parameterType, _this); + var argumentType = _this.resolver.resolveAST(argumentAST, true, _this.context).type; + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(argumentType, parameterType, _this, _this.context); + _this.context.popAnyContextualType(); + + return true; + }); + + return this._finalizeInferredTypeArguments(); + }; + return InvocationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.InvocationTypeArgumentInferenceContext = InvocationTypeArgumentInferenceContext; + + var ContextualSignatureInstantiationTypeArgumentInferenceContext = (function (_super) { + __extends(ContextualSignatureInstantiationTypeArgumentInferenceContext, _super); + function ContextualSignatureInstantiationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, contextualSignature, shouldFixContextualSignatureParameterTypes) { + _super.call(this, resolver, context, signatureBeingInferred); + this.contextualSignature = contextualSignature; + this.shouldFixContextualSignatureParameterTypes = shouldFixContextualSignatureParameterTypes; + } + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return false; + }; + + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + var relateTypesCallback = function (parameterTypeBeingInferred, contextualParameterType) { + if (_this.shouldFixContextualSignatureParameterTypes) { + contextualParameterType = _this.context.fixAllTypeParametersReferencedByType(contextualParameterType, _this.resolver, _this); + } + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(contextualParameterType, parameterTypeBeingInferred, _this, _this.context); + + return true; + }; + + this.signatureBeingInferred.forAllCorrespondingParameterTypesInThisAndOtherSignature(this.contextualSignature, relateTypesCallback); + + return this._finalizeInferredTypeArguments(); + }; + return ContextualSignatureInstantiationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext = ContextualSignatureInstantiationTypeArgumentInferenceContext; var PullContextualTypeContext = (function () { - function PullContextualTypeContext(contextualType, provisional, substitutions) { + function PullContextualTypeContext(contextualType, provisional, isInferentiallyTyping, typeArgumentInferenceContext) { this.contextualType = contextualType; this.provisional = provisional; - this.substitutions = substitutions; + this.isInferentiallyTyping = isInferentiallyTyping; + this.typeArgumentInferenceContext = typeArgumentInferenceContext; this.provisionallyTypedSymbols = []; this.hasProvisionalErrors = false; this.astSymbolMap = []; @@ -38548,6 +39137,8 @@ var TypeScript; this.fileName = fileName; this.contextStack = []; this.typeCheckedNodes = null; + this.enclosingTypeWalker1 = null; + this.enclosingTypeWalker2 = null; this.inBaseTypeResolution = false; if (inTypeCheck) { TypeScript.Debug.assert(fileName, "A file name must be provided if you are typechecking"); @@ -38564,11 +39155,27 @@ var TypeScript; return this.typeCheck() && !this.typeCheckedNodes.valueAt(ast.syntaxID()) && this.fileName === ast.fileName(); }; - PullTypeResolutionContext.prototype.pushContextualType = function (type, provisional, substitutions) { - this.contextStack.push(new PullContextualTypeContext(type, provisional, substitutions)); + PullTypeResolutionContext.prototype._pushAnyContextualType = function (type, provisional, isInferentiallyTyping, argContext) { + this.contextStack.push(new PullContextualTypeContext(type, provisional, isInferentiallyTyping, argContext)); }; - PullTypeResolutionContext.prototype.popContextualType = function () { + PullTypeResolutionContext.prototype.pushNewContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), false, null); + }; + + PullTypeResolutionContext.prototype.propagateContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), this.isInferentiallyTyping(), this.getCurrentTypeArgumentInferenceContext()); + }; + + PullTypeResolutionContext.prototype.pushInferentialType = function (type, typeArgumentInferenceContext) { + this._pushAnyContextualType(type, true, true, typeArgumentInferenceContext); + }; + + PullTypeResolutionContext.prototype.pushProvisionalType = function (type) { + this._pushAnyContextualType(type, true, false, null); + }; + + PullTypeResolutionContext.prototype.popAnyContextualType = function () { var tc = this.contextStack.pop(); tc.invalidateProvisionallyTypedSymbols(); @@ -38584,24 +39191,6 @@ var TypeScript; return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].hasProvisionalErrors : false; }; - PullTypeResolutionContext.prototype.findSubstitution = function (type) { - var substitution = null; - - if (this.contextStack.length) { - for (var i = this.contextStack.length - 1; i >= 0; i--) { - if (this.contextStack[i].substitutions) { - substitution = this.contextStack[i].substitutions[type.pullSymbolID]; - - if (substitution) { - break; - } - } - } - } - - return substitution; - }; - PullTypeResolutionContext.prototype.getContextualType = function () { var context = !this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]; @@ -38612,18 +39201,44 @@ var TypeScript; return null; } - if (type.isTypeParameter() && type.getConstraint()) { - type = type.getConstraint(); - } - - var substitution = this.findSubstitution(type); - - return substitution ? substitution : type; + return type; } return null; }; + PullTypeResolutionContext.prototype.fixAllTypeParametersReferencedByType = function (type, resolver, argContext) { + var argContext = this.getCurrentTypeArgumentInferenceContext(); + if (type.wrapsSomeTypeParameter(argContext.candidateCache)) { + var typeParameterArgumentMap = []; + + for (var n in argContext.candidateCache) { + var typeParameter = argContext.candidateCache[n] && argContext.candidateCache[n].typeParameter; + if (typeParameter) { + var dummyMap = []; + dummyMap[typeParameter.pullSymbolID] = typeParameter; + if (type.wrapsSomeTypeParameter(dummyMap)) { + argContext.fixTypeParameter(typeParameter); + TypeScript.Debug.assert(argContext.candidateCache[n]._inferredTypeAfterFixing); + typeParameterArgumentMap[typeParameter.pullSymbolID] = argContext.candidateCache[n]._inferredTypeAfterFixing; + } + } + } + + return resolver.instantiateType(type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolutionContext.prototype.getCurrentTypeArgumentInferenceContext = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].typeArgumentInferenceContext : null; + }; + + PullTypeResolutionContext.prototype.isInferentiallyTyping = function () { + return this.contextStack.length > 0 && this.contextStack[this.contextStack.length - 1].isInferentiallyTyping; + }; + PullTypeResolutionContext.prototype.inProvisionalResolution = function () { return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); }; @@ -38643,9 +39258,10 @@ var TypeScript; }; PullTypeResolutionContext.prototype.setTypeInContext = function (symbol, type) { - var substitution = this.findSubstitution(type); - - symbol.type = substitution ? substitution : type; + if (symbol.type && symbol.type.isError() && !type.isError()) { + return; + } + symbol.type = type; if (this.contextStack.length && this.inProvisionalResolution()) { this.contextStack[this.contextStack.length - 1].recordProvisionallyTypedSymbol(symbol); @@ -38685,6 +39301,145 @@ var TypeScript; return null; }; + + PullTypeResolutionContext.prototype.startWalkingTypes = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var symbolsWhenStartedWalkingTypes1 = this.enclosingTypeWalker1.startWalkingType(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var symbolsWhenStartedWalkingTypes2 = this.enclosingTypeWalker2.startWalkingType(symbol2); + return { symbolsWhenStartedWalkingTypes1: symbolsWhenStartedWalkingTypes1, symbolsWhenStartedWalkingTypes2: symbolsWhenStartedWalkingTypes2 }; + }; + + PullTypeResolutionContext.prototype.endWalkingTypes = function (symbolsWhenStartedWalkingTypes) { + this.enclosingTypeWalker1.endWalkingType(symbolsWhenStartedWalkingTypes.symbolsWhenStartedWalkingTypes1); + this.enclosingTypeWalker2.endWalkingType(symbolsWhenStartedWalkingTypes.symbolsWhenStartedWalkingTypes2); + }; + + PullTypeResolutionContext.prototype.setEnclosingTypes = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + this.enclosingTypeWalker1.setEnclosingType(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + this.enclosingTypeWalker2.setEnclosingType(symbol2); + }; + + PullTypeResolutionContext.prototype.walkMemberTypes = function (memberName) { + this.enclosingTypeWalker1.walkMemberType(memberName, this.resolver); + this.enclosingTypeWalker2.walkMemberType(memberName, this.resolver); + }; + + PullTypeResolutionContext.prototype.postWalkMemberTypes = function () { + this.enclosingTypeWalker1.postWalkMemberType(); + this.enclosingTypeWalker2.postWalkMemberType(); + }; + + PullTypeResolutionContext.prototype.walkSignatures = function (kind, index, index2) { + this.enclosingTypeWalker1.walkSignature(kind, index); + this.enclosingTypeWalker2.walkSignature(kind, index2 == undefined ? index : index2); + }; + + PullTypeResolutionContext.prototype.postWalkSignatures = function () { + this.enclosingTypeWalker1.postWalkSignature(); + this.enclosingTypeWalker2.postWalkSignature(); + }; + + PullTypeResolutionContext.prototype.walkTypeParameterConstraints = function (index) { + this.enclosingTypeWalker1.walkTypeParameterConstraint(index); + this.enclosingTypeWalker2.walkTypeParameterConstraint(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeParameterConstraints = function () { + this.enclosingTypeWalker1.postWalkTypeParameterConstraint(); + this.enclosingTypeWalker2.postWalkTypeParameterConstraint(); + }; + + PullTypeResolutionContext.prototype.walkTypeArgument = function (index) { + this.enclosingTypeWalker1.walkTypeArgument(index); + this.enclosingTypeWalker2.walkTypeArgument(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeArgument = function () { + this.enclosingTypeWalker1.postWalkTypeArgument(); + this.enclosingTypeWalker2.postWalkTypeArgument(); + }; + + PullTypeResolutionContext.prototype.walkReturnTypes = function () { + this.enclosingTypeWalker1.walkReturnType(); + this.enclosingTypeWalker2.walkReturnType(); + }; + + PullTypeResolutionContext.prototype.postWalkReturnTypes = function () { + this.enclosingTypeWalker1.postWalkReturnType(); + this.enclosingTypeWalker2.postWalkReturnType(); + }; + + PullTypeResolutionContext.prototype.walkParameterTypes = function (iParam) { + this.enclosingTypeWalker1.walkParameterType(iParam); + this.enclosingTypeWalker2.walkParameterType(iParam); + }; + + PullTypeResolutionContext.prototype.postWalkParameterTypes = function () { + this.enclosingTypeWalker1.postWalkParameterType(); + this.enclosingTypeWalker2.postWalkParameterType(); + }; + + PullTypeResolutionContext.prototype.getBothKindOfIndexSignatures = function (includeAugmentedType1, includeAugmentedType2) { + var indexSigs1 = this.enclosingTypeWalker1.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType1); + var indexSigs2 = this.enclosingTypeWalker2.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType2); + return { indexSigs1: indexSigs1, indexSigs2: indexSigs2 }; + }; + + PullTypeResolutionContext.prototype.walkIndexSignatureReturnTypes = function (indexSigs, useStringIndexSignature1, useStringIndexSignature2, onlySignature) { + this.enclosingTypeWalker1.walkIndexSignatureReturnType(indexSigs.indexSigs1, useStringIndexSignature1, onlySignature); + this.enclosingTypeWalker2.walkIndexSignatureReturnType(indexSigs.indexSigs2, useStringIndexSignature2, onlySignature); + }; + + PullTypeResolutionContext.prototype.postWalkIndexSignatureReturnTypes = function (onlySignature) { + this.enclosingTypeWalker1.postWalkIndexSignatureReturnType(onlySignature); + this.enclosingTypeWalker2.postWalkIndexSignatureReturnType(onlySignature); + }; + + PullTypeResolutionContext.prototype.swapEnclosingTypeWalkers = function () { + var tempEnclosingWalker1 = this.enclosingTypeWalker1; + this.enclosingTypeWalker1 = this.enclosingTypeWalker2; + this.enclosingTypeWalker2 = tempEnclosingWalker1; + }; + + PullTypeResolutionContext.prototype.oneOfClassificationsIsInfinitelyExpanding = function () { + var generativeClassification1 = this.enclosingTypeWalker1.getGenerativeClassification(); + if (generativeClassification1 === 3 /* InfinitelyExpanding */) { + return true; + } + var generativeClassification2 = this.enclosingTypeWalker2.getGenerativeClassification(); + if (generativeClassification2 === 3 /* InfinitelyExpanding */) { + return true; + } + + return false; + }; + + PullTypeResolutionContext.prototype.resetEnclosingTypeWalkers = function () { + var enclosingTypeWalker1 = this.enclosingTypeWalker1; + var enclosingTypeWalker2 = this.enclosingTypeWalker2; + this.enclosingTypeWalker1 = null; + this.enclosingTypeWalker2 = null; + return { + enclosingTypeWalker1: enclosingTypeWalker1, + enclosingTypeWalker2: enclosingTypeWalker2 + }; + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeWalkers = function (enclosingTypeWalkers) { + this.enclosingTypeWalker1 = enclosingTypeWalkers.enclosingTypeWalker1; + this.enclosingTypeWalker2 = enclosingTypeWalkers.enclosingTypeWalker2; + }; return PullTypeResolutionContext; })(); TypeScript.PullTypeResolutionContext = PullTypeResolutionContext; @@ -38741,20 +39496,19 @@ var TypeScript; return InheritedIndexSignatureInfo; })(); - var CompilerReservedNames; - (function (CompilerReservedNames) { - CompilerReservedNames[CompilerReservedNames["_this"] = 1] = "_this"; - CompilerReservedNames[CompilerReservedNames["_super"] = 2] = "_super"; - CompilerReservedNames[CompilerReservedNames["arguments"] = 3] = "arguments"; - CompilerReservedNames[CompilerReservedNames["_i"] = 4] = "_i"; - CompilerReservedNames[CompilerReservedNames["require"] = 5] = "require"; - CompilerReservedNames[CompilerReservedNames["exports"] = 6] = "exports"; - })(CompilerReservedNames || (CompilerReservedNames = {})); + var CompilerReservedName; + (function (CompilerReservedName) { + CompilerReservedName[CompilerReservedName["_this"] = 1] = "_this"; + CompilerReservedName[CompilerReservedName["_super"] = 2] = "_super"; + CompilerReservedName[CompilerReservedName["arguments"] = 3] = "arguments"; + CompilerReservedName[CompilerReservedName["_i"] = 4] = "_i"; + CompilerReservedName[CompilerReservedName["require"] = 5] = "require"; + CompilerReservedName[CompilerReservedName["exports"] = 6] = "exports"; + })(CompilerReservedName || (CompilerReservedName = {})); function getCompilerReservedName(name) { var nameText = name.valueText(); - var index = CompilerReservedNames[nameText]; - return CompilerReservedNames[index] ? index : undefined; + return CompilerReservedName[nameText]; } var PullTypeResolver = (function () { @@ -38776,14 +39530,11 @@ var TypeScript; this.assignableCache = TypeScript.BitMatrix.getBitMatrix(true); this.subtypeCache = TypeScript.BitMatrix.getBitMatrix(true); this.identicalCache = TypeScript.BitMatrix.getBitMatrix(true); + this.inResolvingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); } PullTypeResolver.prototype.cachedArrayInterfaceType = function () { if (!this._cachedArrayInterfaceType) { - this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */); - } - - if (!this._cachedArrayInterfaceType) { - this._cachedArrayInterfaceType = this.semanticInfoChain.anyTypeSymbol; + this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (!this._cachedArrayInterfaceType.isResolved) { @@ -38799,7 +39550,7 @@ var TypeScript; PullTypeResolver.prototype.cachedNumberInterfaceType = function () { if (!this._cachedNumberInterfaceType) { - this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */); + this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedNumberInterfaceType && !this._cachedNumberInterfaceType.isResolved) { @@ -38811,7 +39562,7 @@ var TypeScript; PullTypeResolver.prototype.cachedStringInterfaceType = function () { if (!this._cachedStringInterfaceType) { - this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */); + this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedStringInterfaceType && !this._cachedStringInterfaceType.isResolved) { @@ -38823,7 +39574,7 @@ var TypeScript; PullTypeResolver.prototype.cachedBooleanInterfaceType = function () { if (!this._cachedBooleanInterfaceType) { - this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */); + this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedBooleanInterfaceType && !this._cachedBooleanInterfaceType.isResolved) { @@ -38835,7 +39586,7 @@ var TypeScript; PullTypeResolver.prototype.cachedObjectInterfaceType = function () { if (!this._cachedObjectInterfaceType) { - this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */); + this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (!this._cachedObjectInterfaceType) { @@ -38851,7 +39602,7 @@ var TypeScript; PullTypeResolver.prototype.cachedFunctionInterfaceType = function () { if (!this._cachedFunctionInterfaceType) { - this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */); + this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedFunctionInterfaceType && !this._cachedFunctionInterfaceType.isResolved) { @@ -38863,7 +39614,7 @@ var TypeScript; PullTypeResolver.prototype.cachedIArgumentsInterfaceType = function () { if (!this._cachedIArgumentsInterfaceType) { - this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */); + this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedIArgumentsInterfaceType && !this._cachedIArgumentsInterfaceType.isResolved) { @@ -38875,7 +39626,7 @@ var TypeScript; PullTypeResolver.prototype.cachedRegExpInterfaceType = function () { if (!this._cachedRegExpInterfaceType) { - this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */); + this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedRegExpInterfaceType && !this._cachedRegExpInterfaceType.isResolved) { @@ -38888,10 +39639,10 @@ var TypeScript; PullTypeResolver.prototype.cachedFunctionArgumentsSymbol = function () { if (!this._cachedFunctionArgumentsSymbol) { this._cachedFunctionArgumentsSymbol = new TypeScript.PullSymbol("arguments", 512 /* Variable */); - this._cachedFunctionArgumentsSymbol.type = this.cachedIArgumentsInterfaceType() ? this.cachedIArgumentsInterfaceType() : this.semanticInfoChain.anyTypeSymbol; + this._cachedFunctionArgumentsSymbol.type = this.cachedIArgumentsInterfaceType() || this.semanticInfoChain.anyTypeSymbol; this._cachedFunctionArgumentsSymbol.setResolved(); - var functionArgumentsDecl = new TypeScript.PullSynthesizedDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, null, new TypeScript.TextSpan(0, 0), this.semanticInfoChain); + var functionArgumentsDecl = new TypeScript.PullSynthesizedDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, null, this.semanticInfoChain); functionArgumentsDecl.setSymbol(this._cachedFunctionArgumentsSymbol); this._cachedFunctionArgumentsSymbol.addDeclaration(functionArgumentsDecl); } @@ -38899,6 +39650,33 @@ var TypeScript; return this._cachedFunctionArgumentsSymbol; }; + PullTypeResolver.prototype.getApparentType = function (type) { + if (type.isTypeParameter()) { + var baseConstraint = type.getBaseConstraint(this.semanticInfoChain); + if (baseConstraint === this.semanticInfoChain.anyTypeSymbol) { + return this.semanticInfoChain.emptyTypeSymbol; + } else { + type = baseConstraint; + } + } + if (type.isPrimitive()) { + if (type === this.semanticInfoChain.numberTypeSymbol) { + return this.cachedNumberInterfaceType(); + } + if (type === this.semanticInfoChain.booleanTypeSymbol) { + return this.cachedBooleanInterfaceType(); + } + if (type === this.semanticInfoChain.stringTypeSymbol) { + return this.cachedStringInterfaceType(); + } + return type; + } + if (type.isEnum()) { + return this.cachedNumberInterfaceType(); + } + return type; + }; + PullTypeResolver.prototype.setTypeChecked = function (ast, context) { context.setTypeChecked(ast); }; @@ -38948,7 +39726,7 @@ var TypeScript; PullTypeResolver.prototype.getExportedMemberSymbol = function (symbol, parent) { if (!(symbol.kind & (65536 /* Method */ | 4096 /* Property */))) { - var isContainer = (parent.kind & (4 /* Container */ | 32 /* DynamicModule */)) != 0; + var isContainer = (parent.kind & (4 /* Container */ | 32 /* DynamicModule */)) !== 0; var containerType = !isContainer ? parent.getAssociatedContainerType() : parent; if (isContainer && containerType) { @@ -38963,12 +39741,32 @@ var TypeScript; return symbol; }; - PullTypeResolver.prototype.getMemberSymbol = function (symbolName, declSearchKind, parent) { + PullTypeResolver.prototype._getNamedPropertySymbolOfAugmentedType = function (symbolName, parent) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, 68147712 /* SomeValue */, parent); + if (memberSymbol) { + return memberSymbol; + } + + if (this.cachedFunctionInterfaceType() && parent.isFunctionType()) { + memberSymbol = this.cachedFunctionInterfaceType().findMember(symbolName, true); + if (memberSymbol) { + return memberSymbol; + } + } + + if (this.cachedObjectInterfaceType()) { + return this.cachedObjectInterfaceType().findMember(symbolName, true); + } + + return null; + }; + + PullTypeResolver.prototype.getNamedPropertySymbol = function (symbolName, declSearchKind, parent) { var member = null; if (declSearchKind & 68147712 /* SomeValue */) { member = parent.findMember(symbolName, true); - } else if (declSearchKind & 58728539 /* SomeType */) { + } else if (declSearchKind & 58728795 /* SomeType */) { member = parent.findNestedType(symbolName); } else if (declSearchKind & 164 /* SomeContainer */) { member = parent.findNestedContainer(symbolName); @@ -38989,7 +39787,7 @@ var TypeScript; if (declSearchKind & 68147712 /* SomeValue */) { member = parent.findMember(symbolName, true); - } else if (declSearchKind & 58728539 /* SomeType */) { + } else if (declSearchKind & 58728795 /* SomeType */) { member = parent.findNestedType(symbolName); } else if (declSearchKind & 164 /* SomeContainer */) { member = parent.findNestedContainer(symbolName); @@ -39016,12 +39814,12 @@ var TypeScript; return this.getExportedMemberSymbol(member, parent); } - if ((declSearchKind & 58728539 /* SomeType */) != 0 || (declSearchKind & 68147712 /* SomeValue */) != 0) { + if ((declSearchKind & 58728795 /* SomeType */) !== 0 || (declSearchKind & 68147712 /* SomeValue */) !== 0) { childDecls = typeDeclarations[j].searchChildDecls(symbolName, 128 /* TypeAlias */); - if (childDecls.length && childDecls[0].kind == 128 /* TypeAlias */) { + if (childDecls.length && childDecls[0].kind === 128 /* TypeAlias */) { var aliasSymbol = this.getExportedMemberSymbol(childDecls[0].getSymbol(), parent); if (aliasSymbol) { - if ((declSearchKind & 58728539 /* SomeType */) != 0) { + if ((declSearchKind & 58728795 /* SomeType */) !== 0) { var typeSymbol = aliasSymbol.getExportAssignedTypeSymbol(); if (typeSymbol) { return typeSymbol; @@ -39029,9 +39827,12 @@ var TypeScript; } else { var valueSymbol = aliasSymbol.getExportAssignedValueSymbol(); if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); return valueSymbol; } } + + return aliasSymbol; } } } @@ -39040,6 +39841,7 @@ var TypeScript; }; PullTypeResolver.prototype.getSymbolFromDeclPath = function (symbolName, declPath, declSearchKind) { + var _this = this; var symbol = null; var decl = null; @@ -39053,6 +39855,61 @@ var TypeScript; var instanceType = null; var childSymbol = null; + var allowedContainerDeclKind = 4 /* Container */ | 32 /* DynamicModule */; + if (TypeScript.hasFlag(declSearchKind, 67108864 /* EnumMember */)) { + allowedContainerDeclKind |= 64 /* Enum */; + } + + var isAcceptableAlias = function (symbol) { + if (symbol.isAlias()) { + _this.resolveDeclaredSymbol(symbol); + if (TypeScript.hasFlag(declSearchKind, 164 /* SomeContainer */)) { + if (symbol.assignedContainer() || symbol.getExportAssignedContainerSymbol()) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 58728795 /* SomeType */)) { + var type = symbol.getExportAssignedTypeSymbol(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + + var type = symbol.assignedType(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 68147712 /* SomeValue */ & ~67108864 /* EnumMember */)) { + if (symbol.assignedType() && symbol.assignedType().isError()) { + return true; + } else if (symbol.assignedValue() || symbol.getExportAssignedValueSymbol()) { + return true; + } else { + var assignedType = symbol.assignedType(); + if (assignedType && assignedType.isContainer() && assignedType.getInstanceType()) { + return true; + } + + var decls = symbol.getDeclarations(); + var ast = decls[0].ast(); + return ast.moduleReference.kind() === 245 /* ExternalModuleReference */; + } + } + } + + return false; + }; + + var tryFindAlias = function (decl) { + var childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + if (isAcceptableAlias(sym)) { + return sym; + } + } + return null; + }; + for (var i = declPath.length - 1; i >= 0; i--) { decl = declPath[i]; pathDeclKind = decl.kind; @@ -39061,30 +39918,25 @@ var TypeScript; return this.semanticInfoChain.anyTypeSymbol; } - if (pathDeclKind & (4 /* Container */ | 32 /* DynamicModule */)) { + if (pathDeclKind & allowedContainerDeclKind) { childDecls = decl.searchChildDecls(symbolName, declSearchKind); if (childDecls.length) { return childDecls[0].getSymbol(); } + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + if (declSearchKind & 68147712 /* SomeValue */) { instanceSymbol = decl.getSymbol().getInstanceSymbol(); - childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); - - if (childDecls.length) { - var sym = childDecls[0].getSymbol(); - - if (sym.isAlias()) { - return sym; - } - } - if (instanceSymbol) { instanceType = instanceSymbol.type; - childSymbol = this.getMemberSymbol(symbolName, declSearchKind, instanceType); + childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, instanceType); if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { return childSymbol; @@ -39100,12 +39952,12 @@ var TypeScript; declSymbol = decl.getSymbol().type; - var childSymbol = this.getMemberSymbol(symbolName, declSearchKind, declSymbol); + var childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, declSymbol); if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { return childSymbol; } - } else if ((declSearchKind & (58728539 /* SomeType */ | 164 /* SomeContainer */)) || !(pathDeclKind & 8 /* Class */)) { + } else if ((declSearchKind & (58728795 /* SomeType */ | 164 /* SomeContainer */)) || !(pathDeclKind & 8 /* Class */)) { var candidateSymbol = null; if (pathDeclKind === 131072 /* FunctionExpression */ && symbolName === decl.getFunctionExpressionName()) { @@ -39125,23 +39977,26 @@ var TypeScript; return candidateSymbol; } - if (declSearchKind & 68147712 /* SomeValue */) { - childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); - - if (childDecls.length) { - var sym = childDecls[0].getSymbol(); - - if (sym.isAlias()) { - return sym; - } - } + var alias = tryFindAlias(decl); + if (alias) { + return alias; } } } symbol = this.semanticInfoChain.findSymbol([symbolName], declSearchKind); + if (symbol) { + return symbol; + } - return symbol; + if (!TypeScript.hasFlag(declSearchKind, 128 /* TypeAlias */)) { + symbol = this.semanticInfoChain.findSymbol([symbolName], 128 /* TypeAlias */); + if (symbol && isAcceptableAlias(symbol)) { + return symbol; + } + } + + return null; }; PullTypeResolver.prototype.getVisibleDeclsFromDeclPath = function (declPath, declSearchKind) { @@ -39237,7 +40092,7 @@ var TypeScript; PullTypeResolver.prototype.getVisibleDecls = function (enclosingDecl) { var declPath = enclosingDecl.getParentPath(); - var declSearchKind = 58728539 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; return this.getVisibleDeclsFromDeclPath(declPath, declSearchKind); }; @@ -39248,7 +40103,7 @@ var TypeScript; return null; } - var declSearchKind = 58728539 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; var members = contextualTypeSymbol.getAllMembers(declSearchKind, 2 /* externallyVisible */); for (var i = 0; i < members.length; i++) { @@ -39261,7 +40116,7 @@ var TypeScript; PullTypeResolver.prototype.getVisibleMembersFromExpression = function (expression, enclosingDecl, context) { var lhs = this.resolveAST(expression, false, context); - if (isTypesOnlyLocation(expression) && (lhs.kind === 8 /* Class */ || lhs.kind === 16 /* Interface */)) { + if (isTypesOnlyLocation(expression) && (lhs.kind === 8 /* Class */ || lhs.kind === 16 /* Interface */ || lhs.kind === 64 /* Enum */)) { return null; } @@ -39276,13 +40131,6 @@ var TypeScript; lhsType = lhsType.getExportAssignedTypeSymbol(); } - while (lhsType.isTypeParameter()) { - lhsType = lhsType.getConstraint(); - if (!lhsType) { - return null; - } - } - if (this.isAnyOrEquivalent(lhsType)) { return null; } @@ -39307,7 +40155,7 @@ var TypeScript; } } - var declSearchKind = 58728539 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; var members = []; @@ -39318,66 +40166,47 @@ var TypeScript; } } - if (lhsType.isTypeParameter()) { - var constraint = lhsType.getConstraint(); + lhsType = this.getApparentType(lhsType); - if (constraint) { - lhsType = constraint; - members = lhsType.getAllMembers(declSearchKind, 2 /* externallyVisible */); - } - } else { - if (lhs.kind == 67108864 /* EnumMember */) { - lhsType = this.semanticInfoChain.numberTypeSymbol; - } + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); - if (lhsType === this.semanticInfoChain.numberTypeSymbol && this.cachedNumberInterfaceType()) { - lhsType = this.cachedNumberInterfaceType(); - } else if (lhsType === this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { - lhsType = this.cachedStringInterfaceType(); - } else if (lhsType === this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { - lhsType = this.cachedBooleanInterfaceType(); - } - - if (!lhsType.isResolved) { - var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); - - if (potentiallySpecializedType != lhsType) { - if (!lhs.isType()) { - context.setTypeInContext(lhs, potentiallySpecializedType); - } - - lhsType = potentiallySpecializedType; - } - } - - members = lhsType.getAllMembers(declSearchKind, memberVisibilty); - - if (lhsType.isContainer()) { - var associatedInstance = lhsType.getInstanceSymbol(); - if (associatedInstance) { - var instanceType = associatedInstance.type; - this.resolveDeclaredSymbol(instanceType, context); - var instanceMembers = instanceType.getAllMembers(declSearchKind, memberVisibilty); - members = members.concat(instanceMembers); + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); } - var exportedContainer = lhsType.getExportAssignedContainerSymbol(); - if (exportedContainer) { - var exportedContainerMembers = exportedContainer.getAllMembers(declSearchKind, memberVisibilty); - members = members.concat(exportedContainerMembers); - } - } else if (!lhsType.isConstructor()) { - var associatedContainerSymbol = lhsType.getAssociatedContainerType(); - if (associatedContainerSymbol) { - var containerType = associatedContainerSymbol.type; - this.resolveDeclaredSymbol(containerType, context); - var containerMembers = containerType.getAllMembers(declSearchKind, memberVisibilty); - members = members.concat(containerMembers); - } + lhsType = potentiallySpecializedType; } } - if ((lhsType.getCallSignatures().length || lhsType.getConstructSignatures().length) && this.cachedFunctionInterfaceType()) { + members = lhsType.getAllMembers(declSearchKind, memberVisibilty); + + if (lhsType.isContainer()) { + var associatedInstance = lhsType.getInstanceSymbol(); + if (associatedInstance) { + var instanceType = associatedInstance.type; + this.resolveDeclaredSymbol(instanceType, context); + var instanceMembers = instanceType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(instanceMembers); + } + + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + if (exportedContainer) { + var exportedContainerMembers = exportedContainer.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(exportedContainerMembers); + } + } else if (!lhsType.isConstructor() && !lhsType.isEnum()) { + var associatedContainerSymbol = lhsType.getAssociatedContainerType(); + if (associatedContainerSymbol) { + var containerType = associatedContainerSymbol.type; + this.resolveDeclaredSymbol(containerType, context); + var containerMembers = containerType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(containerMembers); + } + } + + if (lhsType.isFunctionType() && this.cachedFunctionInterfaceType()) { members = members.concat(this.cachedFunctionInterfaceType().getAllMembers(declSearchKind, 2 /* externallyVisible */)); } @@ -39456,22 +40285,26 @@ var TypeScript; return symbol; } - if (ast.kind() === 11 /* IdentifierName */ && ast.parent && ast.parent.kind() === 236 /* CatchClause */) { + if (ast.parent && ast.parent.kind() === 236 /* CatchClause */ && ast.parent.identifier === ast) { return symbol; } - var enclosingModule = TypeScript.getEnclosingModuleDeclaration(ast); + if (ast.parent && ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ && ast.parent.identifier === ast) { + return symbol; + } + + var enclosingModule = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(ast); var resolvedSymbol; - if (TypeScript.isAnyNameOfModule(enclosingModule, ast)) { + if (TypeScript.ASTHelpers.isAnyNameOfModule(enclosingModule, ast)) { resolvedSymbol = this.resolveSingleModuleDeclaration(enclosingModule, ast, context); } else if (ast.kind() === 120 /* SourceUnit */ && decl.kind === 32 /* DynamicModule */) { resolvedSymbol = this.resolveModuleSymbol(decl.getSymbol(), context, null, null, ast); } else { - TypeScript.Debug.assert(ast.kind() != 11 /* IdentifierName */ && ast.kind() != 212 /* MemberAccessExpression */); - var resolvedSymbol = this.resolveAST(ast, false, context); + TypeScript.Debug.assert(ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */); + resolvedSymbol = this.resolveAST(ast, false, context); } - if (decl.kind == 2048 /* Parameter */ && !symbol.isResolved && !symbol.type && resolvedSymbol && symbol.anyDeclHasFlag(8388608 /* PropertyParameter */ | 67108864 /* ConstructorParameter */)) { + if (decl.kind === 2048 /* Parameter */ && !symbol.isResolved && !symbol.type && resolvedSymbol && symbol.anyDeclHasFlag(8388608 /* PropertyParameter */ | 67108864 /* ConstructorParameter */)) { symbol.type = resolvedSymbol.type; symbol.setResolved(); } @@ -39480,23 +40313,25 @@ var TypeScript; return symbol; }; + PullTypeResolver.prototype.resolveOtherDecl = function (otherDecl, context) { + var astForOtherDecl = this.getASTForDecl(otherDecl); + var moduleDecl = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(astForOtherDecl); + if (TypeScript.ASTHelpers.isAnyNameOfModule(moduleDecl, astForOtherDecl)) { + this.resolveSingleModuleDeclaration(moduleDecl, astForOtherDecl, context); + } else { + this.resolveAST(astForOtherDecl, false, context); + } + }; + PullTypeResolver.prototype.resolveOtherDeclarations = function (astName, context) { + var _this = this; var resolvedDecl = this.semanticInfoChain.getDeclForAST(astName); var symbol = resolvedDecl.getSymbol(); var allDecls = symbol.getDeclarations(); - for (var i = 0; i < allDecls.length; i++) { - var currentDecl = allDecls[i]; - var astForCurrentDecl = this.getASTForDecl(currentDecl); - if (astForCurrentDecl != astName) { - var moduleDecl = TypeScript.getEnclosingModuleDeclaration(astForCurrentDecl); - if (TypeScript.isAnyNameOfModule(moduleDecl, astForCurrentDecl)) { - this.resolveSingleModuleDeclaration(moduleDecl, astForCurrentDecl, context); - } else { - this.resolveAST(astForCurrentDecl, false, context); - } - } - } + this.inResolvingOtherDeclsWalker.walkOtherPullDecls(resolvedDecl, symbol.getDeclarations(), function (otherDecl) { + return _this.resolveOtherDecl(otherDecl, context); + }); }; PullTypeResolver.prototype.resolveSourceUnit = function (sourceUnit, context) { @@ -39515,9 +40350,26 @@ var TypeScript; }; PullTypeResolver.prototype.typeCheckSourceUnit = function (sourceUnit, context) { + var _this = this; this.setTypeChecked(sourceUnit, context); this.resolveAST(sourceUnit.moduleElements, false, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInSourceUnit(sourceUnit); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInSourceUnit = function (sourceUnit) { + var _this = this; + var enclosingDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + + var doesImportNameExistInOtherFiles = function (name) { + var importSymbol = _this.semanticInfoChain.findTopLevelSymbol(name, 128 /* TypeAlias */, null); + return importSymbol && importSymbol.isAlias(); + }; + + this.checkUniquenessOfImportNames([enclosingDecl], doesImportNameExistInOtherFiles); }; PullTypeResolver.prototype.resolveEnumDeclaration = function (ast, context) { @@ -39552,13 +40404,18 @@ var TypeScript; }; PullTypeResolver.prototype.typeCheckEnumDeclaration = function (ast, context) { + var _this = this; this.setTypeChecked(ast, context); this.resolveAST(ast.enumElements, false, context); var containerDecl = this.semanticInfoChain.getDeclForAST(ast); this.validateVariableDeclarationGroups(containerDecl, context); - if (!TypeScript.enumIsElided(ast)) { + this.typeCheckCallBacks.push(function (context) { + return _this.checkInitializersInEnumDeclarations(containerDecl, context); + }); + + if (!TypeScript.ASTHelpers.enumIsElided(ast)) { this.checkNameForCompilerGeneratedDeclarationCollision(ast, true, ast.identifier, context); } }; @@ -39567,6 +40424,34 @@ var TypeScript; this.checkThisCaptureVariableCollides(ast, true, context); }; + PullTypeResolver.prototype.checkInitializersInEnumDeclarations = function (decl, context) { + var symbol = decl.getSymbol(); + + var declarations = symbol.getDeclarations(); + if (decl !== declarations[0]) { + return; + } + + var seenEnumDeclWithNoFirstMember = false; + for (var i = 0; i < declarations.length; ++i) { + var currentDecl = declarations[i]; + + var ast = currentDecl.ast(); + if (ast.enumElements.nonSeparatorCount() === 0) { + continue; + } + + var firstVariable = ast.enumElements.nonSeparatorAt(0); + if (!firstVariable.equalsValueClause) { + if (!seenEnumDeclWithNoFirstMember) { + seenEnumDeclWithNoFirstMember = true; + } else { + this.semanticInfoChain.addDiagnosticFromAST(firstVariable, TypeScript.DiagnosticCode.In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element); + } + } + } + }; + PullTypeResolver.prototype.resolveModuleDeclaration = function (ast, context) { var result; @@ -39614,7 +40499,7 @@ var TypeScript; this.resolveDeclaredSymbol(instanceSymbol, context); } - var isLastName = TypeScript.isLastNameOfModule(moduleDeclAST, moduleDeclNameAST); + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDeclAST, moduleDeclNameAST); if (isLastName) { this.resolveFirstExportAssignmentStatement(moduleDeclAST.moduleElements, context); } else if (sourceUnitAST) { @@ -39633,7 +40518,7 @@ var TypeScript; PullTypeResolver.prototype.resolveFirstExportAssignmentStatement = function (moduleElements, context) { for (var i = 0, n = moduleElements.childCount(); i < n; i++) { var moduleElement = moduleElements.childAt(i); - if (moduleElement.kind() == 134 /* ExportAssignment */) { + if (moduleElement.kind() === 134 /* ExportAssignment */) { this.resolveExportAssignmentStatement(moduleElement, context); return; } @@ -39659,9 +40544,10 @@ var TypeScript; }; PullTypeResolver.prototype.typeCheckSingleModuleDeclaration = function (ast, astName, context) { + var _this = this; this.setTypeChecked(ast, context); - if (TypeScript.isLastNameOfModule(ast, astName)) { + if (TypeScript.ASTHelpers.isLastNameOfModule(ast, astName)) { this.resolveAST(ast.moduleElements, false, context); } @@ -39674,9 +40560,106 @@ var TypeScript; } } - if (!TypeScript.moduleIsElided(ast) && !ast.stringLiteral) { + if (!TypeScript.ASTHelpers.moduleIsElided(ast) && !ast.stringLiteral) { this.checkNameForCompilerGeneratedDeclarationCollision(astName, true, astName, context); } + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInModule(containerDecl); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInModule = function (decl) { + var symbol = decl.getSymbol(); + if (!symbol) { + return; + } + + var decls = symbol.getDeclarations(); + + if (decls[0] !== decl) { + return; + } + + this.checkUniquenessOfImportNames(decls); + }; + + PullTypeResolver.prototype.checkUniquenessOfImportNames = function (decls, doesNameExistOutside) { + var _this = this; + var importDeclarationNames; + + for (var i = 0; i < decls.length; ++i) { + var childDecls = decls[i].getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[childDecl.name] = true; + } + } + } + + if (!importDeclarationNames && !doesNameExistOutside) { + return; + } + + for (var i = 0; i < decls.length; ++i) { + this.scanVariableDeclarationGroups(decls[i], function (firstDeclInGroup) { + var nameConflict = importDeclarationNames && importDeclarationNames[firstDeclInGroup.name]; + if (!nameConflict) { + nameConflict = doesNameExistOutside && doesNameExistOutside(firstDeclInGroup.name); + if (nameConflict) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[firstDeclInGroup.name] = true; + } + } + + if (nameConflict) { + _this.semanticInfoChain.addDiagnosticFromAST(firstDeclInGroup.ast(), TypeScript.DiagnosticCode.Variable_declaration_cannot_have_the_same_name_as_an_import_declaration); + } + }); + } + }; + + PullTypeResolver.prototype.scanVariableDeclarationGroups = function (enclosingDecl, firstDeclHandler, subsequentDeclHandler) { + var declGroups = enclosingDecl.getVariableDeclGroups(); + + for (var i = 0; i < declGroups.length; i++) { + var firstSymbol = null; + var enclosingDeclForFirstSymbol = null; + + if (enclosingDecl.kind === 1 /* Script */ && declGroups[i].length) { + var name = declGroups[i][0].name; + var candidateSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 512 /* Variable */, enclosingDecl); + if (candidateSymbol && candidateSymbol.isResolved) { + if (!candidateSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */)) { + firstSymbol = candidateSymbol; + } + } + } + + for (var j = 0; j < declGroups[i].length; j++) { + var decl = declGroups[i][j]; + + var name = decl.name; + + var symbol = decl.getSymbol(); + + if (j === 0) { + firstDeclHandler(decl); + if (!subsequentDeclHandler) { + break; + } + + if (!firstSymbol || !firstSymbol.type) { + firstSymbol = symbol; + continue; + } + } + + subsequentDeclHandler(decl, firstSymbol); + } + } }; PullTypeResolver.prototype.postTypeCheckModuleDeclaration = function (ast, context) { @@ -39684,12 +40667,12 @@ var TypeScript; }; PullTypeResolver.prototype.isTypeRefWithoutTypeArgs = function (term) { - if (term.kind() == 11 /* IdentifierName */) { + if (term.kind() === 11 /* IdentifierName */) { return true; - } else if (term.kind() == 121 /* QualifiedName */) { + } else if (term.kind() === 121 /* QualifiedName */) { var binex = term; - if (binex.right.kind() == 11 /* IdentifierName */) { + if (binex.right.kind() === 11 /* IdentifierName */) { return true; } } @@ -39719,7 +40702,7 @@ var TypeScript; var enclosingDecl = this.getEnclosingDecl(typeDecl); var typeDeclSymbol = typeDecl.getSymbol(); var typeDeclIsClass = classOrInterface.kind() === 131 /* ClassDeclaration */; - var hasVisited = this.getSymbolForAST(classOrInterface, context) != null; + var hasVisited = this.getSymbolForAST(classOrInterface, context) !== null; if ((typeDeclSymbol.isResolved && hasVisited) || (typeDeclSymbol.inResolution && !context.isInBaseTypeResolution())) { return typeDeclSymbol; @@ -39728,13 +40711,6 @@ var TypeScript; var wasResolving = typeDeclSymbol.inResolution; typeDeclSymbol.startResolving(); - if (!typeDeclSymbol.isResolved) { - var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); - for (var i = 0; i < typeDeclTypeParameters.length; i++) { - this.resolveDeclaredSymbol(typeDeclTypeParameters[i], context); - } - } - var typeRefDecls = typeDeclSymbol.getDeclarations(); for (var i = 0; i < typeRefDecls.length; i++) { @@ -39745,13 +40721,20 @@ var TypeScript; } } + if (!typeDeclSymbol.isResolved) { + var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); + for (var i = 0; i < typeDeclTypeParameters.length; i++) { + this.resolveDeclaredSymbol(typeDeclTypeParameters[i], context); + } + } + var wasInBaseTypeResolution = context.startBaseTypeResolution(); if (!typeDeclIsClass && !hasVisited) { typeDeclSymbol.resetKnownBaseTypeCount(); } - var extendsClause = TypeScript.getExtendsHeritageClause(heritageClauses); + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); if (extendsClause) { for (var i = typeDeclSymbol.getKnownBaseTypeCount(); i < extendsClause.typeNames.nonSeparatorCount(); i = typeDeclSymbol.getKnownBaseTypeCount()) { typeDeclSymbol.incrementKnownBaseCount(); @@ -39775,7 +40758,7 @@ var TypeScript; } } - var implementsClause = TypeScript.getImplementsHeritageClause(heritageClauses); + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); if (implementsClause && typeDeclIsClass) { var extendsCount = extendsClause ? extendsClause.typeNames.nonSeparatorCount() : 0; for (var i = typeDeclSymbol.getKnownBaseTypeCount(); ((i - extendsCount) >= 0) && ((i - extendsCount) < implementsClause.typeNames.nonSeparatorCount()); i = typeDeclSymbol.getKnownBaseTypeCount()) { @@ -39801,7 +40784,7 @@ var TypeScript; typeDeclSymbol.inResolution = false; this.typeCheckCallBacks.push(function (context) { - if (classOrInterface.kind() == 131 /* ClassDeclaration */) { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { _this.resolveClassDeclaration(classOrInterface, context); } else { _this.resolveInterfaceDeclaration(classOrInterface, context); @@ -39811,25 +40794,6 @@ var TypeScript; return typeDeclSymbol; } - if (!typeDeclSymbol.isResolved) { - if (!typeDeclIsClass) { - var callSignatures = typeDeclSymbol.getCallSignatures(); - for (var i = 0; i < callSignatures.length; i++) { - this.resolveDeclaredSymbol(callSignatures[i], context); - } - - var constructSignatures = typeDeclSymbol.getConstructSignatures(); - for (var i = 0; i < constructSignatures.length; i++) { - this.resolveDeclaredSymbol(constructSignatures[i], context); - } - - var indexSignatures = typeDeclSymbol.getIndexSignatures(); - for (var i = 0; i < indexSignatures.length; i++) { - this.resolveDeclaredSymbol(indexSignatures[i], context); - } - } - } - this.setSymbolForAST(name, typeDeclSymbol, context); this.setSymbolForAST(classOrInterface, typeDeclSymbol, context); @@ -39841,6 +40805,7 @@ var TypeScript; PullTypeResolver.prototype.resolveClassDeclaration = function (classDeclAST, context) { var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); var classDeclSymbol = classDecl.getSymbol(); + if (!classDeclSymbol.isResolved) { this.resolveReferenceTypeDeclaration(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, context); @@ -39869,15 +40834,9 @@ var TypeScript; if (!parentConstructSignatures.length) { parentConstructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); parentConstructSignature.returnType = parentType; - parentConstructorType.addConstructSignature(parentConstructSignature); + parentConstructSignature.addTypeParametersFromReturnType(); + parentConstructorType.appendConstructSignature(parentConstructSignature); parentConstructSignature.addDeclaration(parentType.getDeclarations()[0]); - - var parentTypeParameters = parentConstructorType.getTypeParameters(); - - for (var i = 0; i < parentTypeParameters.length; i++) { - parentConstructSignature.addTypeParameter(parentTypeParameters[i]); - } - parentConstructSignatures = [parentConstructSignature]; } @@ -39885,33 +40844,23 @@ var TypeScript; parentConstructSignature = parentConstructSignatures[i]; parentParameters = parentConstructSignature.parameters; - constructorSignature = parentConstructSignature.isDefinition() ? new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */) : new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + constructorSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */, parentConstructSignature.isDefinition()); constructorSignature.returnType = classDeclSymbol; + constructorSignature.addTypeParametersFromReturnType(); for (var j = 0; j < parentParameters.length; j++) { constructorSignature.addParameter(parentParameters[j], parentParameters[j].isOptional); } - var typeParameters = constructorTypeSymbol.getTypeParameters(); - - for (var j = 0; j < typeParameters.length; j++) { - constructorSignature.addTypeParameter(typeParameters[j]); - } - - constructorTypeSymbol.addConstructSignature(constructorSignature); + constructorTypeSymbol.appendConstructSignature(constructorSignature); constructorSignature.addDeclaration(classDecl); } } else { constructorSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); constructorSignature.returnType = classDeclSymbol; - constructorTypeSymbol.addConstructSignature(constructorSignature); + constructorSignature.addTypeParametersFromReturnType(); + constructorTypeSymbol.appendConstructSignature(constructorSignature); constructorSignature.addDeclaration(classDecl); - - var typeParameters = constructorTypeSymbol.getTypeParameters(); - - for (var i = 0; i < typeParameters.length; i++) { - constructorSignature.addTypeParameter(typeParameters[i]); - } } } @@ -39944,13 +40893,23 @@ var TypeScript; PullTypeResolver.prototype.typeCheckTypeParametersOfTypeDeclaration = function (classOrInterface, context) { var _this = this; - var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); - var typeDeclSymbol = typeDecl.getSymbol(); - var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); - for (var i = 0; i < typeDeclTypeParameters.length; i++) { - this.checkSymbolPrivacy(typeDeclSymbol, typeDeclTypeParameters[i], function (symbol) { - return _this.typeParameterOfTypeDeclarationPrivacyErrorReporter(classOrInterface, i, typeDeclTypeParameters[i], symbol, context); - }); + var typeParametersList = classOrInterface.kind() == 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + if (typeParametersList) { + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var typeDeclSymbol = typeDecl.getSymbol(); + + for (var i = 0; i < typeParametersList.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParametersList.typeParameters.nonSeparatorAt(i); + this.resolveTypeParameterDeclaration(typeParameterAST, context); + + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.checkSymbolPrivacy(typeDeclSymbol, typeParameterSymbol, function (symbol) { + return _this.typeParameterOfTypeDeclarationPrivacyErrorReporter(classOrInterface, typeParameterAST, typeParameterSymbol, symbol, context); + }); + } } }; @@ -39969,6 +40928,8 @@ var TypeScript; if (!classDeclSymbol.hasBaseTypeConflict()) { this.typeCheckMembersAgainstIndexer(classDeclSymbol, classDecl, context); } + + this.checkTypeForDuplicateIndexSignatures(classDeclSymbol); }; PullTypeResolver.prototype.postTypeCheckClassDeclaration = function (classDeclAST, context) { @@ -40025,6 +40986,88 @@ var TypeScript; if (!interfaceDeclSymbol.hasBaseTypeConflict()) { this.typeCheckMembersAgainstIndexer(interfaceDeclSymbol, interfaceDecl, context); } + + var allInterfaceDecls = interfaceDeclSymbol.getDeclarations(); + if (interfaceDecl === allInterfaceDecls[allInterfaceDecls.length - 1]) { + this.checkTypeForDuplicateIndexSignatures(interfaceDeclSymbol); + } + + if (!this.checkInterfaceDeclForIdenticalTypeParameters(interfaceDeclAST, context)) { + this.semanticInfoChain.addDiagnosticFromAST(interfaceDeclAST.identifier, TypeScript.DiagnosticCode.All_declarations_of_an_interface_must_have_identical_type_parameters); + } + }; + + PullTypeResolver.prototype.checkInterfaceDeclForIdenticalTypeParameters = function (interfaceDeclAST, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + if (!interfaceDeclSymbol.isGeneric()) { + return true; + } + + var firstInterfaceDecl = interfaceDeclSymbol.getDeclarations()[0]; + if (firstInterfaceDecl == interfaceDecl) { + return true; + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var firstInterfaceDeclTypeParameters = firstInterfaceDecl.getTypeParameters(); + + if (typeParameters.length != firstInterfaceDeclTypeParameters.length) { + return false; + } + + for (var i = 0; i < typeParameters.length; i++) { + var typeParameter = typeParameters[i]; + var firstInterfaceDeclTypeParameter = firstInterfaceDeclTypeParameters[i]; + + if (typeParameter.name != firstInterfaceDeclTypeParameter.name) { + return false; + } + + var typeParameterSymbol = typeParameter.getSymbol(); + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter); + var firstInterfaceDeclTypeParameterAST = this.semanticInfoChain.getASTForDecl(firstInterfaceDeclTypeParameter); + + if (!!typeParameterAST.constraint != !!firstInterfaceDeclTypeParameterAST.constraint) { + return false; + } + + if (typeParameterAST.constraint) { + var typeParameterConstraint = this.resolveAST(typeParameterAST.constraint, false, context); + if (!this.typesAreIdenticalWithNewEnclosingTypes(typeParameterConstraint, typeParameterSymbol.getConstraint(), context)) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.checkTypeForDuplicateIndexSignatures = function (enclosingTypeSymbol) { + var indexSignatures = enclosingTypeSymbol.getOwnIndexSignatures(); + var firstStringIndexer = null; + var firstNumberIndexer = null; + for (var i = 0; i < indexSignatures.length; i++) { + var currentIndexer = indexSignatures[i]; + var currentParameterType = currentIndexer.parameters[0].type; + TypeScript.Debug.assert(currentParameterType); + if (currentParameterType === this.semanticInfoChain.stringTypeSymbol) { + if (firstStringIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_string_index_signature, null, [this.semanticInfoChain.locationFromAST(firstStringIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstStringIndexer = currentIndexer; + } + } else if (currentParameterType === this.semanticInfoChain.numberTypeSymbol) { + if (firstNumberIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_number_index_signature, null, [this.semanticInfoChain.locationFromAST(firstNumberIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstNumberIndexer = currentIndexer; + } + } + } }; PullTypeResolver.prototype.filterSymbol = function (symbol, kind, enclosingDecl, context) { @@ -40039,7 +41082,7 @@ var TypeScript; var alias = symbol; if (kind & 164 /* SomeContainer */) { return alias.getExportAssignedContainerSymbol(); - } else if (kind & 58728539 /* SomeType */) { + } else if (kind & 58728795 /* SomeType */) { return alias.getExportAssignedTypeSymbol(); } else if (kind & 68147712 /* SomeValue */) { return alias.getExportAssignedValueSymbol(); @@ -40050,7 +41093,7 @@ var TypeScript; }; PullTypeResolver.prototype.getMemberSymbolOfKind = function (symbolName, kind, pullTypeSymbol, enclosingDecl, context) { - var memberSymbol = this.getMemberSymbol(symbolName, kind, pullTypeSymbol); + var memberSymbol = this.getNamedPropertySymbol(symbolName, kind, pullTypeSymbol); return { symbol: this.filterSymbol(memberSymbol, kind, enclosingDecl, context), @@ -40074,11 +41117,11 @@ var TypeScript; var acceptableAlias = true; if (containerSymbol) { - acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) != 0; + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; aliasSymbol = memberSymbol.aliasSymbol; } - if (!acceptableAlias && containerSymbol && containerSymbol.kind == 128 /* TypeAlias */) { + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { this.resolveDeclaredSymbol(containerSymbol, context); var aliasedAssignedValue = containerSymbol.getExportAssignedValueSymbol(); var aliasedAssignedType = containerSymbol.getExportAssignedTypeSymbol(); @@ -40109,7 +41152,7 @@ var TypeScript; } if (!typeSymbol) { - memberSymbol = this.getMemberSymbolOfKind(rhsName, 58728539 /* SomeType */, moduleTypeSymbol, enclosingDecl, context); + memberSymbol = this.getMemberSymbolOfKind(rhsName, 58728795 /* SomeType */, moduleTypeSymbol, enclosingDecl, context); typeSymbol = memberSymbol.symbol; if (typeSymbol && memberSymbol.aliasSymbol) { aliasSymbol = memberSymbol.aliasSymbol; @@ -40134,12 +41177,12 @@ var TypeScript; }; PullTypeResolver.prototype.resolveModuleReference = function (importDecl, moduleNameExpr, enclosingDecl, context, declPath) { - TypeScript.Debug.assert(moduleNameExpr.kind() == 121 /* QualifiedName */ || moduleNameExpr.kind() == 11 /* IdentifierName */ || moduleNameExpr.kind() === 14 /* StringLiteral */, "resolving module reference should always be either name or member reference"); + TypeScript.Debug.assert(moduleNameExpr.kind() === 121 /* QualifiedName */ || moduleNameExpr.kind() === 11 /* IdentifierName */ || moduleNameExpr.kind() === 14 /* StringLiteral */, "resolving module reference should always be either name or member reference"); var moduleSymbol = null; var moduleName; - if (moduleNameExpr.kind() == 121 /* QualifiedName */) { + if (moduleNameExpr.kind() === 121 /* QualifiedName */) { var dottedNameAST = moduleNameExpr; var moduleContainer = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); if (moduleContainer) { @@ -40161,6 +41204,8 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(moduleNameExpr, moduleSymbol); if (resolvedModuleNameSymbol.isAlias()) { this.semanticInfoChain.setAliasSymbolForAST(moduleNameExpr, resolvedModuleNameSymbol); + var importDeclSymbol = importDecl.getSymbol(); + importDeclSymbol.addLinkedAliasSymbol(resolvedModuleNameSymbol); } } else { this.semanticInfoChain.addDiagnosticFromAST(moduleNameExpr, TypeScript.DiagnosticCode.Unable_to_resolve_module_reference_0, [valueText]); @@ -40181,6 +41226,7 @@ var TypeScript; var declPath = enclosingDecl.getParentPath(); var aliasedType = null; + var importDeclSymbol = importDecl.getSymbol(); if (aliasExpr.kind() === 11 /* IdentifierName */ || aliasExpr.kind() === 14 /* StringLiteral */) { var moduleSymbol = this.resolveModuleReference(importDecl, aliasExpr, enclosingDecl, context, declPath); @@ -40192,19 +41238,17 @@ var TypeScript; var valueSymbol = this.getSymbolFromDeclPath(moduleName, declPath, 68147712 /* SomeValue */); var instanceSymbol = aliasedType.getInstanceSymbol(); - if (valueSymbol && (instanceSymbol != valueSymbol || valueSymbol.type == aliasedType)) { + if (valueSymbol && (instanceSymbol != valueSymbol || valueSymbol.type === aliasedType)) { var text = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.text() : aliasExpr.text(); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(aliasExpr, TypeScript.DiagnosticCode.Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1, [text, moduleSymbol.type.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); } else { - var importDeclSymbol = importDecl.getSymbol(); importDeclSymbol.setAssignedValueSymbol(valueSymbol); } } } else { - aliasedType = this.semanticInfoChain.anyTypeSymbol; + aliasedType = this.getNewErrorTypeSymbol(); } - } else if (aliasExpr.kind() == 121 /* QualifiedName */) { - var importDeclSymbol = importDecl.getSymbol(); + } else if (aliasExpr.kind() === 121 /* QualifiedName */) { var dottedNameAST = aliasExpr; var moduleSymbol = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); if (moduleSymbol) { @@ -40214,14 +41258,13 @@ var TypeScript; importDeclSymbol.setAssignedTypeSymbol(identifierResolution.typeSymbol); importDeclSymbol.setAssignedContainerSymbol(identifierResolution.containerSymbol); this.semanticInfoChain.setAliasSymbolForAST(moduleReference, identifierResolution.aliasSymbol); - if (identifierResolution.valueSymbol) { - importDeclSymbol.setIsUsedAsValue(true); - } return null; } } + } - importDeclSymbol.setAssignedTypeSymbol(this.semanticInfoChain.anyTypeSymbol); + if (!aliasedType) { + importDeclSymbol.setAssignedTypeSymbol(this.getNewErrorTypeSymbol()); } return aliasedType; @@ -40249,7 +41292,7 @@ var TypeScript; if (!aliasedType) { var path = importStatementAST.moduleReference.stringLiteral.text(); this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Unable_to_resolve_external_module_0, [path]); - aliasedType = this.semanticInfoChain.anyTypeSymbol; + aliasedType = this.getNewErrorTypeSymbol(); } } else { aliasedType = this.resolveInternalModuleReference(importStatementAST, context); @@ -40258,9 +41301,9 @@ var TypeScript; if (aliasedType) { if (!aliasedType.isContainer()) { this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Module_cannot_be_aliased_to_a_non_module_type); - aliasedType = this.semanticInfoChain.anyTypeSymbol; - } else if (aliasedType.getExportAssignedValueSymbol()) { - importDeclSymbol.setIsUsedAsValue(true); + if (!aliasedType.isError()) { + aliasedType = this.getNewErrorTypeSymbol(); + } } if (aliasedType.isContainer()) { @@ -40277,6 +41320,14 @@ var TypeScript; this.resolveDeclaredSymbol(importDeclSymbol.assignedType(), context); this.resolveDeclaredSymbol(importDeclSymbol.assignedContainer(), context); + if (aliasedType && importDeclSymbol.anyDeclHasFlag(1 /* Exported */)) { + importDeclSymbol.setIsUsedInExportedAlias(); + + if (aliasedType.isContainer() && aliasedType.getExportAssignedValueSymbol()) { + importDeclSymbol.setIsUsedAsValue(); + } + } + if (this.canTypeCheckAST(importStatementAST, context)) { this.typeCheckImportDeclaration(importStatementAST, context); } @@ -40299,7 +41350,7 @@ var TypeScript; var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); if (enclosingDecl.kind === 32 /* DynamicModule */) { - var ast = TypeScript.getEnclosingModuleDeclaration(this.getASTForDecl(enclosingDecl)); + var ast = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(this.getASTForDecl(enclosingDecl)); if (ast && ast.kind() === 130 /* ModuleDeclaration */) { if (TypeScript.isRelative(modPath)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name)); @@ -40312,7 +41363,7 @@ var TypeScript; if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); var container = containerSymbol ? containerSymbol.getContainer() : null; - if (container && container.kind == 32 /* DynamicModule */) { + if (container && container.kind === 32 /* DynamicModule */) { checkPrivacy = true; } } else { @@ -40330,7 +41381,7 @@ var TypeScript; context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); }); - if (typeSymbol != containerSymbol) { + if (typeSymbol !== containerSymbol) { this.checkSymbolPrivacy(importDeclSymbol, typeSymbol, function (symbol) { var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1; @@ -40348,14 +41399,18 @@ var TypeScript; } } - if (getCompilerReservedName(importStatementAST.identifier)) { - this.postTypeCheckWorkitems.push(importStatementAST); - } + this.checkNameForCompilerGeneratedDeclarationCollision(importStatementAST, true, importStatementAST.identifier, context); }; PullTypeResolver.prototype.postTypeCheckImportDeclaration = function (importStatementAST, context) { - if (TypeScript.importDeclarationIsElided(importStatementAST, this.semanticInfoChain)) { - this.checkNameForCompilerGeneratedDeclarationCollision(importStatementAST, true, importStatementAST.identifier, context, true); + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var importSymbol = importDecl.getSymbol(); + + var isUsedAsValue = importSymbol.isUsedAsValue(); + var hasAssignedValue = importStatementAST.moduleReference.kind() !== 245 /* ExternalModuleReference */ && importSymbol.getExportAssignedValueSymbol() !== null; + + if (isUsedAsValue || hasAssignedValue) { + this.checkThisCaptureVariableCollides(importStatementAST, true, context); } }; @@ -40384,10 +41439,10 @@ var TypeScript; var acceptableAlias = true; if (containerSymbol) { - acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) != 0; + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; } - if (!acceptableAlias && containerSymbol && containerSymbol.kind == 128 /* TypeAlias */) { + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { this.resolveDeclaredSymbol(containerSymbol, context); var aliasSymbol = containerSymbol; @@ -40399,7 +41454,10 @@ var TypeScript; valueSymbol = aliasedAssignedValue; typeSymbol = aliasedAssignedType; containerSymbol = aliasedAssignedContainer; - aliasSymbol.setTypeUsedExternally(true); + aliasSymbol.setTypeUsedExternally(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + } acceptableAlias = true; } } @@ -40413,7 +41471,7 @@ var TypeScript; valueSymbol = this.getSymbolFromDeclPath(id, declPath, 68147712 /* SomeValue */); } if (!typeSymbol) { - typeSymbol = this.getSymbolFromDeclPath(id, declPath, 58728539 /* SomeType */); + typeSymbol = this.getSymbolFromDeclPath(id, declPath, 58728795 /* SomeType */); } if (!valueSymbol && !typeSymbol && !containerSymbol) { @@ -40477,28 +41535,32 @@ var TypeScript; var paramSymbol = paramDecl.getSymbol(); if (argDeclAST.typeAnnotation) { - var typeRef = this.resolveTypeReference(TypeScript.getType(argDeclAST), context); + var typeRef = this.resolveTypeReference(TypeScript.ASTHelpers.getType(argDeclAST), context); if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { - var diagnostic = context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); typeRef = this.getNewErrorTypeSymbol(); } context.setTypeInContext(paramSymbol, typeRef); } else { - if (paramSymbol.isVarArg && paramSymbol.type) { + if (paramSymbol.isVarArg) { if (this.cachedArrayInterfaceType()) { - context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [paramSymbol.type])); + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); } else { - context.setTypeInContext(paramSymbol, paramSymbol.type); + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); } } else { context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); - - if (this.compilationSettings.noImplicitAny()) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_function_type_implicitly_has_an_any_type, [argDeclAST.identifier.text()])); - } } + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_function_type_implicitly_has_an_any_type, [argDeclAST.identifier.text()])); + } + } + + if (TypeScript.hasFlag(paramDecl.flags, 128 /* Optional */) && argDeclAST.equalsValueClause && isTypesOnlyLocation(argDeclAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); } paramSymbol.setResolved(); @@ -40521,22 +41583,29 @@ var TypeScript; contextualType = typeRef || contextualType; } if (contextualType) { + if (context.isInferentiallyTyping()) { + contextualType = context.fixAllTypeParametersReferencedByType(contextualType, this); + } context.setTypeInContext(paramSymbol, contextualType); - } else if (paramSymbol.isVarArg && this.cachedArrayInterfaceType()) { - context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } isImplicitAny = true; } var canTypeCheckAST = this.canTypeCheckAST(argDeclAST, context); if (equalsValueClause && (canTypeCheckAST || !contextualType)) { if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.propagateContextualType(contextualType); } - var initExprSymbol = this.resolveAST(equalsValueClause, contextualType != null, context); + var initExprSymbol = this.resolveAST(equalsValueClause, contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); } if (!initExprSymbol || !initExprSymbol.type) { @@ -40548,7 +41617,7 @@ var TypeScript; } else { var initTypeSymbol = this.getInstanceTypeForAssignment(argDeclAST, initExprSymbol.type, context); if (!contextualType) { - context.setTypeInContext(paramSymbol, this.widenType(initTypeSymbol, equalsValueClause, context)); + context.setTypeInContext(paramSymbol, initTypeSymbol.widenedType(this, equalsValueClause, context)); isImplicitAny = initTypeSymbol !== paramSymbol.type; } else { var comparisonInfo = new TypeComparisonInfo(); @@ -40588,42 +41657,31 @@ var TypeScript; paramSymbol.setResolved(); }; - PullTypeResolver.prototype.checkNameForCompilerGeneratedDeclarationCollision = function (astWithName, isDeclaration, name, context, immediateThisCheck) { + PullTypeResolver.prototype.checkNameForCompilerGeneratedDeclarationCollision = function (astWithName, isDeclaration, name, context) { var compilerReservedName = getCompilerReservedName(name); - if (compilerReservedName) { - switch (compilerReservedName) { - case 1 /* _this */: - if (immediateThisCheck) { - this.checkThisCaptureVariableCollides(astWithName, isDeclaration, context); - } else { - this.postTypeCheckWorkitems.push(astWithName); - } - return; + switch (compilerReservedName) { + case 1 /* _this */: + this.postTypeCheckWorkitems.push(astWithName); + return; - case 2 /* _super */: - this.checkSuperCaptureVariableCollides(astWithName, isDeclaration, context); - return; + case 2 /* _super */: + this.checkSuperCaptureVariableCollides(astWithName, isDeclaration, context); + return; - case 3 /* arguments */: - this.checkArgumentsCollides(astWithName, context); - return; + case 3 /* arguments */: + this.checkArgumentsCollides(astWithName, context); + return; - case 4 /* _i */: - if (isDeclaration) { - this.checkIndexOfRestArgumentInitializationCollides(astWithName, context); - } - return; + case 4 /* _i */: + this.checkIndexOfRestArgumentInitializationCollides(astWithName, isDeclaration, context); + return; - case 5 /* require */: - case 6 /* exports */: - if (isDeclaration) { - this.checkExternalModuleRequireExportsCollides(astWithName, name, context); - } - return; - - default: - TypeScript.Debug.fail("Unknown compiler reserved name: " + name.text()); - } + case 5 /* require */: + case 6 /* exports */: + if (isDeclaration) { + this.checkExternalModuleRequireExportsCollides(astWithName, name, context); + } + return; } }; @@ -40631,16 +41689,16 @@ var TypeScript; var enclosingAST = this.getASTForDecl(someFunctionDecl); var nodeType = enclosingAST.kind(); - if (nodeType == 129 /* FunctionDeclaration */) { + if (nodeType === 129 /* FunctionDeclaration */) { var functionDeclaration = enclosingAST; - return !TypeScript.hasFlag(someFunctionDecl.kind == 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && functionDeclaration.block && TypeScript.lastParameterIsRest(functionDeclaration.callSignature.parameterList); + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && functionDeclaration.block && TypeScript.lastParameterIsRest(functionDeclaration.callSignature.parameterList); } else if (nodeType === 135 /* MemberFunctionDeclaration */) { var memberFunction = enclosingAST; - return !TypeScript.hasFlag(someFunctionDecl.kind == 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && memberFunction.block && TypeScript.lastParameterIsRest(memberFunction.callSignature.parameterList); - } else if (nodeType == 137 /* ConstructorDeclaration */) { + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && memberFunction.block && TypeScript.lastParameterIsRest(memberFunction.callSignature.parameterList); + } else if (nodeType === 137 /* ConstructorDeclaration */) { var constructorDeclaration = enclosingAST; - return !TypeScript.hasFlag(someFunctionDecl.getParentDecl().flags, 8 /* Ambient */) && constructorDeclaration.block && TypeScript.lastParameterIsRest(constructorDeclaration.parameterList); - } else if (nodeType == 218 /* ParenthesizedArrowFunctionExpression */) { + return !TypeScript.hasFlag(someFunctionDecl.getParentDecl().flags, 8 /* Ambient */) && constructorDeclaration.block && TypeScript.lastParameterIsRest(constructorDeclaration.callSignature.parameterList); + } else if (nodeType === 218 /* ParenthesizedArrowFunctionExpression */) { var arrowFunctionExpression = enclosingAST; return TypeScript.lastParameterIsRest(arrowFunctionExpression.callSignature.parameterList); } else if (nodeType === 222 /* FunctionExpression */) { @@ -40652,7 +41710,7 @@ var TypeScript; }; PullTypeResolver.prototype.checkArgumentsCollides = function (ast, context) { - if (ast.kind() == 242 /* Parameter */) { + if (ast.kind() === 242 /* Parameter */) { var enclosingDecl = this.getEnclosingDeclForAST(ast); if (TypeScript.hasFlag(enclosingDecl.kind, 1032192 /* SomeFunction */)) { if (this.hasRestParameterCodeGen(enclosingDecl)) { @@ -40662,12 +41720,33 @@ var TypeScript; } }; - PullTypeResolver.prototype.checkIndexOfRestArgumentInitializationCollides = function (ast, context) { - if (ast.kind() == 242 /* Parameter */) { + PullTypeResolver.prototype.checkIndexOfRestArgumentInitializationCollides = function (ast, isDeclaration, context) { + if (!isDeclaration || ast.kind() === 242 /* Parameter */) { var enclosingDecl = this.getEnclosingDeclForAST(ast); - if (TypeScript.hasFlag(enclosingDecl.kind, 1032192 /* SomeFunction */)) { - if (this.hasRestParameterCodeGen(enclosingDecl)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter)); + var declPath = isDeclaration ? [enclosingDecl] : (enclosingDecl ? enclosingDecl.getParentPath() : []); + var resolvedSymbol = null; + var resolvedSymbolContainer; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (!isDeclaration) { + if (!resolvedSymbol) { + resolvedSymbol = this.resolveNameExpression(ast, context); + if (resolvedSymbol.isError()) { + return; + } + + resolvedSymbolContainer = resolvedSymbol.getContainer(); + } + + if (resolvedSymbolContainer && TypeScript.ArrayUtilities.contains(resolvedSymbolContainer.getDeclarations(), decl)) { + break; + } + } + + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter)); + } } } } @@ -40676,12 +41755,12 @@ var TypeScript; PullTypeResolver.prototype.checkExternalModuleRequireExportsCollides = function (ast, name, context) { var enclosingDecl = this.getEnclosingDeclForAST(ast); - var enclosingModule = TypeScript.getEnclosingModuleDeclaration(name); - if (TypeScript.isAnyNameOfModule(enclosingModule, name)) { + var enclosingModule = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(name); + if (TypeScript.ASTHelpers.isAnyNameOfModule(enclosingModule, name)) { enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); } - if (enclosingDecl && enclosingDecl.kind == 32 /* DynamicModule */) { + if (enclosingDecl && enclosingDecl.kind === 32 /* DynamicModule */) { var decl = this.semanticInfoChain.getDeclForAST(ast); if (!TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { @@ -40733,6 +41812,7 @@ var TypeScript; var objectTypeSymbol = objectTypeDecl.getSymbol(); this.typeCheckMembersAgainstIndexer(objectTypeSymbol, objectTypeDecl, context); + this.checkTypeForDuplicateIndexSignatures(objectTypeSymbol); }; PullTypeResolver.prototype.resolveTypeAnnotation = function (typeAnnotation, context) { @@ -40749,11 +41829,11 @@ var TypeScript; var aliasType = null; var type = this.computeTypeReferenceSymbol(typeRef, context); - if (type.kind == 4 /* Container */) { + if (type.kind === 4 /* Container */) { var container = type; var instanceSymbol = container.getInstanceSymbol(); - if (instanceSymbol && (instanceSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */) || instanceSymbol.kind == 32768 /* ConstructorMethod */)) { + if (instanceSymbol && (instanceSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */) || instanceSymbol.kind === 32768 /* ConstructorMethod */)) { type = instanceSymbol.type.getAssociatedContainerType(); } } @@ -40770,7 +41850,7 @@ var TypeScript; } if (type && !type.isError()) { - if ((type.kind & 58728539 /* SomeType */) === 0) { + if ((type.kind & 58728795 /* SomeType */) === 0) { if (type.kind & 164 /* SomeContainer */) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_cannot_refer_to_container_0, [aliasType ? aliasType.toString() : type.toString()])); } else { @@ -40786,6 +41866,22 @@ var TypeScript; return type; }; + PullTypeResolver.prototype.getArrayType = function (elementType) { + var arraySymbol = elementType.getArrayType(); + + if (!arraySymbol) { + arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + + elementType.setArrayType(arraySymbol); + } + + return arraySymbol; + }; + PullTypeResolver.prototype.computeTypeReferenceSymbol = function (term, context) { switch (term.kind()) { case 60 /* AnyKeyword */: @@ -40820,7 +41916,7 @@ var TypeScript; var stringConstantAST = term; var enclosingDecl = this.getEnclosingDeclForAST(term); typeDeclSymbol = new TypeScript.PullStringConstantTypeSymbol(stringConstantAST.text()); - var decl = new TypeScript.PullSynthesizedDecl(stringConstantAST.text(), stringConstantAST.text(), typeDeclSymbol.kind, null, enclosingDecl, new TypeScript.TextSpan(stringConstantAST.start(), stringConstantAST.width()), enclosingDecl.semanticInfoChain()); + var decl = new TypeScript.PullSynthesizedDecl(stringConstantAST.text(), stringConstantAST.text(), typeDeclSymbol.kind, null, enclosingDecl, enclosingDecl.semanticInfoChain); typeDeclSymbol.addDeclaration(decl); } else if (term.kind() === 127 /* TypeQuery */) { var typeQuery = term; @@ -40839,24 +41935,14 @@ var TypeScript; } if (valueSymbol) { - typeDeclSymbol = valueSymbol.type; + typeDeclSymbol = valueSymbol.type.widenedType(this, typeQueryTerm, context); } else { typeDeclSymbol = this.getNewErrorTypeSymbol(); } } else if (term.kind() === 124 /* ArrayType */) { var arrayType = term; - var underlying = this.computeTypeReferenceSymbol(arrayType.type, context); - var arraySymbol = underlying.getArrayType(); - - if (!arraySymbol) { - arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [underlying]); - - if (!arraySymbol) { - arraySymbol = this.semanticInfoChain.anyTypeSymbol; - } - } - - typeDeclSymbol = arraySymbol; + var underlying = this.resolveTypeReference(arrayType.type, context); + typeDeclSymbol = this.getArrayType(underlying); } else { throw TypeScript.Errors.invalidOperation("unknown type"); } @@ -40879,19 +41965,27 @@ var TypeScript; }; PullTypeResolver.prototype.genericTypeIsUsedWithoutRequiredTypeArguments = function (typeSymbol, term, context) { - return typeSymbol.isNamedTypeSymbol() && typeSymbol.isGeneric() && !typeSymbol.isTypeParameter() && (typeSymbol.isResolved || typeSymbol.inResolution) && !typeSymbol.getIsSpecialized() && typeSymbol.getTypeParameters().length && typeSymbol.getTypeArguments() == null && this.isTypeRefWithoutTypeArgs(term); + if (!typeSymbol) { + return false; + } + + if (typeSymbol.isAlias()) { + return this.genericTypeIsUsedWithoutRequiredTypeArguments(typeSymbol.getExportAssignedTypeSymbol(), term, context); + } + + return typeSymbol.isNamedTypeSymbol() && typeSymbol.isGeneric() && !typeSymbol.isTypeParameter() && (typeSymbol.isResolved || typeSymbol.inResolution) && !typeSymbol.getIsSpecialized() && typeSymbol.getTypeParameters().length && typeSymbol.getTypeArguments() === null && this.isTypeRefWithoutTypeArgs(term); }; PullTypeResolver.prototype.resolveMemberVariableDeclaration = function (varDecl, context) { - return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.getType(varDecl.variableDeclarator), varDecl.variableDeclarator.equalsValueClause, context); + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl.variableDeclarator), varDecl.variableDeclarator.equalsValueClause, context); }; PullTypeResolver.prototype.resolvePropertySignature = function (varDecl, context) { - return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.getType(varDecl), null, context); + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); }; PullTypeResolver.prototype.resolveVariableDeclarator = function (varDecl, context) { - return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.getType(varDecl), varDecl.equalsValueClause, context); + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); }; PullTypeResolver.prototype.resolveParameterList = function (list, context) { @@ -40899,7 +41993,7 @@ var TypeScript; }; PullTypeResolver.prototype.resolveParameter = function (parameter, context) { - return this.resolveVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.getType(parameter), parameter.equalsValueClause, context); + return this.resolveVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); }; PullTypeResolver.prototype.getEnumTypeSymbol = function (enumElement, context) { @@ -40932,7 +42026,7 @@ var TypeScript; var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); - if (enclosingDecl && decl.kind == 2048 /* Parameter */) { + if (enclosingDecl && decl.kind === 2048 /* Parameter */) { enclosingDecl.ensureSymbolIsBound(); } @@ -40970,7 +42064,7 @@ var TypeScript; if (!(hasTypeExpr || init)) { var defaultType = this.semanticInfoChain.anyTypeSymbol; - if (declSymbol.isVarArg) { + if (declSymbol.isVarArg && this.cachedArrayInterfaceType()) { defaultType = this.createInstantiatedType(this.cachedArrayInterfaceType(), [defaultType]); } @@ -41012,7 +42106,7 @@ var TypeScript; } var wrapperDecl = this.getEnclosingDecl(decl); - wrapperDecl = wrapperDecl ? wrapperDecl : enclosingDecl; + wrapperDecl = wrapperDecl || enclosingDecl; var typeExprSymbol = this.resolveTypeReference(typeExpr, context); @@ -41029,7 +42123,7 @@ var TypeScript; context.setTypeInContext(declParameterSymbol, typeExprSymbol); } } else { - if (typeExprSymbol == this.semanticInfoChain.anyTypeSymbol) { + if (typeExprSymbol === this.semanticInfoChain.anyTypeSymbol) { decl.setFlag(16777216 /* IsAnnotatedWithAny */); } @@ -41055,7 +42149,7 @@ var TypeScript; } } } - } else if (declSymbol.isVarArg && !(typeExprSymbol.isArrayNamedTypeReference() || typeExprSymbol == this.cachedArrayInterfaceType())) { + } else if (declSymbol.isVarArg && !(typeExprSymbol.isArrayNamedTypeReference() || typeExprSymbol === this.cachedArrayInterfaceType())) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); typeExprSymbol = this.getNewErrorTypeSymbol(); } @@ -41066,7 +42160,7 @@ var TypeScript; declParameterSymbol.type = typeExprSymbol; } - if (typeExprSymbol.kind == 16777216 /* FunctionType */ && !typeExprSymbol.getFunctionSymbol()) { + if (typeExprSymbol.kind === 16777216 /* FunctionType */ && !typeExprSymbol.getFunctionSymbol()) { typeExprSymbol.setFunctionSymbol(declSymbol); } } @@ -41081,7 +42175,7 @@ var TypeScript; var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; if (typeExprSymbol) { - context.pushContextualType(typeExprSymbol, context.inProvisionalResolution(), null); + context.pushNewContextualType(typeExprSymbol); } var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); @@ -41090,12 +42184,12 @@ var TypeScript; var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; var wrapperDecl = this.getEnclosingDecl(decl); - wrapperDecl = wrapperDecl ? wrapperDecl : enclosingDecl; + wrapperDecl = wrapperDecl || enclosingDecl; - var initExprSymbol = this.resolveAST(init, typeExprSymbol != null, context); + var initExprSymbol = this.resolveAST(init, typeExprSymbol !== null, context); if (typeExprSymbol) { - context.popContextualType(); + context.popAnyContextualType(); } if (!initExprSymbol) { @@ -41110,9 +42204,9 @@ var TypeScript; } } else { var initTypeSymbol = initExprSymbol.type; - var widenedInitTypeSymbol = this.widenType(initTypeSymbol, init.value, context); if (!hasTypeExpr) { + var widenedInitTypeSymbol = initTypeSymbol.widenedType(this, init.value, context); context.setTypeInContext(declSymbol, widenedInitTypeSymbol); if (declParameterSymbol) { @@ -41120,30 +42214,32 @@ var TypeScript; } if (this.compilationSettings.noImplicitAny()) { - if ((widenedInitTypeSymbol != initTypeSymbol) && (widenedInitTypeSymbol == this.semanticInfoChain.anyTypeSymbol)) { + if ((widenedInitTypeSymbol !== initTypeSymbol) && (widenedInitTypeSymbol === this.semanticInfoChain.anyTypeSymbol)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); } } + + return widenedInitTypeSymbol; } } - return widenedInitTypeSymbol; + return initTypeSymbol; }; PullTypeResolver.prototype.typeCheckPropertySignature = function (varDecl, context) { - this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.getType(varDecl), null, context); + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); }; PullTypeResolver.prototype.typeCheckMemberVariableDeclaration = function (varDecl, context) { - this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.getType(varDecl), varDecl.variableDeclarator.equalsValueClause, context); + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.variableDeclarator.equalsValueClause, context); }; PullTypeResolver.prototype.typeCheckVariableDeclarator = function (varDecl, context) { - this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.getType(varDecl), varDecl.equalsValueClause, context); + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); }; PullTypeResolver.prototype.typeCheckParameter = function (parameter, context) { - this.typeCheckVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.getType(parameter), parameter.equalsValueClause, context); + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); }; PullTypeResolver.prototype.typeCheckVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { @@ -41199,7 +42295,7 @@ var TypeScript; } } else if (varDeclOrParameter.kind() !== 243 /* EnumElement */ && this.compilationSettings.noImplicitAny() && !this.isForInVariableDeclarator(varDeclOrParameter)) { var wrapperDecl = this.getEnclosingDecl(decl); - wrapperDecl = wrapperDecl ? wrapperDecl : enclosingDecl; + wrapperDecl = wrapperDecl || enclosingDecl; if ((wrapperDecl.kind === 16384 /* Function */ || wrapperDecl.kind === 32768 /* ConstructorMethod */ || wrapperDecl.kind === 2097152 /* ConstructSignature */)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); @@ -41211,7 +42307,7 @@ var TypeScript; } else if (TypeScript.hasFlag(parentDecl.flags, 8 /* Ambient */) && !TypeScript.hasFlag(wrapperDecl.flags, 2 /* Private */)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); } - } else if (wrapperDecl.kind === 8388608 /* ObjectType */) { + } else if (decl.kind === 4096 /* Property */ && !declSymbol.getContainer().isNamedTypeSymbol()) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Member_0_of_object_type_implicitly_has_an_any_type, [name.text()])); } else if (wrapperDecl.kind !== 268435456 /* CatchBlock */) { if (!TypeScript.hasFlag(wrapperDecl.flags, 8 /* Ambient */)) { @@ -41225,16 +42321,16 @@ var TypeScript; if (init && varDeclOrParameter.kind() === 242 /* Parameter */) { var containerSignature = enclosingDecl.getSignatureSymbol(); if (containerSignature && !containerSignature.isDefinition()) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Default_arguments_are_not_allowed_in_an_overload_parameter)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); } } - if (declSymbol.kind != 2048 /* Parameter */ && (declSymbol.kind != 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { + if (declSymbol.kind !== 2048 /* Parameter */ && (declSymbol.kind !== 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { this.checkSymbolPrivacy(declSymbol, declSymbol.type, function (symbol) { return _this.variablePrivacyErrorReporter(varDeclOrParameter, declSymbol, symbol, context); }); } - if ((declSymbol.kind != 4096 /* Property */ && declSymbol.kind != 67108864 /* EnumMember */) || declSymbol.anyDeclHasFlag(8388608 /* PropertyParameter */)) { + if ((declSymbol.kind !== 4096 /* Property */ && declSymbol.kind !== 67108864 /* EnumMember */) || declSymbol.anyDeclHasFlag(8388608 /* PropertyParameter */)) { this.checkNameForCompilerGeneratedDeclarationCollision(varDeclOrParameter, true, name, context); } }; @@ -41245,15 +42341,14 @@ var TypeScript; PullTypeResolver.prototype.checkSuperCaptureVariableCollides = function (superAST, isDeclaration, context) { var enclosingDecl = this.getEnclosingDeclForAST(superAST); - var declPath = enclosingDecl.getParentPath(); var classSymbol = this.getContextualClassSymbolForEnclosingDecl(superAST, enclosingDecl); if (classSymbol && !classSymbol.anyDeclHasFlag(8 /* Ambient */)) { - if (superAST.kind() == 242 /* Parameter */) { + if (superAST.kind() === 242 /* Parameter */) { var enclosingAST = this.getASTForDecl(enclosingDecl); if (enclosingAST.kind() !== 218 /* ParenthesizedArrowFunctionExpression */ && enclosingAST.kind() !== 219 /* SimpleArrowFunctionExpression */) { - var block = enclosingDecl.kind == 65536 /* Method */ ? enclosingAST.block : enclosingAST.block; + var block = enclosingDecl.kind === 65536 /* Method */ ? enclosingAST.block : enclosingAST.block; if (!block) { return; } @@ -41279,8 +42374,8 @@ var TypeScript; var enclosingDecl = this.getEnclosingDeclForAST(_thisAST); - var enclosingModule = TypeScript.getEnclosingModuleDeclaration(_thisAST); - if (TypeScript.isAnyNameOfModule(enclosingModule, _thisAST)) { + var enclosingModule = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(_thisAST); + if (TypeScript.ASTHelpers.isAnyNameOfModule(enclosingModule, _thisAST)) { enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); } @@ -41310,11 +42405,21 @@ var TypeScript; var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); var typeParameterSymbol = typeParameterDecl.getSymbol(); + this.resolveFirstTypeParameterDeclaration(typeParameterSymbol, context); + + if (typeParameterSymbol.isResolved && this.canTypeCheckAST(typeParameterAST, context)) { + this.typeCheckTypeParameterDeclaration(typeParameterAST, context); + } + + return typeParameterSymbol; + }; + + PullTypeResolver.prototype.resolveFirstTypeParameterDeclaration = function (typeParameterSymbol, context) { + var typeParameterDecl = typeParameterSymbol.getDeclarations()[0]; + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecl); + if (typeParameterSymbol.isResolved || typeParameterSymbol.inResolution) { - if (typeParameterSymbol.isResolved && this.canTypeCheckAST(typeParameterAST, context)) { - this.typeCheckTypeParameterDeclaration(typeParameterAST, context); - } - return typeParameterSymbol; + return; } typeParameterSymbol.startResolving(); @@ -41328,18 +42433,27 @@ var TypeScript; } typeParameterSymbol.setResolved(); - - if (this.canTypeCheckAST(typeParameterAST, context)) { - this.setTypeChecked(typeParameterAST, context); - } - - return typeParameterSymbol; }; PullTypeResolver.prototype.typeCheckTypeParameterDeclaration = function (typeParameterAST, context) { this.setTypeChecked(typeParameterAST, context); - this.resolveAST(typeParameterAST.constraint, false, context); + var constraint = this.resolveAST(typeParameterAST.constraint, false, context); + + if (constraint) { + var typeParametersAST = typeParameterAST.parent; + var typeParameters = []; + for (var i = 0; i < typeParametersAST.nonSeparatorCount(); i++) { + var currentTypeParameterAST = typeParametersAST.nonSeparatorAt(i); + var currentTypeParameterDecl = this.semanticInfoChain.getDeclForAST(currentTypeParameterAST); + var currentTypeParameter = this.semanticInfoChain.getSymbolForDecl(currentTypeParameterDecl); + typeParameters[currentTypeParameter.pullSymbolID] = currentTypeParameter; + } + + if (constraint.wrapsSomeTypeParameter(typeParameters)) { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); + } + } }; PullTypeResolver.prototype.resolveConstraint = function (constraint, context) { @@ -41364,6 +42478,7 @@ var TypeScript; case 219 /* SimpleArrowFunctionExpression */: case 218 /* ParenthesizedArrowFunctionExpression */: case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: go = false; break; @@ -41451,20 +42566,12 @@ var TypeScript; var returnType = bestCommonReturnType; var returnExpression = returnExpressions[returnExpressionSymbols.indexOf(returnType)]; - if (useContextualType && returnType == this.semanticInfoChain.anyTypeSymbol) { - var contextualType = context.getContextualType(); - - if (contextualType) { - returnType = contextualType; - } - } - var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); var functionSymbol = functionDecl.getSymbol(); if (returnType) { var previousReturnType = returnType; - var newReturnType = this.widenType(returnType, returnExpression, context); + var newReturnType = returnType.widenedType(this, returnExpression, context); signature.returnType = newReturnType; if (!TypeScript.ArrayUtilities.contains(returnExpressionSymbols, bestCommonReturnType)) { @@ -41474,7 +42581,7 @@ var TypeScript; if (this.compilationSettings.noImplicitAny()) { if (previousReturnType !== newReturnType && newReturnType === this.semanticInfoChain.anyTypeSymbol) { var functionName = enclosingDecl.name; - if (functionName == "") { + if (functionName === "") { functionName = enclosingDecl.getFunctionExpressionName(); } @@ -41500,28 +42607,26 @@ var TypeScript; var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); - if (funcDeclAST.parameterList) { - for (var i = 0; i < funcDeclAST.parameterList.parameters.nonSeparatorCount(); i++) { - this.resolveAST(funcDeclAST.parameterList.parameters.nonSeparatorAt(i), false, context); - } + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveAST(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), false, context); } this.resolveAST(funcDeclAST.block, false, context); if (funcDecl.getSignatureSymbol() && funcDecl.getSignatureSymbol().isDefinition() && this.enclosingClassIsDerived(funcDecl.getParentDecl())) { if (!this.constructorHasSuperCall(funcDeclAST)) { - context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), 11, TypeScript.DiagnosticCode.Constructors_for_derived_classes_must_contain_a_super_call)); + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.Constructors_for_derived_classes_must_contain_a_super_call)); } else if (this.superCallMustBeFirstStatementInConstructor(funcDecl)) { var firstStatement = this.getFirstStatementOfBlockOrNull(funcDeclAST.block); if (!firstStatement || !this.isSuperInvocationExpressionStatement(firstStatement)) { - context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), 11, TypeScript.DiagnosticCode.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties)); + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties)); } } } this.validateVariableDeclarationGroups(funcDecl, context); - this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.callSignature.parameterList), null, funcDeclAST.block, context); this.typeCheckCallBacks.push(function (context) { _this.typeCheckFunctionOverloads(funcDeclAST, context); @@ -41533,9 +42638,18 @@ var TypeScript; if (constructorDecl.block) { var foundSuperCall = false; var pre = function (ast, walker) { - if (_this.isSuperInvocationExpression(ast)) { - foundSuperCall = true; - walker.options.stopWalking = true; + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + walker.options.goChildren = false; + default: + if (_this.isSuperInvocationExpression(ast)) { + foundSuperCall = true; + walker.options.stopWalking = true; + } } }; @@ -41546,19 +42660,31 @@ var TypeScript; return false; }; - PullTypeResolver.prototype.typeCheckFunctionExpression = function (funcDecl, context) { - this.typeCheckAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.getType(funcDecl), funcDecl.block, null, context); + PullTypeResolver.prototype.typeCheckFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), funcDecl.callSignature.typeAnnotation, funcDecl.block, null, isContextuallyTyped, context); }; PullTypeResolver.prototype.typeCheckCallSignature = function (funcDecl, context) { - this.typeCheckFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.getType(funcDecl), null, context); + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; PullTypeResolver.prototype.typeCheckConstructSignature = function (funcDecl, context) { - this.typeCheckFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), null, context); + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; - PullTypeResolver.prototype.typeCheckFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameters, returnTypeAnnotation, block, context) { + PullTypeResolver.prototype.typeCheckMethodSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberFunctionDeclaration = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.containsSingleThrowStatement = function (block) { + return block !== null && block.statements.childCount() === 1 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */; + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameters, returnTypeAnnotation, block, context) { var _this = this; this.setTypeChecked(funcDeclAST, context); @@ -41578,22 +42704,9 @@ var TypeScript; this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); this.validateVariableDeclarationGroups(funcDecl, context); - this.checkFunctionTypePrivacy(funcDeclAST, isStatic, typeParameters, TypeScript.Parameters.fromParameterList(parameters), returnTypeAnnotation, block, context); + this.checkFunctionTypePrivacy(funcDeclAST, isStatic, typeParameters, TypeScript.ASTHelpers.parametersFromParameterList(parameters), returnTypeAnnotation, block, context); - var signature = funcDecl.getSignatureSymbol(); - - var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) != 0; - - if (funcDeclAST.kind() !== 143 /* ConstructSignature */ && block && returnTypeAnnotation != null && !hasReturn) { - var isVoidOrAny = this.isAnyOrEquivalent(signature.returnType) || signature.returnType === this.semanticInfoChain.voidTypeSymbol; - - if (!isVoidOrAny && !(block.statements.childCount() > 0 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */)) { - var funcName = funcDecl.getDisplayName(); - funcName = funcName ? funcName : "expression"; - - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_0_declared_a_non_void_return_type_but_has_no_return_expression, [funcName])); - } - } + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(funcDecl, returnTypeAnnotation, funcDecl.getSignatureSymbol().returnType, block, context); if (funcDecl.kind === 16384 /* Function */) { this.checkNameForCompilerGeneratedDeclarationCollision(funcDeclAST, true, name, context); @@ -41604,6 +42717,20 @@ var TypeScript; }); }; + PullTypeResolver.prototype.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement = function (functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context) { + var hasReturn = TypeScript.hasFlag(functionDecl.flags, 4194304 /* HasReturnStatement */); + + if (block !== null && returnTypeAnnotation !== null && !hasReturn) { + var isVoidOrAny = this.isAnyOrEquivalent(returnTypeSymbol) || returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol; + + if (!isVoidOrAny && !this.containsSingleThrowStatement(block)) { + var funcName = functionDecl.getDisplayName() || TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_declared_a_non_void_return_type_but_has_no_return_expression)); + } + } + }; + PullTypeResolver.prototype.typeCheckIndexSignature = function (funcDeclAST, context) { var _this = this; this.setTypeChecked(funcDeclAST, context); @@ -41614,16 +42741,16 @@ var TypeScript; var enclosingDecl = this.getEnclosingDecl(funcDecl); - this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.getType(funcDeclAST), context); + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); this.validateVariableDeclarationGroups(funcDecl, context); - this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.Parameters.fromParameter(funcDeclAST.parameter), TypeScript.getType(funcDeclAST), null, context); + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameter(funcDeclAST.parameter), TypeScript.ASTHelpers.getType(funcDeclAST), null, context); var signature = funcDecl.getSignatureSymbol(); this.typeCheckCallBacks.push(function (context) { var parentSymbol = funcDecl.getSignatureSymbol().getContainer(); - var allIndexSignatures = _this.getBothKindsOfIndexSignatures(parentSymbol, context); + var allIndexSignatures = _this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parentSymbol, context); var stringIndexSignature = allIndexSignatures.stringSignature; var numberIndexSignature = allIndexSignatures.numericSignature; var isNumericIndexer = numberIndexSignature === signature; @@ -41631,12 +42758,12 @@ var TypeScript; if (numberIndexSignature && stringIndexSignature && (isNumericIndexer || stringIndexSignature.getDeclarations()[0].getParentDecl() !== numberIndexSignature.getDeclarations()[0].getParentDecl())) { var comparisonInfo = new TypeComparisonInfo(); - if (!_this.sourceIsSubtypeOfTarget(numberIndexSignature.returnType, stringIndexSignature.returnType, funcDeclAST, context, comparisonInfo)) { + if (!_this.sourceIsAssignableToTarget(numberIndexSignature.returnType, stringIndexSignature.returnType, funcDeclAST, context, comparisonInfo)) { var enclosingSymbol = _this.getEnclosingSymbolForAST(funcDeclAST); if (comparisonInfo.message) { - context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_a_subtype_of_string_indexer_type_1_NL_2, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); } else { - context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_a_subtype_of_string_indexer_type_1, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol)])); + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol)])); } } } @@ -41657,7 +42784,7 @@ var TypeScript; if (indexerKindMatchesMemberNameKind || onlyStringIndexerIsPresent) { var comparisonInfo = new TypeComparisonInfo(); - if (!_this.sourceIsSubtypeOfTarget(allMembers[i].type, signature.returnType, funcDeclAST, context, comparisonInfo, false)) { + if (!_this.sourceIsAssignableToTarget(allMembers[i].type, signature.returnType, funcDeclAST, context, comparisonInfo, false)) { _this.reportErrorThatMemberIsNotSubtypeOfIndexer(allMembers[i], signature, funcDeclAST, context, comparisonInfo); } } @@ -41693,35 +42820,35 @@ var TypeScript; }; PullTypeResolver.prototype.resolveMemberFunctionDeclaration = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), funcDecl.block, context); + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); }; PullTypeResolver.prototype.resolveCallSignature = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.getType(funcDecl), null, context); + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; PullTypeResolver.prototype.resolveConstructSignature = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), null, context); + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; PullTypeResolver.prototype.resolveMethodSignature = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), null, context); + return this.resolveFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; PullTypeResolver.prototype.resolveAnyFunctionDeclaration = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), funcDecl.block, context); + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); }; PullTypeResolver.prototype.resolveFunctionExpression = function (funcDecl, isContextuallyTyped, context) { - return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList), TypeScript.getType(funcDecl), funcDecl.block, null, isContextuallyTyped, context); + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, null, isContextuallyTyped, context); }; PullTypeResolver.prototype.resolveSimpleArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { - return this.resolveAnyFunctionExpression(funcDecl, null, TypeScript.Parameters.fromIdentifier(funcDecl.identifier), null, funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + return this.resolveAnyFunctionExpression(funcDecl, null, TypeScript.ASTHelpers.parametersFromIdentifier(funcDecl.identifier), null, funcDecl.block, funcDecl.expression, isContextuallyTyped, context); }; PullTypeResolver.prototype.resolveParenthesizedArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { - return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList), TypeScript.getType(funcDecl), funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, funcDecl.expression, isContextuallyTyped, context); }; PullTypeResolver.prototype.getEnclosingClassDeclaration = function (ast) { @@ -41786,18 +42913,16 @@ var TypeScript; } signature.startResolving(); - if (funcDeclAST.parameterList) { - var prevInTypeCheck = context.inTypeCheck; + var prevInTypeCheck = context.inTypeCheck; - context.inTypeCheck = false; + context.inTypeCheck = false; - for (var i = 0; i < funcDeclAST.parameterList.parameters.nonSeparatorCount(); i++) { - this.resolveParameter(funcDeclAST.parameterList.parameters.nonSeparatorAt(i), context); - } - - context.inTypeCheck = prevInTypeCheck; + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), context); } + context.inTypeCheck = prevInTypeCheck; + if (signature.isGeneric()) { if (funcSymbol) { funcSymbol.type.setHasGenericSignature(); @@ -41855,9 +42980,9 @@ var TypeScript; if (signature.inResolution) { if (funcDeclAST.typeAnnotation) { - var returnTypeSymbol = this.resolveTypeReference(TypeScript.getType(funcDeclAST), context); + var returnTypeSymbol = this.resolveTypeReference(TypeScript.ASTHelpers.getType(funcDeclAST), context); if (!returnTypeSymbol) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(TypeScript.getType(funcDeclAST), TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(TypeScript.ASTHelpers.getType(funcDeclAST), TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); signature.returnType = this.getNewErrorTypeSymbol(); hadError = true; } else { @@ -41891,7 +43016,7 @@ var TypeScript; } if (funcDeclAST.typeAnnotation) { - returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.getType(funcDeclAST), context); + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); if (!returnTypeSymbol) { signature.returnType = this.getNewErrorTypeSymbol(); @@ -41901,16 +43026,6 @@ var TypeScript; } } else { signature.returnType = this.semanticInfoChain.anyTypeSymbol; - var parentDeclFlags = 0 /* None */; - if (TypeScript.hasFlag(funcDecl.kind, 65536 /* Method */) || TypeScript.hasFlag(funcDecl.kind, 32768 /* ConstructorMethod */)) { - var parentDecl = funcDecl.getParentDecl(); - parentDeclFlags = parentDecl.flags; - } - - if (this.compilationSettings.noImplicitAny() && (!TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) || (TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) && !TypeScript.hasFlag(funcDecl.flags, 2 /* Private */)))) { - var funcDeclASTName = name; - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, ["Indexer"])); - } } if (!hadError) { @@ -41949,7 +43064,7 @@ var TypeScript; if (signature) { if (signature.isResolved) { if (this.canTypeCheckAST(funcDeclAST, context)) { - this.typeCheckFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); } return funcSymbol; } @@ -42073,7 +43188,7 @@ var TypeScript; } if (this.canTypeCheckAST(funcDeclAST, context)) { - this.typeCheckFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); } return funcSymbol; @@ -42081,7 +43196,7 @@ var TypeScript; PullTypeResolver.prototype.resolveGetterReturnTypeAnnotation = function (getterFunctionDeclarationAst, enclosingDecl, context) { if (getterFunctionDeclarationAst && getterFunctionDeclarationAst.typeAnnotation) { - return this.resolveTypeReference(TypeScript.getType(getterFunctionDeclarationAst), context); + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), context); } return null; @@ -42090,7 +43205,7 @@ var TypeScript; PullTypeResolver.prototype.resolveSetterArgumentTypeAnnotation = function (setterFunctionDeclarationAst, enclosingDecl, context) { if (setterFunctionDeclarationAst && setterFunctionDeclarationAst.parameterList && setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorCount() > 0) { var parameter = setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorAt(0); - return this.resolveTypeReference(TypeScript.getType(parameter), context); + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(parameter), context); } return null; @@ -42129,7 +43244,7 @@ var TypeScript; accessorSymbol.startResolving(); if (hasGetter) { - getterSymbol = this.resolveGetAccessorDeclaration(getterFunctionDeclarationAst, getterFunctionDeclarationAst.parameterList, TypeScript.getType(getterFunctionDeclarationAst), getterFunctionDeclarationAst.block, setterAnnotatedType, context); + getterSymbol = this.resolveGetAccessorDeclaration(getterFunctionDeclarationAst, getterFunctionDeclarationAst.parameterList, TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), getterFunctionDeclarationAst.block, setterAnnotatedType, context); } if (hasSetter) { @@ -42156,7 +43271,7 @@ var TypeScript; } } - if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol)) { + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { accessorSymbol.type = this.getNewErrorTypeSymbol(); } else { accessorSymbol.type = getterSuppliedTypeSymbol; @@ -42189,12 +43304,12 @@ var TypeScript; var getterSymbol = accessorSymbol.getGetter(); var setterSymbol = accessorSymbol.getSetter(); - var isGetter = funcDeclAst.kind() == 139 /* GetAccessor */; + var isGetter = funcDeclAst.kind() === 139 /* GetAccessor */; if (isGetter) { var getterFunctionDeclarationAst = funcDeclAst; - context.pushContextualType(getterSymbol.type, context.inProvisionalResolution(), null); + context.pushNewContextualType(getterSymbol.type); this.typeCheckGetAccessorDeclaration(getterFunctionDeclarationAst, context); - context.popContextualType(); + context.popAnyContextualType(); } else { var setterFunctionDeclarationAst = funcDeclAst; this.typeCheckSetAccessorDeclaration(setterFunctionDeclarationAst, context); @@ -42272,7 +43387,7 @@ var TypeScript; var setterSuppliedTypeSymbol = setterParameters[0].type; var getterSuppliedTypeSymbol = getterSig.returnType; - if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol)) { + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.get_and_set_accessor_must_have_the_same_type)); } } @@ -42283,7 +43398,7 @@ var TypeScript; var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); var accessorSymbol = funcDecl.getSymbol(); - this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.getType(funcDeclAST), context); + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); this.resolveAST(funcDeclAST.block, false, context); @@ -42291,10 +43406,10 @@ var TypeScript; var enclosingDecl = this.getEnclosingDecl(funcDecl); - var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) != 0; + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; var funcNameAST = funcDeclAST.propertyName; - if (!hasReturn && !(funcDeclAST.block.statements.childCount() > 0 && funcDeclAST.block.statements.childAt(0).kind() === 157 /* ThrowStatement */)) { + if (!hasReturn && !this.containsSingleThrowStatement(funcDeclAST.block)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getters_must_return_a_value)); } @@ -42304,18 +43419,18 @@ var TypeScript; var setterIsPrivate = TypeScript.hasFlag(setterDecl.flags, 2 /* Private */); var getterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); - if (getterIsPrivate != setterIsPrivate) { + if (getterIsPrivate !== setterIsPrivate) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); } this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); } - this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), TypeScript.getType(funcDeclAST), funcDeclAST.block, context); + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), TypeScript.ASTHelpers.getType(funcDeclAST), funcDeclAST.block, context); }; PullTypeResolver.hasSetAccessorParameterTypeAnnotation = function (setAccessor) { - return setAccessor.parameterList && setAccessor.parameterList.parameters.nonSeparatorCount() > 0 && setAccessor.parameterList.parameters.nonSeparatorAt(0).typeAnnotation != null; + return setAccessor.parameterList && setAccessor.parameterList.parameters.nonSeparatorCount() > 0 && setAccessor.parameterList.parameters.nonSeparatorAt(0).typeAnnotation !== null; }; PullTypeResolver.prototype.resolveSetAccessorDeclaration = function (funcDeclAST, parameterList, context) { @@ -42350,10 +43465,6 @@ var TypeScript; signature.returnType = this.semanticInfoChain.voidTypeSymbol; - if (signature.hasAGenericParameter) { - setterTypeSymbol.setHasGenericSignature(); - } - if (!hadError) { signature.setResolved(); } @@ -42376,7 +43487,7 @@ var TypeScript; this.validateVariableDeclarationGroups(funcDecl, context); - var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) != 0; + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; var getter = accessorSymbol.getGetter(); @@ -42387,7 +43498,7 @@ var TypeScript; var getterIsPrivate = TypeScript.hasFlag(getterDecl.flags, 2 /* Private */); var setterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); - if (getterIsPrivate != setterIsPrivate) { + if (getterIsPrivate !== setterIsPrivate) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); } @@ -42395,13 +43506,13 @@ var TypeScript; } else { if (this.compilationSettings.noImplicitAny()) { var setterFunctionDeclarationAst = funcDeclAST; - if (!PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterFunctionDeclarationAst) && accessorSymbol.type == this.semanticInfoChain.anyTypeSymbol) { + if (!PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterFunctionDeclarationAst) && accessorSymbol.type === this.semanticInfoChain.anyTypeSymbol) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type, [setterFunctionDeclarationAst.propertyName.text()])); } } } - this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); }; PullTypeResolver.prototype.resolveList = function (list, context) { @@ -42497,7 +43608,7 @@ var TypeScript; var nodeType = unaryExpression.kind(); var expression = this.resolveAST(unaryExpression.operand, false, context); - if (nodeType == 164 /* PlusExpression */ || nodeType == 165 /* NegateExpression */ || nodeType == 166 /* BitwiseNotExpression */) { + if (nodeType === 164 /* PlusExpression */ || nodeType == 165 /* NegateExpression */ || nodeType == 166 /* BitwiseNotExpression */) { return; } @@ -42632,14 +43743,14 @@ var TypeScript; var enclosingSymbol = this.getEnclosingSymbolForAST(binaryExpression); var isValidLHS = this.isAnyOrEquivalent(lhsType) || lhsType.isObject() || lhsType.isTypeParameter(); - var isValidRHS = this.isAnyOrEquivalent(rhsType) || this.typeIsSubtypeOfFunction(rhsType, binaryExpression, context); + var isValidRHS = this.isAnyOrEquivalent(rhsType) || this.typeIsAssignableToFunction(rhsType, binaryExpression, context); if (!isValidLHS) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); } if (!isValidRHS) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_a_subtype_of_the_Function_interface_type)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type)); } }; @@ -42650,8 +43761,6 @@ var TypeScript; this.resolveAST(commaExpression.left, false, context); } - var rhsType = this.resolveAST(commaExpression.right, false, context).type; - return this.resolveAST(commaExpression.right, false, context).type; }; @@ -42678,7 +43787,7 @@ var TypeScript; } if (!isValidRHS) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); } }; @@ -42707,29 +43816,27 @@ var TypeScript; PullTypeResolver.prototype.typeCheckForInStatement = function (forInStatement, context) { this.setTypeChecked(forInStatement, context); - var rhsType = this.resolveAST(forInStatement.expression, false, context).type; - var lval = forInStatement.variableDeclaration || forInStatement.left; - - var varSym = this.resolveAST(lval, false, context); - if (forInStatement.variableDeclaration) { var declaration = forInStatement.variableDeclaration; - var varDecl = declaration.declarators.nonSeparatorAt(0); - if (varDecl.typeAnnotation) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(lval, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation)); + if (declaration.declarators.nonSeparatorCount() === 1) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + if (varDecl.typeAnnotation) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declaration, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation)); + } } + } else { + var varSym = this.resolveAST(forInStatement.left, false, context); + var isStringOrNumber = varSym.type === this.semanticInfoChain.stringTypeSymbol || this.isAnyOrEquivalent(varSym.type); - var varSym = this.getSymbolForAST(varDecl, context); + if (!isStringOrNumber) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.left, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any)); + } } - var isStringOrNumber = varSym.type === this.semanticInfoChain.stringTypeSymbol || this.isAnyOrEquivalent(varSym.type); - - var isValidRHS = rhsType && (this.isAnyOrEquivalent(rhsType) || !rhsType.isPrimitive()); - - if (!isStringOrNumber) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(lval, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any)); - } + var rhsType = this.resolveAST(forInStatement.expression, false, context).type; + var isValidRHS = rhsType && (this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter()); if (!isValidRHS) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.expression, TypeScript.DiagnosticCode.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter)); @@ -42908,23 +44015,23 @@ var TypeScript; if (enclosingFunction) { var enclosingDeclAST = this.getASTForDecl(enclosingFunction); - var typeAnnotation = TypeScript.getType(enclosingDeclAST); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); if (typeAnnotation) { var returnTypeAnnotationSymbol = this.resolveTypeReference(typeAnnotation, context); if (returnTypeAnnotationSymbol) { isContextuallyTyped = true; - context.pushContextualType(returnTypeAnnotationSymbol, context.inProvisionalResolution(), null); + context.pushNewContextualType(returnTypeAnnotationSymbol); } } else { var currentContextualType = context.getContextualType(); if (currentContextualType && currentContextualType.isFunction()) { - var currentContextTypeDecls = currentContextualType.getDeclarations(); - var currentContextualTypeSignatureSymbol = currentContextTypeDecls && currentContextTypeDecls.length > 0 ? currentContextTypeDecls[0].getSignatureSymbol() : currentContextualType.getCallSignatures()[0]; + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; if (currentContextualTypeReturnTypeSymbol) { isContextuallyTyped = true; - context.pushContextualType(currentContextualTypeReturnTypeSymbol, context.inProvisionalResolution(), null); + context.propagateContextualType(currentContextualTypeReturnTypeSymbol); } } } @@ -42932,7 +44039,7 @@ var TypeScript; var result = this.resolveAST(expression, isContextuallyTyped, context).type; if (isContextuallyTyped) { - context.popContextualType(); + context.popAnyContextualType(); } return result; @@ -42959,7 +44066,7 @@ var TypeScript; if (enclosingFunction) { var enclosingDeclAST = this.getASTForDecl(enclosingFunction); - var typeAnnotation = TypeScript.getType(enclosingDeclAST); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); if (typeAnnotation || enclosingFunction.kind === 262144 /* GetAccessor */) { var signatureSymbol = enclosingFunction.getSignatureSymbol(); var sigReturnType = signatureSymbol.returnType; @@ -42968,22 +44075,6 @@ var TypeScript; var comparisonInfo = new TypeComparisonInfo(); var upperBound = null; - if (expressionType.isTypeParameter()) { - upperBound = expressionType.getConstraint(); - - if (upperBound) { - expressionType = upperBound; - } - } - - if (sigReturnType.isTypeParameter()) { - upperBound = sigReturnType.getConstraint(); - - if (upperBound) { - sigReturnType = upperBound; - } - } - this.resolveDeclaredSymbol(expressionType, context); this.resolveDeclaredSymbol(sigReturnType, context); @@ -43081,8 +44172,11 @@ var TypeScript; var breakableLabels = this.getEnclosingLabels(ast, true, false); - if (TypeScript.ArrayUtilities.contains(breakableLabels, labelIdentifier)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast.identifier, TypeScript.DiagnosticCode.Duplicate_identifier_0, [labelIdentifier])); + var matchingLabel = TypeScript.ArrayUtilities.firstOrDefault(breakableLabels, function (s) { + return s.identifier.valueText() === labelIdentifier; + }); + if (matchingLabel) { + context.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(ast.identifier, labelIdentifier, matchingLabel)); } this.resolveAST(ast.statement, false, context); @@ -43157,13 +44251,13 @@ var TypeScript; return false; }; - PullTypeResolver.prototype.inIterationStatement = function (ast) { + PullTypeResolver.prototype.inIterationStatement = function (ast, crossFunctions) { while (ast) { if (this.isIterationStatement(ast)) { return true; } - if (this.isAnyFunctionExpressionOrDeclaration(ast)) { + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { return false; } @@ -43181,10 +44275,10 @@ var TypeScript; if (ast.kind() === 160 /* LabeledStatement */) { var labeledStatement = ast; if (breakable) { - result.push(labeledStatement.identifier.valueText()); + result.push(labeledStatement); } else { if (this.labelIsOnContinuableConstruct(labeledStatement.statement)) { - result.push(labeledStatement.identifier.valueText()); + result.push(labeledStatement); } } } @@ -43202,15 +44296,23 @@ var TypeScript; PullTypeResolver.prototype.typeCheckContinueStatement = function (ast, context) { this.setTypeChecked(ast, context); - if (!this.inIterationStatement(ast)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.continue_statement_can_only_be_used_within_an_enclosing_iteration_statement)); + if (!this.inIterationStatement(ast, false)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.continue_statement_can_only_be_used_within_an_enclosing_iteration_statement)); + } } else if (ast.identifier) { var continuableLabels = this.getEnclosingLabels(ast, false, false); - if (!TypeScript.ArrayUtilities.contains(continuableLabels, ast.identifier.valueText())) { + if (!TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { var continuableLabels = this.getEnclosingLabels(ast, false, true); - if (TypeScript.ArrayUtilities.contains(continuableLabels, ast.identifier.valueText())) { + if (TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); } else { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); @@ -43233,16 +44335,24 @@ var TypeScript; if (ast.identifier) { var breakableLabels = this.getEnclosingLabels(ast, true, false); - if (!TypeScript.ArrayUtilities.contains(breakableLabels, ast.identifier.valueText())) { + if (!TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { var breakableLabels = this.getEnclosingLabels(ast, true, true); - if (TypeScript.ArrayUtilities.contains(breakableLabels, ast.identifier.valueText())) { + if (TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); } else { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); } } - } else if (!this.inIterationStatement(ast) && !this.inSwitchStatement(ast)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement)); + } else if (!this.inIterationStatement(ast, false) && !this.inSwitchStatement(ast)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement)); + } } }; @@ -43257,6 +44367,10 @@ var TypeScript; return symbol; } + if (ast.isExpression() && !isTypesOnlyLocation(ast)) { + return this.resolveExpressionAST(ast, isContextuallyTyped, context); + } + var nodeType = ast.kind(); switch (nodeType) { @@ -43322,9 +44436,6 @@ var TypeScript; case 133 /* ImportDeclaration */: return this.resolveImportDeclaration(ast, context); - case 215 /* ObjectLiteralExpression */: - return this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); - case 240 /* SimplePropertyAssignment */: return this.resolveSimplePropertyAssignment(ast, isContextuallyTyped, context); @@ -43332,14 +44443,8 @@ var TypeScript; return this.resolveFunctionPropertyAssignment(ast, isContextuallyTyped, context); case 11 /* IdentifierName */: - if (isTypesOnlyLocation(ast)) { - return this.resolveTypeNameExpression(ast, context); - } else { - return this.resolveNameExpression(ast, context); - } - - case 212 /* MemberAccessExpression */: - return this.resolveMemberAccessExpression(ast, context); + TypeScript.Debug.assert(isTypesOnlyLocation(ast)); + return this.resolveTypeNameExpression(ast, context); case 121 /* QualifiedName */: return this.resolveQualifiedName(ast, context); @@ -43372,6 +44477,94 @@ var TypeScript; case 129 /* FunctionDeclaration */: return this.resolveAnyFunctionDeclaration(ast, context); + case 244 /* TypeAnnotation */: + return this.resolveTypeAnnotation(ast, context); + + case 134 /* ExportAssignment */: + return this.resolveExportAssignmentStatement(ast, context); + + case 157 /* ThrowStatement */: + return this.resolveThrowStatement(ast, context); + + case 149 /* ExpressionStatement */: + return this.resolveExpressionStatement(ast, context); + + case 154 /* ForStatement */: + return this.resolveForStatement(ast, context); + + case 155 /* ForInStatement */: + return this.resolveForInStatement(ast, context); + + case 158 /* WhileStatement */: + return this.resolveWhileStatement(ast, context); + + case 161 /* DoStatement */: + return this.resolveDoStatement(ast, context); + + case 147 /* IfStatement */: + return this.resolveIfStatement(ast, context); + + case 235 /* ElseClause */: + return this.resolveElseClause(ast, context); + + case 146 /* Block */: + return this.resolveBlock(ast, context); + + case 148 /* VariableStatement */: + return this.resolveVariableStatement(ast, context); + + case 163 /* WithStatement */: + return this.resolveWithStatement(ast, context); + + case 159 /* TryStatement */: + return this.resolveTryStatement(ast, context); + + case 236 /* CatchClause */: + return this.resolveCatchClause(ast, context); + + case 237 /* FinallyClause */: + return this.resolveFinallyClause(ast, context); + + case 150 /* ReturnStatement */: + return this.resolveReturnStatement(ast, context); + + case 151 /* SwitchStatement */: + return this.resolveSwitchStatement(ast, context); + + case 153 /* ContinueStatement */: + return this.resolveContinueStatement(ast, context); + + case 152 /* BreakStatement */: + return this.resolveBreakStatement(ast, context); + + case 160 /* LabeledStatement */: + return this.resolveLabeledStatement(ast, context); + } + + return this.semanticInfoChain.anyTypeSymbol; + }; + + PullTypeResolver.prototype.resolveExpressionAST = function (ast, isContextuallyOrInferentiallyTyped, context) { + var expressionSymbol = this.resolveExpressionWorker(ast, isContextuallyOrInferentiallyTyped, context); + + if (isContextuallyOrInferentiallyTyped && context.isInferentiallyTyping()) { + return this.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference(expressionSymbol, context); + } else { + return expressionSymbol; + } + }; + + PullTypeResolver.prototype.resolveExpressionWorker = function (ast, isContextuallyTyped, context) { + switch (ast.kind()) { + case 215 /* ObjectLiteralExpression */: + return this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + return this.resolveNameExpression(ast, context); + + case 212 /* MemberAccessExpression */: + return this.resolveMemberAccessExpression(ast, context); + case 222 /* FunctionExpression */: return this.resolveFunctionExpression(ast, isContextuallyTyped, context); @@ -43399,12 +44592,6 @@ var TypeScript; case 220 /* CastExpression */: return this.resolveCastExpression(ast, context); - case 244 /* TypeAnnotation */: - return this.resolveTypeAnnotation(ast, context); - - case 134 /* ExportAssignment */: - return this.resolveExportAssignmentStatement(ast, context); - case 13 /* NumericLiteral */: return this.semanticInfoChain.numberTypeSymbol; @@ -43486,9 +44673,6 @@ var TypeScript; case 171 /* TypeOfExpression */: return this.resolveTypeOfExpression(ast, context); - case 157 /* ThrowStatement */: - return this.resolveThrowStatement(ast, context); - case 170 /* DeleteExpression */: return this.resolveDeleteExpression(ast, context); @@ -43501,9 +44685,6 @@ var TypeScript; case 217 /* ParenthesizedExpression */: return this.resolveParenthesizedExpression(ast, context); - case 149 /* ExpressionStatement */: - return this.resolveExpressionStatement(ast, context); - case 200 /* InstanceOfExpression */: return this.resolveInstanceOfExpression(ast, context); @@ -43513,59 +44694,11 @@ var TypeScript; case 201 /* InExpression */: return this.resolveInExpression(ast, context); - case 154 /* ForStatement */: - return this.resolveForStatement(ast, context); - - case 155 /* ForInStatement */: - return this.resolveForInStatement(ast, context); - - case 158 /* WhileStatement */: - return this.resolveWhileStatement(ast, context); - - case 161 /* DoStatement */: - return this.resolveDoStatement(ast, context); - - case 147 /* IfStatement */: - return this.resolveIfStatement(ast, context); - - case 235 /* ElseClause */: - return this.resolveElseClause(ast, context); - - case 146 /* Block */: - return this.resolveBlock(ast, context); - - case 148 /* VariableStatement */: - return this.resolveVariableStatement(ast, context); - - case 163 /* WithStatement */: - return this.resolveWithStatement(ast, context); - - case 159 /* TryStatement */: - return this.resolveTryStatement(ast, context); - - case 236 /* CatchClause */: - return this.resolveCatchClause(ast, context); - - case 237 /* FinallyClause */: - return this.resolveFinallyClause(ast, context); - - case 150 /* ReturnStatement */: - return this.resolveReturnStatement(ast, context); - - case 151 /* SwitchStatement */: - return this.resolveSwitchStatement(ast, context); - - case 153 /* ContinueStatement */: - return this.resolveContinueStatement(ast, context); - - case 152 /* BreakStatement */: - return this.resolveBreakStatement(ast, context); - - case 160 /* LabeledStatement */: - return this.resolveLabeledStatement(ast, context); + case 223 /* OmittedExpression */: + return this.semanticInfoChain.undefinedTypeSymbol; } - return this.semanticInfoChain.anyTypeSymbol; + TypeScript.Debug.fail("resolveExpressionASTWorker: Missing expression kind: " + TypeScript.SyntaxKind[ast.kind()]); }; PullTypeResolver.prototype.typeCheckAST = function (ast, isContextuallyTyped, context) { @@ -43644,8 +44777,25 @@ var TypeScript; return; case 222 /* FunctionExpression */: - this.typeCheckFunctionExpression(ast, context); - break; + this.typeCheckFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 137 /* ConstructorDeclaration */: + this.typeCheckConstructorDeclaration(ast, context); + return; + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + this.typeCheckAccessorDeclaration(ast, context); + return; + + case 135 /* MemberFunctionDeclaration */: + this.typeCheckMemberFunctionDeclaration(ast, context); + return; + + case 145 /* MethodSignature */: + this.typeCheckMethodSignature(ast, context); + return; case 144 /* IndexSignature */: this.typeCheckIndexSignature(ast, context); @@ -43653,24 +44803,24 @@ var TypeScript; case 142 /* CallSignature */: this.typeCheckCallSignature(ast, context); - break; + return; case 143 /* ConstructSignature */: this.typeCheckConstructSignature(ast, context); - break; + return; case 129 /* FunctionDeclaration */: { var funcDecl = ast; - this.typeCheckFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), funcDecl.block, context); + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); return; } case 219 /* SimpleArrowFunctionExpression */: - this.typeCheckSimpleArrowFunctionExpression(ast, context); + this.typeCheckSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); return; case 218 /* ParenthesizedArrowFunctionExpression */: - this.typeCheckParenthesizedArrowFunctionExpression(ast, context); + this.typeCheckParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); return; case 214 /* ArrayLiteralExpression */: @@ -43758,36 +44908,112 @@ var TypeScript; PullTypeResolver.prototype.resolveNameExpression = function (nameAST, context) { var nameSymbol = this.getSymbolForAST(nameAST, context); - var foundCached = nameSymbol != null; + var foundCached = nameSymbol !== null; if (!foundCached || this.canTypeCheckAST(nameAST, context)) { if (this.canTypeCheckAST(nameAST, context)) { this.typeCheckNameExpression(nameAST, context); } - nameSymbol = this.computeNameExpression(nameAST, context, true); + nameSymbol = this.computeNameExpression(nameAST, context); } this.resolveDeclaredSymbol(nameSymbol, context); - if (nameSymbol && (nameSymbol.type != this.semanticInfoChain.anyTypeSymbol || nameSymbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + if (nameSymbol && (nameSymbol.type !== this.semanticInfoChain.anyTypeSymbol || nameSymbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { this.setSymbolForAST(nameAST, nameSymbol, context); } return nameSymbol; }; - PullTypeResolver.prototype.isSomeFunctionScope = function (declPath) { - for (var i = declPath.length - 1; i >= 0; i--) { - var decl = declPath[i]; - if (decl.kind & 1032192 /* SomeFunction */) { - return true; - } + PullTypeResolver.prototype.isInEnumDecl = function (decl) { + if (decl.kind & 64 /* Enum */) { + return true; } + var declPath = decl.getParentPath(); + + var disallowedKinds = 164 /* SomeContainer */ | 58728795 /* SomeType */; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + + if (decl.kind & 64 /* Enum */) { + return true; + } + + if (decl.kind & disallowedKinds) { + return false; + } + } return false; }; - PullTypeResolver.prototype.computeNameExpression = function (nameAST, context, reportDiagnostics) { + PullTypeResolver.prototype.getSomeInnermostFunctionScopeDecl = function (declPath) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (decl.kind & 1032192 /* SomeFunction */) { + return decl; + } + } + + return null; + }; + + PullTypeResolver.prototype.isFromFunctionScope = function (nameSymbol, functionScopeDecl) { + var _this = this; + return TypeScript.ArrayUtilities.any(nameSymbol.getDeclarations(), function (nameSymbolDecl) { + return _this.getSomeInnermostFunctionScopeDecl(nameSymbolDecl.getParentPath()) === functionScopeDecl; + }); + }; + + PullTypeResolver.prototype.findConstructorDeclOfEnclosingType = function (decl) { + var current = decl; + while (current) { + if (TypeScript.hasFlag(current.kind, 4096 /* Property */)) { + var parentDecl = current.getParentDecl(); + if (TypeScript.hasFlag(parentDecl.kind, 8 /* Class */)) { + return TypeScript.ArrayUtilities.lastOrDefault(parentDecl.getChildDecls(), function (decl) { + return TypeScript.hasFlag(decl.kind, 32768 /* ConstructorMethod */); + }); + } + } + + if (TypeScript.hasFlag(current.kind, 164 /* SomeContainer */)) { + return null; + } + + current = current.getParentDecl(); + } + return null; + }; + + PullTypeResolver.prototype.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable = function (nameAST) { + var id = nameAST.valueText(); + if (id.length === 0) { + return null; + } + + var memberVariableDeclarationAST = TypeScript.ASTHelpers.getEnclosingMemberVariableDeclaration(nameAST); + if (memberVariableDeclarationAST) { + var memberVariableDecl = this.semanticInfoChain.getDeclForAST(memberVariableDeclarationAST); + if (!TypeScript.hasFlag(memberVariableDecl.flags, 16 /* Static */)) { + var constructorDecl = this.findConstructorDeclOfEnclosingType(memberVariableDecl); + + if (constructorDecl) { + var childDecls = constructorDecl.searchChildDecls(id, 68147712 /* SomeValue */); + + if (childDecls.length) { + var memberVariableSymbol = memberVariableDecl.getSymbol(); + + return this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, [memberVariableSymbol.getScopedName(constructorDecl.getSymbol()), nameAST.text()]); + } + } + } + } + return null; + }; + + PullTypeResolver.prototype.computeNameExpression = function (nameAST, context) { var id = nameAST.valueText(); if (id.length === 0) { return this.semanticInfoChain.anyTypeSymbol; @@ -43796,37 +45022,47 @@ var TypeScript; var nameSymbol = null; var enclosingDecl = this.getEnclosingDeclForAST(nameAST); - if (TypeScript.isDeclarationASTOrDeclarationNameAST(nameAST)) { + if (TypeScript.hasFlag(enclosingDecl.flags, 8388608 /* PropertyParameter */)) { + var valueDecl = enclosingDecl.getValueDecl(); + if (valueDecl && TypeScript.hasFlag(valueDecl.kind, 2048 /* Parameter */)) { + enclosingDecl = valueDecl; + } + } + + var diagnosticForInitializer = this.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable(nameAST); + + if (TypeScript.ASTHelpers.isDeclarationASTOrDeclarationNameAST(nameAST)) { nameSymbol = this.semanticInfoChain.getDeclForAST(nameAST.parent).getSymbol(); } var declPath = enclosingDecl.getParentPath(); if (!nameSymbol) { - var nameSymbol = this.getSymbolFromDeclPath(id, declPath, 68147712 /* SomeValue */); + var searchKind = 68147712 /* SomeValue */; + + if (!this.isInEnumDecl(enclosingDecl)) { + searchKind = searchKind & ~(67108864 /* EnumMember */); + } + + var nameSymbol = this.getSymbolFromDeclPath(id, declPath, searchKind); } - if (!nameSymbol && id === "arguments" && this.isSomeFunctionScope(declPath)) { - nameSymbol = this.cachedFunctionArgumentsSymbol(); - - this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), context); - } - - if (!nameSymbol) { - nameSymbol = this.getSymbolFromDeclPath(id, declPath, 128 /* TypeAlias */); - - if (nameSymbol && !nameSymbol.isAlias()) { - nameSymbol = null; + if (id === "arguments") { + var functionScopeDecl = this.getSomeInnermostFunctionScopeDecl(declPath); + if (functionScopeDecl) { + if (!nameSymbol || !this.isFromFunctionScope(nameSymbol, functionScopeDecl)) { + nameSymbol = this.cachedFunctionArgumentsSymbol(); + this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), context); + } } } if (!nameSymbol) { - if (!reportDiagnostics) { - return null; - } else { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); - return this.getNewErrorTypeSymbol(id); - } + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (diagnosticForInitializer) { + context.postDiagnostic(diagnosticForInitializer); + return this.getNewErrorTypeSymbol(id); } var nameDeclaration = nameSymbol.getDeclarations()[0]; @@ -43835,22 +45071,26 @@ var TypeScript; var enclosingFunctionAST = this.semanticInfoChain.getASTForDecl(nameParentDecl); var currentParameterIndex = this.getCurrentParameterIndexForFunction(nameAST, enclosingFunctionAST); - var parameterList = TypeScript.getParameterList(enclosingFunctionAST); + var parameterList = TypeScript.ASTHelpers.getParameterList(enclosingFunctionAST); if (currentParameterIndex >= 0) { - var foundMatchingParameter = false; + var matchingParameter; if (parameterList) { for (var i = 0; i <= currentParameterIndex; i++) { var candidateParameter = parameterList.parameters.nonSeparatorAt(i); if (candidateParameter && candidateParameter.identifier.valueText() === id) { - foundMatchingParameter = true; + matchingParameter = candidateParameter; + break; } } } - if (!foundMatchingParameter) { + if (!matchingParameter) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text(), nameAST.text()])); return this.getNewErrorTypeSymbol(id); + } else if (matchingParameter === TypeScript.ASTHelpers.getEnclosingParameterForInitializer(nameAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Parameter_0_cannot_be_referenced_in_its_initializer, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text()])); + return this.getNewErrorTypeSymbol(id); } } } @@ -43860,7 +45100,7 @@ var TypeScript; if (nameSymbol.isType() && nameSymbol.isAlias()) { aliasSymbol = nameSymbol; if (!this.inTypeQuery(nameAST)) { - aliasSymbol.setIsUsedAsValue(true); + aliasSymbol.setIsUsedAsValue(); } this.resolveDeclaredSymbol(nameSymbol, context); @@ -43885,7 +45125,7 @@ var TypeScript; }; PullTypeResolver.prototype.getCurrentParameterIndexForFunction = function (parameter, funcDecl) { - var parameterList = TypeScript.getParameterList(funcDecl); + var parameterList = TypeScript.ASTHelpers.getParameterList(funcDecl); if (parameterList) { while (parameter && parameter.parent) { if (parameter.parent.parent === parameterList) { @@ -43905,7 +45145,7 @@ var TypeScript; PullTypeResolver.prototype.resolveDottedNameExpression = function (dottedNameAST, expression, name, context) { var symbol = this.getSymbolForAST(dottedNameAST, context); - var foundCached = symbol != null; + var foundCached = symbol !== null; if (!foundCached || this.canTypeCheckAST(dottedNameAST, context)) { var canTypeCheckDottedNameAST = this.canTypeCheckAST(dottedNameAST, context); @@ -43918,7 +45158,7 @@ var TypeScript; this.resolveDeclaredSymbol(symbol, context); - if (symbol && (symbol.type != this.semanticInfoChain.anyTypeSymbol || symbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + if (symbol && (symbol.type !== this.semanticInfoChain.anyTypeSymbol || symbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { this.setSymbolForAST(dottedNameAST, symbol, context); this.setSymbolForAST(name, symbol, context); } @@ -43933,17 +45173,23 @@ var TypeScript; } var lhs = this.resolveAST(expression, false, context); + return this.computeDottedNameExpressionFromLHS(lhs, expression, name, context, checkSuperPrivateAndStaticAccess); + }; + + PullTypeResolver.prototype.computeDottedNameExpressionFromLHS = function (lhs, expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + var lhsType = lhs.type; if (lhs.isAlias()) { + var lhsAlias = lhs; if (!this.inTypeQuery(expression)) { - lhs.setIsUsedAsValue(true); + lhsAlias.setIsUsedAsValue(); } - lhsType = lhs.getExportAssignedTypeSymbol(); - } - - if (this.isAnyOrEquivalent(lhsType)) { - return lhsType; + lhsType = lhsAlias.getExportAssignedTypeSymbol(); } if (lhsType.isAlias()) { @@ -43958,7 +45204,7 @@ var TypeScript; if (!lhsType.isResolved) { var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); - if (potentiallySpecializedType != lhsType) { + if (potentiallySpecializedType !== lhsType) { if (!lhs.isType()) { context.setTypeInContext(lhs, potentiallySpecializedType); } @@ -43975,47 +45221,37 @@ var TypeScript; } } - if (lhsType.isTypeParameter()) { - lhsType = this.substituteUpperBoundForType(lhsType); + var originalLhsTypeForErrorReporting = lhsType; + + lhsType = this.getApparentType(lhsType).widenedType(this, expression, context); + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; } - if ((lhsType === this.semanticInfoChain.numberTypeSymbol || lhsType.isEnum()) && this.cachedNumberInterfaceType()) { - lhsType = this.cachedNumberInterfaceType(); - } else if (lhsType === this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { - lhsType = this.cachedStringInterfaceType(); - } else if (lhsType === this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { - lhsType = this.cachedBooleanInterfaceType(); - } - - var nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, lhsType); + var nameSymbol = this._getNamedPropertySymbolOfAugmentedType(rhsName, lhsType); if (!nameSymbol) { - if ((lhsType.getCallSignatures().length || lhsType.getConstructSignatures().length) && this.cachedFunctionInterfaceType()) { - nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, this.cachedFunctionInterfaceType()); - } else if (lhsType.kind === 32 /* DynamicModule */) { + if (lhsType.kind === 32 /* DynamicModule */) { var container = lhsType; var associatedInstance = container.getInstanceSymbol(); if (associatedInstance) { var instanceType = associatedInstance.type; - nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, instanceType); + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, instanceType); } } else { var associatedType = lhsType.getAssociatedContainerType(); if (associatedType && !associatedType.isClass()) { - nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, associatedType); + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, associatedType); } } - if (!nameSymbol && !lhsType.isPrimitive() && this.cachedObjectInterfaceType()) { - nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, this.cachedObjectInterfaceType()); - } - if (!nameSymbol) { var enclosingDecl = this.getEnclosingDeclForAST(expression); - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [name.text(), lhsType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [name.text(), originalLhsTypeForErrorReporting.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); return this.getNewErrorTypeSymbol(rhsName); } } @@ -44055,8 +45291,8 @@ var TypeScript; var onLeftOfDot = this.isLeftSideOfQualifiedName(nameAST); - var kindToCheckFirst = onLeftOfDot ? 164 /* SomeContainer */ : 58728539 /* SomeType */; - var kindToCheckSecond = onLeftOfDot ? 58728539 /* SomeType */ : 164 /* SomeContainer */; + var kindToCheckFirst = onLeftOfDot ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + var kindToCheckSecond = onLeftOfDot ? 58728795 /* SomeType */ : 164 /* SomeContainer */; var typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckFirst); @@ -44080,11 +45316,11 @@ var TypeScript; } if (typeNameSymbol.isTypeParameter()) { - if (enclosingDecl && (enclosingDecl.kind & 1032192 /* SomeFunction */) && (enclosingDecl.flags & 16 /* Static */)) { + if (this.isInStaticMemberContext(enclosingDecl)) { var parentDecl = typeNameSymbol.getDeclarations()[0].getParentDecl(); - if (parentDecl.kind == 8 /* Class */) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Static_methods_cannot_reference_class_type_parameters)); + if (parentDecl.kind === 8 /* Class */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Static_members_cannot_reference_class_type_parameters)); return this.getNewErrorTypeSymbol(); } } @@ -44097,6 +45333,22 @@ var TypeScript; return typeNameSymbol; }; + PullTypeResolver.prototype.isInStaticMemberContext = function (decl) { + while (decl) { + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */ | 4096 /* Property */) && TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + return true; + } + + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + return false; + } + + decl = decl.getParentDecl(); + } + + return false; + }; + PullTypeResolver.prototype.isLeftSideOfQualifiedName = function (ast) { return ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.left === ast; }; @@ -44113,9 +45365,18 @@ var TypeScript; } if (genericTypeSymbol.isAlias()) { + if (this.inClassExtendsHeritageClause(genericTypeAST) && !this.inTypeArgumentList(genericTypeAST)) { + genericTypeSymbol.setIsUsedAsValue(); + } genericTypeSymbol = genericTypeSymbol.getExportAssignedTypeSymbol(); } + var typeParameters = genericTypeSymbol.getTypeParameters(); + if (typeParameters.length === 0) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_have_type_parameters, [genericTypeSymbol.toString()])); + return this.getNewErrorTypeSymbol(); + } + var typeArgs = []; if (genericTypeAST.typeArgumentList && genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount()) { @@ -44128,9 +45389,7 @@ var TypeScript; } } - var typeParameters = genericTypeSymbol.getTypeParameters(); - - if (typeArgs.length && typeArgs.length != typeParameters.length) { + if (typeArgs.length && typeArgs.length !== typeParameters.length) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Generic_type_0_requires_1_type_argument_s, [genericTypeSymbol.toString(), genericTypeSymbol.getTypeParameters().length])); return this.getNewErrorTypeSymbol(); } @@ -44177,7 +45436,7 @@ var TypeScript; if (typeConstraint) { if (typeConstraint.isTypeParameter()) { for (var j = 0; j < typeParameters.length && j < typeArgs.length; j++) { - if (typeParameters[j] == typeConstraint) { + if (typeParameters[j] === typeConstraint) { typeConstraint = typeArgs[j]; } } @@ -44196,6 +45455,7 @@ var TypeScript; if (typeArg.inResolution || (typeArg.isTypeReference() && typeArg.referencedTypeSymbol.inResolution)) { return specializedSymbol; } + if (!this.sourceIsAssignableToTarget(typeArg, typeConstraint, genericTypeAST, context)) { var enclosingSymbol = this.getEnclosingSymbolForAST(genericTypeAST); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [typeArg.toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[iArg].toString(enclosingSymbol, true)])); @@ -44227,6 +45487,10 @@ var TypeScript; return symbol; }; + PullTypeResolver.prototype.isLastNameOfModuleNameModuleReference = function (ast) { + return ast.kind() === 11 /* IdentifierName */ && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast && ast.parent.parent && ast.parent.parent.kind() === 246 /* ModuleNameModuleReference */; + }; + PullTypeResolver.prototype.computeQualifiedName = function (dottedNameAST, context) { var rhsName = dottedNameAST.right.valueText(); if (rhsName.length === 0) { @@ -44240,7 +45504,7 @@ var TypeScript; if (this.inClassExtendsHeritageClause(dottedNameAST) && !this.inTypeArgumentList(dottedNameAST)) { if (lhs.isAlias()) { - lhs.setIsUsedAsValue(true); + lhs.setIsUsedAsValue(); } } @@ -44254,15 +45518,20 @@ var TypeScript; var onLeftOfDot = this.isLeftSideOfQualifiedName(dottedNameAST); var isNameOfModule = dottedNameAST.parent.kind() === 130 /* ModuleDeclaration */ && dottedNameAST.parent.name === dottedNameAST; - var memberKind = (onLeftOfDot || isNameOfModule) ? 164 /* SomeContainer */ : 58728539 /* SomeType */; - var childTypeSymbol = this.getMemberSymbol(rhsName, memberKind, lhsType); + var memberKind = (onLeftOfDot || isNameOfModule) ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + + var childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + + if (!childTypeSymbol && !isNameOfModule && this.isLastNameOfModuleNameModuleReference(dottedNameAST.right)) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, lhsType); + } if (!childTypeSymbol && lhsType.isContainer()) { var exportedContainer = lhsType.getExportAssignedContainerSymbol(); if (exportedContainer) { - childTypeSymbol = this.getMemberSymbol(rhsName, memberKind, exportedContainer); + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, exportedContainer); } } @@ -44281,7 +45550,7 @@ var TypeScript; var enclosingSymbolType = parentDecl.getSymbol().type; if (enclosingSymbolType === lhsType) { - childTypeSymbol = this.getMemberSymbol(rhsName, memberKind, lhsType); + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); } } } @@ -44316,12 +45585,12 @@ var TypeScript; if (contextualFunctionTypeSymbol) { this.resolveDeclaredSymbol(contextualFunctionTypeSymbol, context); var callSignatures = contextualFunctionTypeSymbol.getCallSignatures(); - var exactlyOneCallSignature = callSignatures && callSignatures.length == 1; + var exactlyOneCallSignature = callSignatures && callSignatures.length === 1; if (!exactlyOneCallSignature) { return false; } - var callSignatureIsGeneric = callSignatures[0].typeParameters && callSignatures[0].typeParameters.length > 0; + var callSignatureIsGeneric = callSignatures[0].getTypeParameters().length > 0; return !callSignatureIsGeneric; } @@ -44358,36 +45627,7 @@ var TypeScript; assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; } - if (parameters) { - var contextParams = []; - - if (assigningFunctionSignature) { - contextParams = assigningFunctionSignature.parameters; - } - - var contextualParametersCount = contextParams.length; - for (var i = 0, n = parameters.length; i < n; i++) { - var actualParameterIsVarArgParameter = (i === (n - 1)) && parameters.lastParameterIsRest(); - var correspondingContextualParameter = null; - var contextualParameterType = null; - - if (i < contextualParametersCount) { - correspondingContextualParameter = contextParams[i]; - } else if (contextualParametersCount && contextParams[contextualParametersCount - 1].isVarArg) { - correspondingContextualParameter = contextParams[contextualParametersCount - 1]; - } - - if (correspondingContextualParameter) { - if (correspondingContextualParameter.isVarArg === actualParameterIsVarArgParameter) { - contextualParameterType = correspondingContextualParameter.type; - } else if (correspondingContextualParameter.isVarArg) { - contextualParameterType = correspondingContextualParameter.type.getElementType(); - } - } - - this.resolveFunctionExpressionParameter(parameters.astAt(i), parameters.identifierAt(i), parameters.typeAt(i), parameters.initializerAt(i), contextualParameterType, functionDecl, context); - } - } + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); if (returnTypeAnnotation) { signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); @@ -44396,10 +45636,9 @@ var TypeScript; var returnType = assigningFunctionSignature.returnType; if (returnType) { - context.pushContextualType(returnType, context.inProvisionalResolution(), null); - + context.propagateContextualType(returnType); this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, true, functionDecl, context); - context.popContextualType(); + context.popAnyContextualType(); } else { signature.returnType = this.semanticInfoChain.anyTypeSymbol; @@ -44422,21 +45661,63 @@ var TypeScript; funcDeclSymbol.setResolved(); if (this.canTypeCheckAST(funcDeclAST, context)) { - this.typeCheckAnyFunctionExpression(funcDeclAST, typeParameters, returnTypeAnnotation, block, bodyExpression, context); + this.typeCheckAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context); } return funcDeclSymbol; }; - PullTypeResolver.prototype.typeCheckSimpleArrowFunctionExpression = function (arrowFunction, context) { - return this.typeCheckAnyFunctionExpression(arrowFunction, null, null, arrowFunction.block, arrowFunction.expression, context); + PullTypeResolver.prototype.resolveAnyFunctionExpressionParameters = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context) { + if (!parameters) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var contextParams = []; + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + if (assigningFunctionSignature) { + contextParams = assigningFunctionSignature.parameters; + } + + var contextualParametersCount = contextParams.length; + for (var i = 0, n = parameters.length; i < n; i++) { + var actualParameterIsVarArgParameter = (i === (n - 1)) && parameters.lastParameterIsRest(); + var correspondingContextualParameter = null; + var contextualParameterType = null; + + if (i < contextualParametersCount) { + correspondingContextualParameter = contextParams[i]; + } else if (contextualParametersCount && contextParams[contextualParametersCount - 1].isVarArg) { + correspondingContextualParameter = contextParams[contextualParametersCount - 1]; + } + + if (correspondingContextualParameter) { + if (correspondingContextualParameter.isVarArg === actualParameterIsVarArgParameter) { + contextualParameterType = correspondingContextualParameter.type; + } else if (correspondingContextualParameter.isVarArg) { + contextualParameterType = correspondingContextualParameter.type.getElementType(); + } + } + + this.resolveFunctionExpressionParameter(parameters.astAt(i), parameters.identifierAt(i), parameters.typeAt(i), parameters.initializerAt(i), contextualParameterType, functionDecl, context); + } }; - PullTypeResolver.prototype.typeCheckParenthesizedArrowFunctionExpression = function (arrowFunction, context) { - return this.typeCheckAnyFunctionExpression(arrowFunction, arrowFunction.callSignature.typeParameterList, TypeScript.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, context); + PullTypeResolver.prototype.typeCheckSimpleArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), null, arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); }; - PullTypeResolver.prototype.typeCheckAnyFunctionExpression = function (funcDeclAST, typeParameters, returnTypeAnnotation, block, bodyExpression, context) { + PullTypeResolver.prototype.typeCheckParenthesizedArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { var _this = this; this.setTypeChecked(funcDeclAST, context); @@ -44453,27 +45734,19 @@ var TypeScript; } } - context.pushContextualType(null, context.inProvisionalResolution(), null); + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + context.pushNewContextualType(null); if (block) { this.resolveAST(block, false, context); } else { var bodyExpressionType = this.resolveReturnExpression(bodyExpression, functionDecl, context); this.typeCheckReturnExpression(bodyExpression, bodyExpressionType, functionDecl, context); } - context.popContextualType(); - var hasReturn = (functionDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) != 0; + context.popAnyContextualType(); - if (block && returnTypeAnnotation != null && !hasReturn) { - var isVoidOrAny = this.isAnyOrEquivalent(returnTypeSymbol) || returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol; - - if (!isVoidOrAny && !(block.statements.childCount() > 0 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */)) { - var funcName = functionDecl.getDisplayName(); - funcName = funcName ? "'" + funcName + "'" : "expression"; - - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_0_declared_a_non_void_return_type_but_has_no_return_expression, [funcName])); - } - } + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context); this.validateVariableDeclarationGroups(functionDecl, context); @@ -44587,9 +45860,11 @@ var TypeScript; var current = ast; while (current) { switch (current.kind()) { - case 137 /* ConstructorDeclaration */: - var constructorDecl = current; - return previous === constructorDecl.parameterList; + case 142 /* CallSignature */: + var callSignature = current; + if (previous === callSignature.parameterList && callSignature.parent.kind() === 137 /* ConstructorDeclaration */) { + return true; + } case 131 /* ClassDeclaration */: case 130 /* ModuleDeclaration */: @@ -44602,6 +45877,13 @@ var TypeScript; return false; }; + PullTypeResolver.prototype.isFunctionAccessorOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 262144 /* GetAccessor */ || decl.kind === 524288 /* SetAccessor */) { + return true; + } + + return this.isFunctionOrNonArrowFunctionExpression(decl); + }; PullTypeResolver.prototype.isFunctionOrNonArrowFunctionExpression = function (decl) { if (decl.kind === 16384 /* Function */) { @@ -44622,7 +45904,7 @@ var TypeScript; } for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { - if (this.isFunctionOrNonArrowFunctionExpression(currentDecl)) { + if (this.isFunctionAccessorOrNonArrowFunctionExpression(currentDecl)) { return; } else if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { if (currentDecl.getParentDecl() === null) { @@ -44631,6 +45913,9 @@ var TypeScript; context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_within_module_bodies)); return; } + } else if (currentDecl.kind === 64 /* Enum */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + return; } else if (currentDecl.kind === 32768 /* ConstructorMethod */) { if (this.inArgumentListOfSuperInvocation(thisExpression) && this.superCallMustBeFirstStatementInConstructor(currentDecl)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); @@ -44745,29 +46030,22 @@ var TypeScript; return; } } - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class)); return; } else { - for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { - if (this.isFunctionOrNonArrowFunctionExpression(currentDecl)) { - break; - } else if (currentDecl.kind === 32768 /* ConstructorMethod */) { - var classDecl = currentDecl.getParentDecl(); - - if (!this.enclosingClassIsDerived(classDecl)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); - return; - } else if (this.inConstructorParameterList(ast)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); - return; - } + if (enclosingDecl.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingDecl.getParentDecl(); + if (!this.enclosingClassIsDerived(classDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); return; } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors)); } - - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors)); } }; @@ -44776,17 +46054,18 @@ var TypeScript; }; PullTypeResolver.prototype.resolveFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { - return this.resolveAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(funcProp.callSignature.parameterList), TypeScript.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + return this.resolveAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); }; PullTypeResolver.prototype.typeCheckFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { - this.typeCheckAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.getType(funcProp), funcProp.block, null, context); + this.typeCheckAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); }; PullTypeResolver.prototype.resolveObjectLiteralExpression = function (expressionAST, isContextuallyTyped, context, additionalResults) { var symbol = this.getSymbolForAST(expressionAST, context); + var hasResolvedSymbol = symbol && symbol.isResolved; - if (!symbol || additionalResults || this.canTypeCheckAST(expressionAST, context)) { + if (!hasResolvedSymbol || additionalResults || this.canTypeCheckAST(expressionAST, context)) { if (this.canTypeCheckAST(expressionAST, context)) { this.setTypeChecked(expressionAST, context); } @@ -44810,7 +46089,7 @@ var TypeScript; var decl = this.semanticInfoChain.getDeclForAST(propertyAssignment); TypeScript.Debug.assert(decl); - if (propertyAssignment.kind() == 240 /* SimplePropertyAssignment */) { + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { if (!isUsingExistingSymbol) { memberSymbol = new TypeScript.PullSymbol(assignmentText.memberName, 4096 /* Property */); memberSymbol.addDeclaration(decl); @@ -44826,8 +46105,9 @@ var TypeScript; } if (!isUsingExistingSymbol && !isAccessor) { - if (objectLiteralTypeSymbol.findMember(memberSymbol.name, true)) { - pullTypeContext.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(propertyAssignment, TypeScript.DiagnosticCode.Duplicate_identifier_0, [assignmentText.actualText])); + var existingMember = objectLiteralTypeSymbol.findMember(memberSymbol.name, true); + if (existingMember) { + pullTypeContext.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(propertyAssignment, assignmentText.actualText, existingMember.getDeclarations()[0].ast())); } objectLiteralTypeSymbol.addMember(memberSymbol); @@ -44848,9 +46128,10 @@ var TypeScript; var id = this.getPropertyAssignmentName(propertyAssignment); var memberSymbol = boundMemberSymbols[i]; + var contextualMemberType = null; if (objectLiteralContextualType) { - assigningSymbol = this.getMemberSymbol(memberSymbol.name, 68147712 /* SomeValue */, objectLiteralContextualType); + assigningSymbol = this.getNamedPropertySymbol(memberSymbol.name, 68147712 /* SomeValue */, objectLiteralContextualType); if (!assigningSymbol) { if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { @@ -44863,8 +46144,8 @@ var TypeScript; if (assigningSymbol) { this.resolveDeclaredSymbol(assigningSymbol, pullTypeContext); - var contextualMemberType = assigningSymbol.kind === 4194304 /* IndexSignature */ ? assigningSymbol.returnType : assigningSymbol.type; - pullTypeContext.pushContextualType(contextualMemberType, pullTypeContext.inProvisionalResolution(), null); + contextualMemberType = assigningSymbol.kind === 4194304 /* IndexSignature */ ? assigningSymbol.returnType : assigningSymbol.type; + pullTypeContext.propagateContextualType(contextualMemberType); acceptedContextualType = true; @@ -44874,32 +46155,31 @@ var TypeScript; } } - var propertySymbol = this.resolveAST(propertyAssignment, contextualMemberType != null, pullTypeContext); - var memberExpr = this.widenType(propertySymbol.type, propertyAssignment, pullTypeContext); + var memberSymbolType = this.resolveAST(propertyAssignment, contextualMemberType !== null, pullTypeContext).type; - if (memberExpr.type) { - if (memberExpr.type.isGeneric()) { + if (memberSymbolType) { + if (memberSymbolType.isGeneric()) { objectLiteralTypeSymbol.setHasGenericMember(); } if (stringIndexerSignature) { - allMemberTypes.push(memberExpr.type); + allMemberTypes.push(memberSymbolType); } if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { - allNumericMemberTypes.push(memberExpr.type); + allNumericMemberTypes.push(memberSymbolType); } } if (acceptedContextualType) { - pullTypeContext.popContextualType(); + pullTypeContext.popAnyContextualType(); } var isAccessor = propertyAssignment.kind() === 140 /* SetAccessor */ || propertyAssignment.kind() === 139 /* GetAccessor */; - if (!isUsingExistingSymbol) { + if (!memberSymbol.isResolved) { if (isAccessor) { - this.setSymbolForAST(id, memberExpr, pullTypeContext); + this.setSymbolForAST(id, memberSymbolType, pullTypeContext); } else { - pullTypeContext.setTypeInContext(memberSymbol, memberExpr.type); + pullTypeContext.setTypeInContext(memberSymbol, memberSymbolType); memberSymbol.setResolved(); this.setSymbolForAST(id, memberSymbol, pullTypeContext); @@ -44916,7 +46196,7 @@ var TypeScript; var isUsingExistingSymbol = !!typeSymbol; if (!typeSymbol) { - typeSymbol = new TypeScript.PullTypeSymbol("", 16 /* Interface */); + typeSymbol = new TypeScript.PullTypeSymbol("", 256 /* ObjectLiteral */); typeSymbol.addDeclaration(objectLitDecl); this.setSymbolForAST(objectLitAST, typeSymbol, context); objectLitDecl.setSymbol(typeSymbol); @@ -44936,17 +46216,18 @@ var TypeScript; var allNumericMemberTypes = null; if (contextualType) { - var indexSignatures = this.getBothKindsOfIndexSignatures(contextualType, context); + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); stringIndexerSignature = indexSignatures.stringSignature; numericIndexerSignature = indexSignatures.numericSignature; + var inInferentialTyping = context.isInferentiallyTyping(); if (stringIndexerSignature) { - allMemberTypes = [stringIndexerSignature.returnType]; + allMemberTypes = inInferentialTyping ? [] : [stringIndexerSignature.returnType]; } if (numericIndexerSignature) { - allNumericMemberTypes = [numericIndexerSignature.returnType]; + allNumericMemberTypes = inInferentialTyping ? [] : [numericIndexerSignature.returnType]; } } @@ -44994,8 +46275,8 @@ var TypeScript; } }; var decl = objectLiteralSymbol.getDeclarations()[0]; - var indexerReturnType = this.widenType(this.findBestCommonType(typeCollection, context)); - if (indexerReturnType == contextualIndexSignature.returnType) { + var indexerReturnType = this.findBestCommonType(typeCollection, context).widenedType(this, null, context); + if (indexerReturnType === contextualIndexSignature.returnType) { objectLiteralSymbol.addIndexSignature(contextualIndexSignature); } else { this.semanticInfoChain.addSyntheticIndexSignature(decl, objectLiteralSymbol, this.getASTForDecl(decl), contextualIndexSignature.parameters[0].name, contextualIndexSignature.parameters[0].type, indexerReturnType); @@ -45030,7 +46311,7 @@ var TypeScript; this.resolveDeclaredSymbol(contextualType, context); if (contextualType) { - var indexSignatures = this.getBothKindsOfIndexSignatures(contextualType, context); + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); if (indexSignatures.numericSignature) { contextualElementType = indexSignatures.numericSignature.returnType; } @@ -45039,7 +46320,7 @@ var TypeScript; if (elements) { if (contextualElementType) { - context.pushContextualType(contextualElementType, context.inProvisionalResolution(), null); + context.propagateContextualType(contextualElementType); } for (var i = 0, n = elements.nonSeparatorCount(); i < n; i++) { @@ -45047,7 +46328,7 @@ var TypeScript; } if (contextualElementType) { - context.popContextualType(); + context.popAnyContextualType(); } } @@ -45055,7 +46336,8 @@ var TypeScript; elementType = elementTypes[0]; } var collection; - if (contextualElementType) { + + if (contextualElementType && !context.isInferentiallyTyping()) { if (!elementType) { elementType = contextualElementType; } @@ -45085,19 +46367,7 @@ var TypeScript; elementType = this.semanticInfoChain.undefinedTypeSymbol; } - var arraySymbol = elementType.getArrayType(); - - if (!arraySymbol) { - arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); - - if (!arraySymbol) { - arraySymbol = this.semanticInfoChain.anyTypeSymbol; - } - - elementType.setArrayType(arraySymbol); - } - - return arraySymbol; + return this.getArrayType(elementType); }; PullTypeResolver.prototype.resolveElementAccessExpression = function (callEx, context) { @@ -45121,6 +46391,8 @@ var TypeScript; var targetTypeSymbol = targetSymbol.type; + targetTypeSymbol = this.getApparentType(targetTypeSymbol); + if (this.isAnyOrEquivalent(targetTypeSymbol)) { return { symbol: targetTypeSymbol }; } @@ -45136,7 +46408,7 @@ var TypeScript; if (callEx.argumentExpression.kind() === 14 /* StringLiteral */ || callEx.argumentExpression.kind() === 13 /* NumericLiteral */) { var memberName = callEx.argumentExpression.kind() === 14 /* StringLiteral */ ? TypeScript.stripStartAndEndQuotes(callEx.argumentExpression.text()) : callEx.argumentExpression.valueText(); - var member = this.getMemberSymbol(memberName, 68147712 /* SomeValue */, targetTypeSymbol); + var member = this._getNamedPropertySymbolOfAugmentedType(memberName, targetTypeSymbol); if (member) { this.resolveDeclaredSymbol(member, context); @@ -45145,11 +46417,7 @@ var TypeScript; } } - if (targetTypeSymbol == this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { - targetTypeSymbol = this.cachedStringInterfaceType(); - } - - var signatures = this.getBothKindsOfIndexSignatures(targetTypeSymbol, context); + var signatures = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(targetTypeSymbol, context); var stringSignature = signatures.stringSignature; var numberSignature = signatures.numericSignature; @@ -45159,6 +46427,9 @@ var TypeScript; } else if (stringSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol)) { return { symbol: stringSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; } else if (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol) { + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(callEx.argumentExpression, TypeScript.DiagnosticCode.Index_signature_of_object_type_implicitly_has_an_any_type)); + } return { symbol: this.semanticInfoChain.anyTypeSymbol }; } else { return { @@ -45168,8 +46439,16 @@ var TypeScript; } }; - PullTypeResolver.prototype.getBothKindsOfIndexSignatures = function (enclosingType, context) { - var signatures = enclosingType.getIndexSignatures(); + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesIncludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, true); + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesExcludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, false); + }; + + PullTypeResolver.prototype._getBothKindsOfIndexSignatures = function (enclosingType, context, includeAugmentedType) { + var signatures = includeAugmentedType ? enclosingType.getIndexSignaturesOfAugmentedType(this, this.cachedFunctionInterfaceType(), this.cachedObjectInterfaceType()) : enclosingType.getIndexSignatures(); var stringSignature = null; var numberSignature = null; @@ -45208,6 +46487,27 @@ var TypeScript; }; }; + PullTypeResolver.prototype._addUnhiddenSignaturesFromBaseType = function (derivedTypeSignatures, baseTypeSignatures, signaturesBeingAggregated) { + var _this = this; + if (!derivedTypeSignatures) { + signaturesBeingAggregated.push.apply(signaturesBeingAggregated, baseTypeSignatures); + return; + } + + var context = new TypeScript.PullTypeResolutionContext(this); + for (var i = 0; i < baseTypeSignatures.length; i++) { + var baseSignature = baseTypeSignatures[i]; + + var signatureIsHidden = TypeScript.ArrayUtilities.any(derivedTypeSignatures, function (sig) { + return _this.signaturesAreIdenticalWithNewEnclosingTypes(baseSignature, sig, context, false); + }); + + if (!signatureIsHidden) { + signaturesBeingAggregated.push(baseSignature); + } + } + }; + PullTypeResolver.prototype.resolveBinaryAdditionOperation = function (binaryExpression, context) { var lhsExpression = this.resolveAST(binaryExpression.left, false, context); var lhsType = lhsExpression.type; @@ -45215,22 +46515,23 @@ var TypeScript; if (TypeScript.PullHelpers.symbolIsEnum(lhsType)) { lhsType = this.semanticInfoChain.numberTypeSymbol; - } else if (lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol) { - if (rhsType != this.semanticInfoChain.nullTypeSymbol && rhsType != this.semanticInfoChain.undefinedTypeSymbol) { - lhsType = rhsType; - } else { - lhsType = this.semanticInfoChain.anyTypeSymbol; - } } if (TypeScript.PullHelpers.symbolIsEnum(rhsType)) { rhsType = this.semanticInfoChain.numberTypeSymbol; - } else if (rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol) { - if (lhsType != this.semanticInfoChain.nullTypeSymbol && lhsType != this.semanticInfoChain.undefinedTypeSymbol) { - rhsType = lhsType; + } + + var isLhsTypeNullOrUndefined = lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol; + var isRhsTypeNullOrUndefined = rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol; + + if (isLhsTypeNullOrUndefined) { + if (isRhsTypeNullOrUndefined) { + lhsType = rhsType = this.semanticInfoChain.anyTypeSymbol; } else { - rhsType = this.semanticInfoChain.anyTypeSymbol; + lhsType = rhsType; } + } else if (isRhsTypeNullOrUndefined) { + rhsType = lhsType; } var exprType = null; @@ -45310,13 +46611,13 @@ var TypeScript; var leftType = this.resolveAST(binex.left, isContextuallyTyped, context).type; var rightType = this.resolveAST(binex.right, isContextuallyTyped, context).type; - return this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + return context.isInferentiallyTyping() ? this.bestCommonTypeOfTwoTypes(leftType, rightType, context) : this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); } else { var leftType = this.resolveAST(binex.left, false, context).type; - context.pushContextualType(leftType, context.inProvisionalResolution(), null); + context.pushNewContextualType(leftType); var rightType = this.resolveAST(binex.right, true, context).type; - context.popContextualType(); + context.popAnyContextualType(); return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); } @@ -45333,7 +46634,7 @@ var TypeScript; }; PullTypeResolver.prototype.computeTypeOfConditionalExpression = function (leftType, rightType, isContextuallyTyped, context) { - if (isContextuallyTyped) { + if (isContextuallyTyped && !context.isInferentiallyTyping()) { var contextualType = context.getContextualType(); return this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); } else { @@ -45373,11 +46674,11 @@ var TypeScript; PullTypeResolver.prototype.conditionExpressionTypesAreValid = function (leftType, rightType, expressionType, isContextuallyTyped, context) { if (isContextuallyTyped) { var contextualType = context.getContextualType(); - if (this.typesAreIdentical(expressionType, leftType) || this.typesAreIdentical(expressionType, rightType) || this.typesAreIdentical(expressionType, contextualType)) { + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context) || this.typesAreIdentical(expressionType, contextualType, context)) { return true; } } else { - if (this.typesAreIdentical(expressionType, leftType) || this.typesAreIdentical(expressionType, rightType)) { + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context)) { return true; } } @@ -45414,7 +46715,7 @@ var TypeScript; if (this.canTypeCheckAST(callEx, context)) { this.setTypeChecked(callEx, context); } - if (symbol != this.semanticInfoChain.anyTypeSymbol) { + if (symbol !== this.semanticInfoChain.anyTypeSymbol) { this.setSymbolForAST(callEx, symbol, context); } this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); @@ -45424,7 +46725,7 @@ var TypeScript; } var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); - if (additionalResults && (callResolutionData != additionalResults)) { + if (additionalResults && (callResolutionData !== additionalResults)) { additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; additionalResults.candidateSignature = callResolutionData.candidateSignature; additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; @@ -45446,13 +46747,13 @@ var TypeScript; for (var i = 0; i < len; i++) { var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.pushNewContextualType(contextualType); } - this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType != null, context); + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); contextualType = null; } } @@ -45500,12 +46801,11 @@ var TypeScript; var signatures = isSuperCall ? targetTypeSymbol.getConstructSignatures() : targetTypeSymbol.getCallSignatures(); - if (!signatures.length && (targetTypeSymbol.kind == 33554432 /* ConstructorType */)) { + if (!signatures.length && (targetTypeSymbol.kind === 33554432 /* ConstructorType */)) { this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, [targetTypeSymbol.toString()]), additionalResults, context); } - var typeArgs = null; - var typeReplacementMap = null; + var explicitTypeArgs = null; var couldNotFindGenericOverload = false; var couldNotAssignToConstraint; var constraintDiagnostic = null; @@ -45513,21 +46813,19 @@ var TypeScript; var diagnostics = []; if (callEx.argumentList.typeArgumentList) { - typeArgs = []; + explicitTypeArgs = []; if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { - typeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); } } - } else if (isSuperCall && targetTypeSymbol.isGeneric()) { - typeArgs = targetTypeSymbol.getTypeArguments(); } var triedToInferTypeArgs = false; var resolvedSignatures = []; - var inferredTypeArgs; + var inferredOrExplicitTypeArgs; var specializedSignature; var typeParameters; var typeConstraint = null; @@ -45539,86 +46837,61 @@ var TypeScript; couldNotAssignToConstraint = false; if (signatures[i].isGeneric() && typeParameters.length) { - if (typeArgs) { - if (typeArgs.length == typeParameters.length) { - inferredTypeArgs = typeArgs; - } else { - typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, typeArgs.length]); - continue; - } - } else if (!typeArgs && callEx.argumentList.arguments && callEx.argumentList.arguments.nonSeparatorCount()) { - inferredTypeArgs = this.inferArgumentTypesForSignature(signatures[i], new TypeScript.ArgumentInferenceContext(this, callEx.argumentList.arguments), new TypeComparisonInfo(), context); - triedToInferTypeArgs = true; - } else { - inferredTypeArgs = []; + if (isSuperCall && targetTypeSymbol.isGeneric() && !callEx.argumentList.typeArgumentList) { + explicitTypeArgs = signatures[i].returnType.getTypeArguments(); } - if (inferredTypeArgs) { - typeReplacementMap = []; - - if (inferredTypeArgs.length) { - if (inferredTypeArgs.length != typeParameters.length) { - continue; - } - - if (targetTypeReplacementMap) { - for (var symbolID in targetTypeReplacementMap) { - if (targetTypeReplacementMap.hasOwnProperty(symbolID)) { - typeReplacementMap[symbolID] = targetTypeReplacementMap[symbolID]; - } - } - } - - for (var j = 0; j < typeParameters.length; j++) { - typeReplacementMap[typeParameters[j].pullSymbolID] = inferredTypeArgs[j]; - } - for (var j = 0; j < typeParameters.length; j++) { - typeConstraint = typeParameters[j].getConstraint(); - - if (typeConstraint) { - if (typeConstraint.isTypeParameter()) { - for (var k = 0; k < typeParameters.length && k < inferredTypeArgs.length; k++) { - if (typeParameters[k] == typeConstraint) { - typeConstraint = inferredTypeArgs[k]; - } else { - typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); - } - } - } else if (typeConstraint.isGeneric()) { - typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); - } - - if (!this.sourceIsAssignableToTarget(inferredTypeArgs[j], typeConstraint, targetAST, context, null, true)) { - var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); - constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); - couldNotAssignToConstraint = true; - } - - if (couldNotAssignToConstraint) { - break; - } - } - } + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; } else { - if (triedToInferTypeArgs) { - continue; - } - - for (var j = 0; j < typeParameters.length; j++) { - typeReplacementMap[typeParameters[j].pullSymbolID] = this.semanticInfoChain.emptyTypeSymbol; - } - } - - if (couldNotAssignToConstraint) { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); continue; } + } else { + TypeScript.Debug.assert(callEx.argumentList); + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, signatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } - specializedSignature = this.instantiateSignature(signatures[i], typeReplacementMap, true); + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); - if (specializedSignature) { - resolvedSignatures[resolvedSignatures.length] = specializedSignature; + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } } } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(signatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } } else { if (!(callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { resolvedSignatures[resolvedSignatures.length] = signatures[i]; @@ -45643,7 +46916,7 @@ var TypeScript; this.resolveAST(callEx.argumentList.arguments, false, context); if (!couldNotFindGenericOverload) { - if (this.cachedFunctionInterfaceType() && this.sourceIsSubtypeOfTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), targetAST, context)) { + if (this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), targetAST, context)) { if (callEx.argumentList.typeArgumentList) { this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); } @@ -45662,7 +46935,7 @@ var TypeScript; return this.getNewErrorTypeSymbol(); } - var signature = this.resolveOverloads(callEx, signatures, callEx.argumentList.typeArgumentList != null, context, diagnostics); + var signature = this.resolveOverloads(callEx, signatures, callEx.argumentList.typeArgumentList !== null, context, diagnostics); var useBeforeResolutionSignatures = signature == null; if (!signature) { @@ -45681,10 +46954,11 @@ var TypeScript; signature = signatures[0]; } - if (!signature.isGeneric() && callEx.argumentList.typeArgumentList) { + var rootSignature = signature.getRootSymbol(); + if (!rootSignature.isGeneric() && callEx.argumentList.typeArgumentList) { this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); - } else if (signature.isGeneric() && callEx.argumentList.typeArgumentList && signature.getTypeParameters() && (callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount() != signature.getTypeParameters().length)) { - this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [signature.getTypeParameters().length, callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()]), additionalResults, context); + } else if (rootSignature.isGeneric() && callEx.argumentList.typeArgumentList && rootSignature.getTypeParameters() && (callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount() !== rootSignature.getTypeParameters().length)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [rootSignature.getTypeParameters().length, callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()]), additionalResults, context); } var returnType = isSuperCall ? this.semanticInfoChain.voidTypeSymbol : signature.returnType; @@ -45710,14 +46984,14 @@ var TypeScript; } if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.pushNewContextualType(contextualType); actualParametersContextTypeSymbols[i] = contextualType; } - this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType != null, context); + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); contextualType = null; } } @@ -45763,7 +47037,7 @@ var TypeScript; } var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); - if (additionalResults && (callResolutionData != additionalResults)) { + if (additionalResults && (callResolutionData !== additionalResults)) { additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; additionalResults.candidateSignature = callResolutionData.candidateSignature; additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; @@ -45785,13 +47059,13 @@ var TypeScript; for (var i = 0; i < len; i++) { var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.pushNewContextualType(contextualType); } - this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType != null, context); + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); contextualType = null; } } @@ -45810,6 +47084,7 @@ var TypeScript; }; PullTypeResolver.prototype.computeObjectCreationExpressionSymbol = function (callEx, context, additionalResults) { + var _this = this; var returnType = null; var targetSymbol = this.resolveAST(callEx.expression, false, context); @@ -45819,8 +47094,7 @@ var TypeScript; var constructSignatures = targetTypeSymbol.getConstructSignatures(); - var typeArgs = null; - var typeReplacementMap = null; + var explicitTypeArgs = null; var usedCallSignaturesInstead = false; var couldNotAssignToConstraint; var constraintDiagnostic = null; @@ -45846,18 +47120,18 @@ var TypeScript; if (constructSignatures.length) { if (callEx.argumentList && callEx.argumentList.typeArgumentList) { - typeArgs = []; + explicitTypeArgs = []; if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { - typeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); } } } if (targetTypeSymbol.isGeneric()) { var resolvedSignatures = []; - var inferredTypeArgs; + var inferredOrExplicitTypeArgs; var specializedSignature; var typeParameters; var typeConstraint = null; @@ -45870,85 +47144,59 @@ var TypeScript; if (constructSignatures[i].isGeneric()) { typeParameters = constructSignatures[i].getTypeParameters(); - if (typeArgs) { - if (typeArgs.length == typeParameters.length) { - inferredTypeArgs = typeArgs; + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; } else { - typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, typeArgs.length]); + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); continue; } - } else if (!typeArgs && callEx.argumentList && callEx.argumentList.arguments && callEx.argumentList.arguments.nonSeparatorCount()) { - inferredTypeArgs = this.inferArgumentTypesForSignature(constructSignatures[i], new TypeScript.ArgumentInferenceContext(this, callEx.argumentList.arguments), new TypeComparisonInfo(), context); + } else if (callEx.argumentList) { + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, constructSignatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); triedToInferTypeArgs = true; } else { - inferredTypeArgs = []; + inferredOrExplicitTypeArgs = TypeScript.ArrayUtilities.select(typeParameters, function (typeParameter) { + return typeParameter.getDefaultConstraint(_this.semanticInfoChain); + }); } - if (inferredTypeArgs) { - typeReplacementMap = []; + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); - if (inferredTypeArgs.length) { - if (inferredTypeArgs.length < typeParameters.length) { - continue; - } + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; - if (targetTypeReplacementMap) { - for (var symbolID in targetTypeReplacementMap) { - if (targetTypeReplacementMap.hasOwnProperty(symbolID)) { - typeReplacementMap[symbolID] = targetTypeReplacementMap[symbolID]; - } + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); } - } - for (var j = 0; j < typeParameters.length; j++) { - typeReplacementMap[typeParameters[j].pullSymbolID] = inferredTypeArgs[j]; - } - for (var j = 0; j < typeParameters.length; j++) { - typeConstraint = typeParameters[j].getConstraint(); - - if (typeConstraint) { - if (typeConstraint.isTypeParameter()) { - for (var k = 0; k < typeParameters.length && k < inferredTypeArgs.length; k++) { - if (typeParameters[k] == typeConstraint) { - typeConstraint = inferredTypeArgs[k]; - } else { - typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); - } - } - } else if (typeConstraint.isGeneric()) { - typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); - } - - if (!this.sourceIsAssignableToTarget(inferredTypeArgs[j], typeConstraint, targetAST, context, null, true)) { - var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); - constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); - couldNotAssignToConstraint = true; - } - - if (couldNotAssignToConstraint) { - break; - } + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; } - } - } else { - if (triedToInferTypeArgs) { - continue; - } else { - for (var j = 0; j < typeParameters.length; j++) { - typeReplacementMap[typeParameters[j].pullSymbolID] = this.semanticInfoChain.emptyTypeSymbol; + + if (couldNotAssignToConstraint) { + break; } } } + } - if (couldNotAssignToConstraint) { - continue; - } + if (couldNotAssignToConstraint) { + continue; + } - specializedSignature = this.instantiateSignature(constructSignatures[i], typeReplacementMap, true); + specializedSignature = this.instantiateSignature(constructSignatures[i], typeReplacementMap); - if (specializedSignature) { - resolvedSignatures[resolvedSignatures.length] = specializedSignature; - } + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; } } else { if (!(callEx.argumentList && callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { @@ -45960,7 +47208,7 @@ var TypeScript; constructSignatures = resolvedSignatures; } - var signature = this.resolveOverloads(callEx, constructSignatures, callEx.argumentList && callEx.argumentList.typeArgumentList != null, context, diagnostics); + var signature = this.resolveOverloads(callEx, constructSignatures, callEx.argumentList && callEx.argumentList.typeArgumentList !== null, context, diagnostics); additionalResults.targetSymbol = targetSymbol; additionalResults.resolvedSignatures = constructSignatures; @@ -45998,15 +47246,15 @@ var TypeScript; returnType = signature.returnType; if (returnType && !signature.isGeneric() && returnType.isGeneric() && !returnType.getIsSpecialized()) { - if (typeArgs && typeArgs.length) { - returnType = this.createInstantiatedType(returnType, typeArgs); + if (explicitTypeArgs && explicitTypeArgs.length) { + returnType = this.createInstantiatedType(returnType, explicitTypeArgs); } else { returnType = this.instantiateTypeToAny(returnType, context); } } if (usedCallSignaturesInstead) { - if (returnType != this.semanticInfoChain.voidTypeSymbol) { + if (returnType !== this.semanticInfoChain.voidTypeSymbol) { this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Call_signatures_used_in_a_new_expression_must_have_a_void_return_type), additionalResults, context); return this.getNewErrorTypeSymbol(); @@ -46044,14 +47292,14 @@ var TypeScript; } if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.pushNewContextualType(contextualType); actualParametersContextTypeSymbols[i] = contextualType; } - this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType != null, context); + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); contextualType = null; } } @@ -46080,23 +47328,18 @@ var TypeScript; return this.getNewErrorTypeSymbol(); }; - PullTypeResolver.prototype.instantiateSignatureInContext = function (signatureA, signatureB, context) { + PullTypeResolver.prototype.instantiateSignatureInContext = function (signatureAToInstantiate, contextualSignatureB, context, shouldFixContextualSignatureParameterTypes) { var typeReplacementMap = []; var inferredTypeArgs; var specializedSignature; - var typeParameters = signatureA.getTypeParameters(); + var typeParameters = signatureAToInstantiate.getTypeParameters(); var typeConstraint = null; - var fixedParameterTypes = []; + var typeArgumentInferenceContext = new TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext(this, context, signatureAToInstantiate, contextualSignatureB, shouldFixContextualSignatureParameterTypes); + inferredTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); - for (var i = 0; i < signatureB.parameters.length; i++) { - fixedParameterTypes.push(signatureB.parameters[i].isVarArg ? signatureB.parameters[i].type.getElementType() : signatureB.parameters[i].type); - } - - inferredTypeArgs = this.inferArgumentTypesForSignature(signatureA, new TypeScript.ArgumentInferenceContext(this, fixedParameterTypes), new TypeComparisonInfo(), context); - - var functionTypeA = signatureA.functionType; - var functionTypeB = signatureB.functionType; + var functionTypeA = signatureAToInstantiate.functionType; + var functionTypeB = contextualSignatureB.functionType; var enclosingTypeParameterMap; if (functionTypeA) { @@ -46115,34 +47358,9 @@ var TypeScript; } } - for (var i = 0; i < typeParameters.length; i++) { - typeReplacementMap[typeParameters[i].pullSymbolID] = inferredTypeArgs[i]; - } - for (var i = 0; i < typeParameters.length; i++) { - typeConstraint = typeParameters[i].getConstraint(); + TypeScript.PullInstantiationHelpers.updateTypeParameterArgumentMap(typeParameters, inferredTypeArgs, typeReplacementMap); - if (typeConstraint) { - if (typeConstraint.isTypeParameter()) { - for (var j = 0; j < typeParameters.length && j < inferredTypeArgs.length; j++) { - if (typeParameters[j] == typeConstraint) { - typeConstraint = inferredTypeArgs[j]; - } - } - } else if (typeConstraint.isGeneric()) { - typeConstraint = TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, typeConstraint, typeReplacementMap); - } - - if (!this.sourceIsAssignableToTarget(inferredTypeArgs[i], typeConstraint, null, context, null, true)) { - if (this.signaturesAreIdentical(signatureA, signatureB, true)) { - return signatureA; - } else { - return null; - } - } - } - } - - return this.instantiateSignature(signatureA, typeReplacementMap, true); + return this.instantiateSignature(signatureAToInstantiate, typeReplacementMap); }; PullTypeResolver.prototype.resolveCastExpression = function (assertionExpression, context) { @@ -46158,16 +47376,21 @@ var TypeScript; PullTypeResolver.prototype.typeCheckCastExpression = function (assertionExpression, context, typeAssertionType) { this.setTypeChecked(assertionExpression, context); - context.pushContextualType(typeAssertionType, context.inProvisionalResolution(), null); + context.pushNewContextualType(typeAssertionType); var exprType = this.resolveAST(assertionExpression.expression, true, context).type; - context.popContextualType(); + context.popAnyContextualType(); this.resolveDeclaredSymbol(typeAssertionType, context); this.resolveDeclaredSymbol(exprType, context); var comparisonInfo = new TypeComparisonInfo(); - var isAssignable = this.sourceIsAssignableToTarget(typeAssertionType, exprType, assertionExpression, context, comparisonInfo) || this.sourceIsAssignableToTarget(exprType, typeAssertionType, assertionExpression, context, comparisonInfo); + var isAssignable = this.sourceIsAssignableToTarget(exprType, typeAssertionType, assertionExpression, context, comparisonInfo); + + if (!isAssignable) { + var widenedExprType = exprType.widenedType(this, assertionExpression.expression, context); + isAssignable = this.sourceIsAssignableToTarget(typeAssertionType, widenedExprType, assertionExpression, context, comparisonInfo); + } if (!isAssignable) { var enclosingSymbol = this.getEnclosingSymbolForAST(assertionExpression); @@ -46183,9 +47406,9 @@ var TypeScript; var leftExpr = this.resolveAST(binaryExpression.left, false, context); var leftType = leftExpr.type; - context.pushContextualType(leftType, context.inProvisionalResolution(), null); + context.pushNewContextualType(leftType); var rightType = this.resolveAST(binaryExpression.right, true, context).type; - context.popContextualType(); + context.popAnyContextualType(); rightType = this.getInstanceTypeForAssignment(binaryExpression.left, rightType, context); @@ -46228,30 +47451,82 @@ var TypeScript; } if (type.isArrayNamedTypeReference()) { - var elementType = this.widenType(type.getElementType(), null, context); - - if (this.compilationSettings.noImplicitAny() && ast && ast.kind() === 214 /* ArrayLiteralExpression */) { - if (elementType === this.semanticInfoChain.anyTypeSymbol && type.getElementType() !== this.semanticInfoChain.anyTypeSymbol) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Array_Literal_implicitly_has_an_any_type_from_widening)); - } - } - - var arraySymbol = elementType.getArrayType(); - - if (!arraySymbol) { - arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); - - if (!arraySymbol) { - arraySymbol = this.semanticInfoChain.anyTypeSymbol; - } - } - - return arraySymbol; + return this.widenArrayType(type, ast, context); + } else if (type.kind === 256 /* ObjectLiteral */) { + return this.widenObjectLiteralType(type, ast, context); } return type; }; + PullTypeResolver.prototype.widenArrayType = function (type, ast, context) { + var elementType = type.getElementType().widenedType(this, ast, context); + + if (this.compilationSettings.noImplicitAny() && ast) { + if (elementType === this.semanticInfoChain.anyTypeSymbol && type.getElementType() !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Array_Literal_implicitly_has_an_any_type_from_widening)); + } + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.widenObjectLiteralType = function (type, ast, context) { + if (!this.needsToWidenObjectLiteralType(type, ast, context)) { + return type; + } + + TypeScript.Debug.assert(type.name === ""); + var newObjectTypeSymbol = new TypeScript.PullTypeSymbol(type.name, type.kind); + var declsOfObjectType = type.getDeclarations(); + TypeScript.Debug.assert(declsOfObjectType.length === 1); + newObjectTypeSymbol.addDeclaration(declsOfObjectType[0]); + var members = type.getMembers(); + + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + + var widenedMemberType = members[i].type.widenedType(this, ast, context); + var newMember = new TypeScript.PullSymbol(members[i].name, members[i].kind); + + var declsOfMember = members[i].getDeclarations(); + + newMember.addDeclaration(declsOfMember[0]); + newMember.type = widenedMemberType; + newObjectTypeSymbol.addMember(newMember); + newMember.setResolved(); + + if (this.compilationSettings.noImplicitAny() && ast && widenedMemberType === this.semanticInfoChain.anyTypeSymbol && memberType !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Object_literal_s_property_0_implicitly_has_an_any_type_from_widening, [members[i].name])); + } + } + + var indexers = type.getIndexSignatures(); + for (var i = 0; i < indexers.length; i++) { + var newIndexer = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var parameter = indexers[i].parameters[0]; + var newParameter = new TypeScript.PullSymbol(parameter.name, parameter.kind); + newParameter.type = parameter.type; + newIndexer.addParameter(newParameter); + newIndexer.returnType = indexers[i].returnType; + newObjectTypeSymbol.addIndexSignature(newIndexer); + } + + return newObjectTypeSymbol; + }; + + PullTypeResolver.prototype.needsToWidenObjectLiteralType = function (type, ast, context) { + var members = type.getMembers(); + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + if (memberType !== memberType.widenedType(this, ast, context)) { + return true; + } + } + + return false; + }; + PullTypeResolver.prototype.findBestCommonType = function (collection, context, comparisonInfo) { var len = collection.getLength(); @@ -46268,15 +47543,11 @@ var TypeScript; PullTypeResolver.prototype.typeIsBestCommonTypeCandidate = function (candidateType, collection, context) { for (var i = 0; i < collection.getLength(); i++) { var otherType = collection.getTypeAtIndex(i); - if (candidateType == otherType) { + if (candidateType === otherType) { continue; } - if (candidateType.isTypeParameter() && !otherType.isTypeParameter()) { - return false; - } else if (!candidateType.isTypeParameter() && otherType.isTypeParameter()) { - continue; - } else if (!this.sourceIsSubtypeOfTarget(otherType, candidateType, null, context)) { + if (!this.sourceIsSubtypeOfTarget(otherType, candidateType, null, context)) { return false; } } @@ -46284,7 +47555,7 @@ var TypeScript; return true; }; - PullTypeResolver.prototype.typesAreIdenticalInEnclosingTypes = function (t1, t2, t1EnclosingType, t2EnclosingType, val) { + PullTypeResolver.prototype.typesAreIdenticalInEnclosingTypes = function (t1, t2, context) { t1 = this.getSymbolForRelationshipCheck(t1); t2 = this.getSymbolForRelationshipCheck(t2); @@ -46293,17 +47564,22 @@ var TypeScript; } if (t1 && t2) { - var t1GenerativeTypeKind = t1EnclosingType ? t1.getGenerativeTypeClassification(t1EnclosingType) : 0 /* Unknown */; - var t2GenerativeTypeKind = t2EnclosingType ? t2.getGenerativeTypeClassification(t2EnclosingType) : 0 /* Unknown */; - if (t1GenerativeTypeKind == 3 /* InfinitelyExpanding */ || t2GenerativeTypeKind == 3 /* InfinitelyExpanding */) { - return this.infinitelyExpandingTypesAreIdentical(t1, t2); + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingTypesAreIdentical(t1, t2, context); } } - return this.typesAreIdentical(t1, t2, val); + return this.typesAreIdentical(t1, t2, context); }; - PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, val) { + PullTypeResolver.prototype.typesAreIdenticalWithNewEnclosingTypes = function (t1, t2, context) { + var enclosingTypeWalkers = context.resetEnclosingTypeWalkers(); + var areTypesIdentical = this.typesAreIdentical(t1, t2, context); + context.setEnclosingTypeWalkers(enclosingTypeWalkers); + return areTypesIdentical; + }; + + PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, context) { t1 = this.getSymbolForRelationshipCheck(t1); t2 = this.getSymbolForRelationshipCheck(t2); @@ -46315,12 +47591,8 @@ var TypeScript; return false; } - if (val && t1.isPrimitive() && t1.isStringConstant() && t2 === this.semanticInfoChain.stringTypeSymbol) { - return (val.kind() === 14 /* StringLiteral */) && (TypeScript.stripStartAndEndQuotes(val.text()) === TypeScript.stripStartAndEndQuotes(t1.name)); - } - - if (val && t2.isPrimitive() && t2.isStringConstant() && t2 === this.semanticInfoChain.stringTypeSymbol) { - return (val.kind() === 14 /* StringLiteral */) && (TypeScript.stripStartAndEndQuotes(val.text()) === TypeScript.stripStartAndEndQuotes(t2.name)); + if (TypeScript.hasFlag(t1.kind, 64 /* Enum */) || TypeScript.hasFlag(t2.kind, 64 /* Enum */)) { + return false; } if (t1.isPrimitive() && t1.isStringConstant() && t2.isPrimitive() && t2.isStringConstant()) { @@ -46335,7 +47607,12 @@ var TypeScript; return true; } - if (t1.isTypeParameter() != t2.isTypeParameter()) { + var isIdentical = this.identicalCache.valueAt(t1.pullSymbolID, t2.pullSymbolID); + if (isIdentical != undefined) { + return isIdentical; + } + + if (t1.isTypeParameter() !== t2.isTypeParameter()) { return false; } else if (t1.isTypeParameter()) { var t1ParentDeclaration = t1.getDeclarations()[0].getParentDecl(); @@ -46348,27 +47625,42 @@ var TypeScript; } } - var isIdentical = this.identicalCache.valueAt(t1.pullSymbolID, t2.pullSymbolID); - if (isIdentical != undefined) { - return isIdentical; - } - - if ((t1.kind & 64 /* Enum */) || (t2.kind & 64 /* Enum */)) { - return t1.getAssociatedContainerType() === t2 || t2.getAssociatedContainerType() === t1; - } - - if (t1.isPrimitive() != t2.isPrimitive()) { + if (t1.isPrimitive() !== t2.isPrimitive()) { return false; } - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, false); + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, true); + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(t1, t2); + isIdentical = this.typesAreIdenticalWorker(t1, t2, context); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, isIdentical); + + return isIdentical; + }; + + PullTypeResolver.prototype.typesAreIdenticalWorker = function (t1, t2, context) { + if (t1.getIsSpecialized() && t2.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(t1) === TypeScript.PullHelpers.getRootType(t2) && TypeScript.PullHelpers.getRootType(t1).isNamedTypeSymbol()) { + var t1TypeArguments = t1.getTypeArguments(); + var t2TypeArguments = t2.getTypeArguments(); + + if (t1TypeArguments && t2TypeArguments) { + for (var i = 0; i < t1TypeArguments.length; i++) { + if (!this.typesAreIdenticalWithNewEnclosingTypes(t1TypeArguments[i], t2TypeArguments[i], context)) { + return false; + } + } + } + + return true; + } + } if (t1.hasMembers() && t2.hasMembers()) { var t1Members = t1.getAllMembers(68147712 /* SomeValue */, 0 /* all */); var t2Members = t2.getAllMembers(68147712 /* SomeValue */, 0 /* all */); - if (t1Members.length != t2Members.length) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); + if (t1Members.length !== t2Members.length) { return false; } @@ -46380,22 +47672,13 @@ var TypeScript; for (var iMember = 0; iMember < t1Members.length; iMember++) { t1MemberSymbol = t1Members[iMember]; - t2MemberSymbol = this.getMemberSymbol(t1MemberSymbol.name, 68147712 /* SomeValue */, t2); + t2MemberSymbol = this.getNamedPropertySymbol(t1MemberSymbol.name, 68147712 /* SomeValue */, t2); - if (!t2MemberSymbol || (t1MemberSymbol.isOptional != t2MemberSymbol.isOptional)) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); - return false; - } - - t1MemberType = t1MemberSymbol.type; - t2MemberType = t2MemberSymbol.type; - - if (!this.typesAreIdenticalInEnclosingTypes(t1MemberType, t2MemberType, t1, t2)) { + if (!this.propertiesAreIdentical(t1MemberSymbol, t2MemberSymbol, context)) { return false; } } } else if (t1.hasMembers() || t2.hasMembers()) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); return false; } @@ -46408,26 +47691,57 @@ var TypeScript; var t1IndexSigs = t1.getIndexSignatures(); var t2IndexSigs = t2.getIndexSignatures(); - if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs)) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); + if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs, context)) { return false; } - if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs)) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); + if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs, context)) { return false; } - if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs)) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); + if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs, context)) { return false; } - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, true); return true; }; - PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { + PullTypeResolver.prototype.propertiesAreIdentical = function (propertySymbol1, propertySymbol2, context) { + if (!propertySymbol2 || (propertySymbol1.isOptional !== propertySymbol2.isOptional)) { + return false; + } + + var t1MemberSymbolIsPrivate = propertySymbol1.anyDeclHasFlag(2 /* Private */); + var t2MemberSymbolIsPrivate = propertySymbol2.anyDeclHasFlag(2 /* Private */); + + if (t1MemberSymbolIsPrivate !== t2MemberSymbolIsPrivate) { + return false; + } else if (t2MemberSymbolIsPrivate && t1MemberSymbolIsPrivate) { + var t1MemberSymbolDecl = propertySymbol1.getDeclarations()[0]; + var sourceDecl = propertySymbol2.getDeclarations()[0]; + if (t1MemberSymbolDecl !== sourceDecl) { + return false; + } + } + + var t1MemberType = propertySymbol1.type; + var t2MemberType = propertySymbol2.type; + + context.walkMemberTypes(propertySymbol1.name); + var areMemberTypesIdentical = this.typesAreIdenticalInEnclosingTypes(t1MemberType, t2MemberType, context); + context.postWalkMemberTypes(); + return areMemberTypesIdentical; + }; + + PullTypeResolver.prototype.propertiesAreIdenticalWithNewEnclosingTypes = function (type1, type2, property1, property2, context) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(type1, type2); + var arePropertiesIdentical = this.propertiesAreIdentical(property1, property2, context); + context.setEnclosingTypeWalkers(enclosingWalkers); + return arePropertiesIdentical; + }; + + PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2, context) { if (sg1 === sg2) { return true; } @@ -46436,75 +47750,15 @@ var TypeScript; return false; } - if (sg1.length != sg2.length) { + if (sg1.length !== sg2.length) { return false; } - var sig1 = null; - var sig2 = null; - var sigsMatch = false; - - for (var iSig1 = 0; iSig1 < sg1.length; iSig1++) { - sig1 = sg1[iSig1]; - - for (var iSig2 = 0; iSig2 < sg2.length; iSig2++) { - sig2 = sg2[iSig2]; - - if (this.signaturesAreIdentical(sig1, sig2)) { - sigsMatch = true; - break; - } - } - - if (sigsMatch) { - sigsMatch = false; - continue; - } - - return false; - } - - return true; - }; - - PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2, includingReturnType) { - if (typeof includingReturnType === "undefined") { includingReturnType = true; } - if (s1 === s2) { - return true; - } - - if (s1.hasVarArgs != s2.hasVarArgs) { - return false; - } - - if (s1.nonOptionalParamCount != s2.nonOptionalParamCount) { - return false; - } - - if (!!(s1.typeParameters && s1.typeParameters.length) != !!(s2.typeParameters && s2.typeParameters.length)) { - return false; - } - - if (s1.typeParameters && s2.typeParameters && (s1.typeParameters.length != s2.typeParameters.length)) { - return false; - } - - if (s1.parameters.length != s2.parameters.length) { - return false; - } - - this.resolveDeclaredSymbol(s1); - this.resolveDeclaredSymbol(s2); - - var s1Params = s1.parameters; - var s2Params = s2.parameters; - - if (includingReturnType && !this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, s1.functionType, s2.functionType)) { - return false; - } - - for (var iParam = 0; iParam < s1Params.length; iParam++) { - if (!this.typesAreIdenticalInEnclosingTypes(s1Params[iParam].type, s2Params[iParam].type, s1.functionType, s2.functionType)) { + for (var i = 0; i < sg1.length; i++) { + context.walkSignatures(sg1[i].kind, i); + var areSignaturesIdentical = this.signaturesAreIdentical(sg1[i], sg2[i], context, true); + context.postWalkSignatures(); + if (!areSignaturesIdentical) { return false; } } @@ -46512,18 +47766,152 @@ var TypeScript; return true; }; - PullTypeResolver.prototype.substituteUpperBoundForType = function (type) { - if (!type || !type.isTypeParameter()) { - return type; + PullTypeResolver.prototype.typeParametersAreIdentical = function (tp1, tp2, context) { + var typeParamsAreIdentical = this.typeParametersAreIdenticalWorker(tp1, tp2, context); + + this.setTypeParameterIdentity(tp1, tp2, undefined); + + return typeParamsAreIdentical; + }; + + PullTypeResolver.prototype.typeParametersAreIdenticalWorker = function (tp1, tp2, context) { + if (!!(tp1 && tp1.length) !== !!(tp2 && tp2.length)) { + return false; } - var constraint = type.getConstraint(); - - if (constraint && (constraint != type)) { - return this.substituteUpperBoundForType(constraint); + if (tp1 && tp2 && (tp1.length !== tp2.length)) { + return false; } - return type; + if (tp1 && tp2) { + for (var i = 0; i < tp1.length; i++) { + context.walkTypeParameterConstraints(i); + var areConstraintsIdentical = this.typesAreIdentical(tp1[i].getConstraint(), tp2[i].getConstraint(), context); + context.postWalkTypeParameterConstraints(); + if (!areConstraintsIdentical) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.setTypeParameterIdentity = function (tp1, tp2, val) { + if (tp1 && tp2 && tp1.length === tp2.length) { + for (var i = 0; i < tp1.length; i++) { + this.identicalCache.setValueAt(tp1[i].pullSymbolID, tp2[i].pullSymbolID, val); + } + } + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWithNewEnclosingTypes = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(s1, s2); + var areSignaturesIdentical = this.signaturesAreIdentical(s1, s2, context, includingReturnType); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSignaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1 === s2) { + return true; + } + + var signaturesIdentical = this.identicalCache.valueAt(s1.pullSymbolID, s2.pullSymbolID); + if (signaturesIdentical || (signaturesIdentical != undefined && includingReturnType)) { + return signaturesIdentical; + } + + var oldValue = signaturesIdentical; + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, true); + + signaturesIdentical = this.signaturesAreIdenticalWorker(s1, s2, context, includingReturnType); + + if (includingReturnType) { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, signaturesIdentical); + } else { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, oldValue); + } + + return signaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWorker = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1.hasVarArgs !== s2.hasVarArgs) { + return false; + } + + if (s1.nonOptionalParamCount !== s2.nonOptionalParamCount) { + return false; + } + + if (s1.parameters.length !== s2.parameters.length) { + return false; + } + + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var typeParametersParametersAndReturnTypesAreIdentical = this.signatureTypeParametersParametersAndReturnTypesAreIdentical(s1, s2, context, includingReturnType); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + return typeParametersParametersAndReturnTypesAreIdentical; + }; + + PullTypeResolver.prototype.signatureTypeParametersParametersAndReturnTypesAreIdentical = function (s1, s2, context, includingReturnType) { + if (!this.typeParametersAreIdenticalWorker(s1.getTypeParameters(), s2.getTypeParameters(), context)) { + return false; + } + + if (includingReturnType) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2); + context.walkReturnTypes(); + var areReturnTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + context.postWalkReturnTypes(); + if (!areReturnTypesIdentical) { + return false; + } + } + + var s1Params = s1.parameters; + var s2Params = s2.parameters; + + for (var iParam = 0; iParam < s1Params.length; iParam++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1Params[iParam]); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2Params[iParam]); + context.walkParameterTypes(iParam); + var areParameterTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1Params[iParam].type, s2Params[iParam].type, context); + context.postWalkParameterTypes(); + + if (!areParameterTypesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureReturnTypesAreIdentical = function (s1, s2, context) { + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(s1, s2); + context.walkReturnTypes(); + var returnTypeIsIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + + context.setEnclosingTypeWalkers(enclosingWalkers); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + + return returnTypeIsIdentical; }; PullTypeResolver.prototype.symbolsShareDeclaration = function (symbol1, symbol2) { @@ -46531,58 +47919,7 @@ var TypeScript; var decls2 = symbol2.getDeclarations(); if (decls1.length && decls2.length) { - return decls1[0].isEqual(decls2[0]); - } - - return false; - }; - - PullTypeResolver.prototype.sourceExtendsTarget = function (source, target, context) { - if (source.isGeneric() != target.isGeneric()) { - return false; - } - - if (source.isTypeReference() && target.isTypeReference()) { - if (source.referencedTypeSymbol.hasBase(target.referencedTypeSymbol)) { - var sourceTypeArguments = source.getTypeArguments(); - var targetTypeArguments = target.getTypeArguments(); - - if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length != targetTypeArguments.length) { - return false; - } - - for (var i = 0; i < targetTypeArguments.length; i++) { - if (!this.sourceExtendsTarget(sourceTypeArguments[i], targetTypeArguments[i], context)) { - return false; - } - } - - return true; - } - } - - if (source.hasBase(target)) { - return true; - } - - if (context.isInBaseTypeResolution() && (source.kind & (16 /* Interface */ | 8 /* Class */)) && (target.kind & (16 /* Interface */ | 8 /* Class */))) { - var sourceDecls = source.getDeclarations(); - var extendsSymbol = null; - - for (var i = 0; i < sourceDecls.length; i++) { - var sourceAST = this.semanticInfoChain.getASTForDecl(sourceDecls[i]); - var extendsClause = TypeScript.getExtendsHeritageClause(sourceAST.heritageClauses); - - if (extendsClause) { - for (var j = 0; j < extendsClause.typeNames.nonSeparatorCount(); j++) { - extendsSymbol = this.semanticInfoChain.getSymbolForAST(extendsClause.typeNames.nonSeparatorAt(j)); - - if (extendsSymbol && (extendsSymbol == target || this.sourceExtendsTarget(extendsSymbol, target, context))) { - return true; - } - } - } - } + return decls1[0] === decls2[0]; } return false; @@ -46592,44 +47929,68 @@ var TypeScript; return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); }; - PullTypeResolver.prototype.sourceMembersAreSubtypeOfTargetMembers = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourceMembersAreRelatableToTargetMembers(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceMembersAreAssignableToTargetMembers = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var areSourceMembersAreAssignableToTargetMembers = this.sourceMembersAreRelatableToTargetMembers(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSourceMembersAreAssignableToTargetMembers; }; - PullTypeResolver.prototype.sourcePropertyIsSubtypeOfTargetProperty = function (source, target, sourceProp, targetProp, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourcePropertyIsAssignableToTargetProperty = function (source, target, sourceProp, targetProp, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var isSourcePropertyIsAssignableToTargetProperty = this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return isSourcePropertyIsAssignableToTargetProperty; }; - PullTypeResolver.prototype.sourceCallSignaturesAreSubtypeOfTargetCallSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceCallSignaturesAreAssignableToTargetCallSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var areSourceCallSignaturesAssignableToTargetCallSignatures = this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSourceCallSignaturesAssignableToTargetCallSignatures; }; - PullTypeResolver.prototype.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceConstructSignaturesAreAssignableToTargetConstructSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var areSourceConstructSignaturesAssignableToTargetConstructSignatures = this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSourceConstructSignaturesAssignableToTargetConstructSignatures; }; - PullTypeResolver.prototype.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceIndexSignaturesAreAssignableToTargetIndexSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var areSourceIndexSignaturesAssignableToTargetIndexSignatures = this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSourceIndexSignaturesAssignableToTargetIndexSignatures; }; - PullTypeResolver.prototype.typeIsSubtypeOfFunction = function (source, ast, context) { - if (source.getCallSignatures().length || source.getConstructSignatures().length) { + PullTypeResolver.prototype.typeIsAssignableToFunction = function (source, ast, context) { + if (source.isFunctionType()) { return true; } - return this.cachedFunctionInterfaceType() && this.sourceIsSubtypeOfTarget(source, this.cachedFunctionInterfaceType(), ast, context); + return this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(source, this.cachedFunctionInterfaceType(), ast, context); }; - PullTypeResolver.prototype.signatureIsSubtypeOfTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(s1, s2); + var isSignatureIsAssignableToTarget = this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return isSignatureIsAssignableToTarget; }; PullTypeResolver.prototype.sourceIsAssignableToTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); }; - PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceIsAssignableToTargetWithNewEnclosingTypes = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTargetWithNewEnclosingTypes(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); }; PullTypeResolver.prototype.getSymbolForRelationshipCheck = function (symbol) { @@ -46640,7 +48001,7 @@ var TypeScript; return symbol; }; - PullTypeResolver.prototype.sourceIsRelatableToTargetInEnclosingTypes = function (source, target, sourceEnclosingType, targetEnclosingType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + PullTypeResolver.prototype.sourceIsRelatableToTargetInEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { source = this.getSymbolForRelationshipCheck(source); target = this.getSymbolForRelationshipCheck(target); @@ -46649,9 +48010,7 @@ var TypeScript; } if (source && target) { - var sourceGenerativeTypeKind = sourceEnclosingType ? source.getGenerativeTypeClassification(sourceEnclosingType) : 0 /* Unknown */; - var targetGenerativeTypeKind = targetEnclosingType ? target.getGenerativeTypeClassification(targetEnclosingType) : 0 /* Unknown */; - if (sourceGenerativeTypeKind == 3 /* InfinitelyExpanding */ || targetGenerativeTypeKind == 3 /* InfinitelyExpanding */) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { return this.infinitelyExpandingSourceTypeIsRelatableToTargetType(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); } } @@ -46659,6 +48018,27 @@ var TypeScript; return this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); }; + PullTypeResolver.prototype.sourceIsRelatableToTargetWithNewEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + var isSourceRelatable = this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return isSourceRelatable; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInCache = function (source, target, comparisonCache, comparisonInfo) { + var isRelatable = comparisonCache.valueAt(source.pullSymbolID, target.pullSymbolID); + + if (isRelatable) { + return { isRelatable: isRelatable }; + } + + if (isRelatable != undefined && !comparisonInfo) { + return { isRelatable: isRelatable }; + } + + return null; + }; + PullTypeResolver.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { source = this.getSymbolForRelationshipCheck(source); target = this.getSymbolForRelationshipCheck(target); @@ -46671,25 +48051,11 @@ var TypeScript; return true; } - var sourceSubstitution = source; + var sourceApparentType = this.getApparentType(source); - if (source == this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { - this.resolveDeclaredSymbol(this.cachedStringInterfaceType(), context); - sourceSubstitution = this.cachedStringInterfaceType(); - } else if (source == this.semanticInfoChain.numberTypeSymbol && this.cachedNumberInterfaceType()) { - this.resolveDeclaredSymbol(this.cachedNumberInterfaceType(), context); - sourceSubstitution = this.cachedNumberInterfaceType(); - } else if (source == this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { - this.resolveDeclaredSymbol(this.cachedBooleanInterfaceType(), context); - sourceSubstitution = this.cachedBooleanInterfaceType(); - } else if (TypeScript.PullHelpers.symbolIsEnum(source) && this.cachedNumberInterfaceType()) { - sourceSubstitution = this.cachedNumberInterfaceType(); - } else if (source.isTypeParameter()) { - sourceSubstitution = this.substituteUpperBoundForType(source); - } - - if (comparisonCache.valueAt(source.pullSymbolID, target.pullSymbolID) != undefined) { - return true; + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(source, target, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; } if (source === this.semanticInfoChain.stringTypeSymbol && target.isPrimitive() && target.isStringConstant()) { @@ -46704,10 +48070,10 @@ var TypeScript; if (this.isAnyOrEquivalent(target)) { return true; } + } - if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && source.isStringConstant()) { - return true; - } + if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && source.isStringConstant()) { + return true; } if (source.isPrimitive() && source.isStringConstant() && target.isPrimitive() && target.isStringConstant()) { @@ -46718,18 +48084,18 @@ var TypeScript; return true; } - if ((source === this.semanticInfoChain.nullTypeSymbol) && (target != this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { + if ((source === this.semanticInfoChain.nullTypeSymbol) && (target !== this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { return true; } - if (target == this.semanticInfoChain.voidTypeSymbol) { - if (source == this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { + if (target === this.semanticInfoChain.voidTypeSymbol) { + if (source === this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { return true; } return false; - } else if (source == this.semanticInfoChain.voidTypeSymbol) { - if (target == this.semanticInfoChain.anyTypeSymbol) { + } else if (source === this.semanticInfoChain.voidTypeSymbol) { + if (target === this.semanticInfoChain.anyTypeSymbol) { return true; } @@ -46753,21 +48119,20 @@ var TypeScript; } if (source.getIsSpecialized() && target.getIsSpecialized()) { - if (TypeScript.PullHelpers.getRootType(source) == TypeScript.PullHelpers.getRootType(target)) { + if (TypeScript.PullHelpers.getRootType(source) === TypeScript.PullHelpers.getRootType(target) && TypeScript.PullHelpers.getRootType(source).isNamedTypeSymbol()) { var sourceTypeArguments = source.getTypeArguments(); var targetTypeArguments = target.getTypeArguments(); if (sourceTypeArguments && targetTypeArguments) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, false); + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); for (var i = 0; i < sourceTypeArguments.length; i++) { - if (!this.sourceIsRelatableToTarget(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + if (!this.sourceIsRelatableToTargetWithNewEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, null, isComparingInstantiatedSignatures)) { break; } } - if (i == sourceTypeArguments.length) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + if (i === sourceTypeArguments.length) { return true; } else { comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); @@ -46776,57 +48141,75 @@ var TypeScript; } } - if (sourceSubstitution.isPrimitive() || target.isPrimitive()) { - return false; - } - if (target.isTypeParameter()) { - if (source.isTypeParameter() && (source === sourceSubstitution)) { - return this.typesAreIdentical(target, source); + if (source.isTypeParameter()) { + if (!source.getConstraint()) { + return this.typesAreIdentical(target, source, context); + } else { + return this.isSourceTypeParameterConstrainedToTargetTypeParameter(source, target); + } } else { if (isComparingInstantiatedSignatures) { - target = this.substituteUpperBoundForType(target); + target = target.getBaseConstraint(this.semanticInfoChain); } else { - return this.typesAreIdentical(target, sourceSubstitution); + return this.typesAreIdentical(target, sourceApparentType, context); } } } - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, false); - - if ((source.kind & 8216 /* SomeInstantiatableType */) && (target.kind & 8216 /* SomeInstantiatableType */) && this.sourceExtendsTarget(source, target, context)) { - return true; - } - - if (this.cachedObjectInterfaceType() && target === this.cachedObjectInterfaceType()) { - return true; - } - - if (this.cachedFunctionInterfaceType() && (sourceSubstitution.getCallSignatures().length || sourceSubstitution.getConstructSignatures().length) && target.hasBase(this.cachedFunctionInterfaceType())) { - return true; - } - - if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); - return false; - } - - if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); - return false; - } - - if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); - return false; - } - - if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); + if (sourceApparentType.isPrimitive() || target.isPrimitive()) { return false; } comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(sourceApparentType, target); + + var needsSourceSubstitutionUpdate = source != sourceApparentType && context.enclosingTypeWalker1._canWalkStructure() && context.enclosingTypeWalker1._getCurrentSymbol() != sourceApparentType; + if (needsSourceSubstitutionUpdate) { + context.enclosingTypeWalker1.setCurrentSymbol(sourceApparentType); + } + + var isRelatable = this.sourceIsRelatableToTargetWorker(source, target, sourceApparentType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + + if (needsSourceSubstitutionUpdate) { + context.enclosingTypeWalker1.setCurrentSymbol(source); + } + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.isSourceTypeParameterConstrainedToTargetTypeParameter = function (source, target) { + var current = source; + while (current && current.isTypeParameter()) { + if (current === target) { + return true; + } + + current = current.getConstraint(); + } + return false; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWorker = function (source, target, sourceSubstitution, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + return true; }; @@ -46835,38 +48218,23 @@ var TypeScript; for (var itargetProp = 0; itargetProp < targetProps.length; itargetProp++) { var targetProp = targetProps[itargetProp]; - var sourceProp = this.getMemberSymbol(targetProp.name, 68147712 /* SomeValue */, source); + + var sourceProp = this._getNamedPropertySymbolOfAugmentedType(targetProp.name, source); this.resolveDeclaredSymbol(targetProp, context); var targetPropType = targetProp.type; - if (sourceProp && sourceProp.anyDeclHasFlag(16 /* Static */) && source.isClass()) { - sourceProp = null; - } - if (!sourceProp) { - if (this.cachedObjectInterfaceType()) { - sourceProp = this.getMemberSymbol(targetProp.name, 68147712 /* SomeValue */, this.cachedObjectInterfaceType()); - } - - if (!sourceProp) { - if (this.cachedFunctionInterfaceType() && (targetPropType.getCallSignatures().length || targetPropType.getConstructSignatures().length)) { - sourceProp = this.getMemberSymbol(targetProp.name, 68147712 /* SomeValue */, this.cachedFunctionInterfaceType()); - } - - if (!sourceProp) { - if (!(targetProp.isOptional)) { - if (comparisonInfo) { - var enclosingSymbol = this.getEnclosingSymbolForAST(ast); - comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_is_missing_property_1_from_type_2, [source.toString(enclosingSymbol), targetProp.getScopedNameEx().toString(), target.toString(enclosingSymbol)])); - } - return false; - } - continue; + if (!(targetProp.isOptional)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_is_missing_property_1_from_type_2, [source.toString(enclosingSymbol), targetProp.getScopedNameEx().toString(), target.toString(enclosingSymbol)])); } + return false; } + continue; } if (!this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { @@ -46878,18 +48246,18 @@ var TypeScript; }; PullTypeResolver.prototype.infinitelyExpandingSourceTypeIsRelatableToTargetType = function (sourceType, targetType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - var widenedTargetType = this.widenType(targetType); - var widenedSourceType = this.widenType(sourceType); + var widenedTargetType = targetType.widenedType(this, null, context); + var widenedSourceType = sourceType.widenedType(this, null, context); - if ((widenedSourceType != this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType != this.semanticInfoChain.anyTypeSymbol)) { + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); - if (sourceTypeNamedTypeReference != targetTypeNamedTypeReference) { + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); if (comparisonInfo) { var enclosingSymbol = this.getEnclosingSymbolForAST(ast); - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_inifinitely_expanding_type_reference_do_not_refer_to_same_named_type, [sourceType.getScopedNameEx(enclosingSymbol).toString(), targetType.toString(enclosingSymbol)])); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type, [sourceType.getScopedNameEx(enclosingSymbol).toString(), targetType.toString(enclosingSymbol)])); } return false; } @@ -46902,11 +48270,11 @@ var TypeScript; return true; } - if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length != targetTypeArguments.length) { + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); if (comparisonInfo) { var enclosingSymbol = this.getEnclosingSymbolForAST(ast); - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)])); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)])); } return false; } @@ -46915,35 +48283,41 @@ var TypeScript; if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { comparisonInfoTypeArgumentsCheck = new TypeComparisonInfo(comparisonInfo); } - for (var i = 0; i < sourceTypeArguments.length; i++) { - if (!this.sourceIsRelatableToTarget(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + var isRelatable = true; + for (var i = 0; i < sourceTypeArguments.length && isRelatable; i++) { + context.walkTypeArgument(i); + + if (!this.sourceIsRelatableToTargetInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfoTypeArgumentsCheck, isComparingInstantiatedSignatures)) { + isRelatable = false; if (comparisonInfo) { var message; var enclosingSymbol = this.getEnclosingSymbolForAST(ast); if (comparisonInfoTypeArgumentsCheck && comparisonInfoTypeArgumentsCheck.message) { - message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol), comparisonInfoTypeArgumentsCheck.message]); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol), comparisonInfoTypeArgumentsCheck.message]); } else { - message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)]); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)]); } comparisonInfo.addMessage(message); } } + + context.postWalkTypeArgument(); } } - comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); - return true; + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, isRelatable); + return isRelatable; }; - PullTypeResolver.prototype.infinitelyExpandingTypesAreIdentical = function (sourceType, targetType) { - var widenedTargetType = this.widenType(targetType); - var widenedSourceType = this.widenType(sourceType); + PullTypeResolver.prototype.infinitelyExpandingTypesAreIdentical = function (sourceType, targetType, context) { + var widenedTargetType = targetType.widenedType(this, null, null); + var widenedSourceType = sourceType.widenedType(this, null, null); - if ((widenedSourceType != this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType != this.semanticInfoChain.anyTypeSymbol)) { + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); - if (sourceTypeNamedTypeReference != targetTypeNamedTypeReference) { + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); return false; } @@ -46956,13 +48330,17 @@ var TypeScript; return true; } - if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length != targetTypeArguments.length) { + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); return false; } for (var i = 0; i < sourceTypeArguments.length; i++) { - if (!this.typesAreIdentical(sourceTypeArguments[i], targetTypeArguments[i])) { + context.walkTypeArgument(i); + var areIdentical = this.typesAreIdenticalInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], context); + context.postWalkTypeArgument(); + + if (!areIdentical) { this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); return false; } @@ -46974,17 +48352,37 @@ var TypeScript; }; PullTypeResolver.prototype.sourcePropertyIsRelatableToTargetProperty = function (source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceAndTargetAreConstructors = source.isConstructor() && target.isConstructor(); + + var getNames = function (takeTypesFromPropertyContainers) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(ast); + var sourceType = takeTypesFromPropertyContainers ? sourceProp.getContainer() : source; + var targetType = takeTypesFromPropertyContainers ? targetProp.getContainer() : target; + if (sourceAndTargetAreConstructors) { + sourceType = sourceType.getAssociatedContainerType(); + targetType = targetType.getAssociatedContainerType(); + } + return { + propertyName: targetProp.getScopedNameEx().toString(), + sourceTypeName: sourceType.toString(enclosingSymbol), + targetTypeName: targetType.toString(enclosingSymbol) + }; + }; + var targetPropIsPrivate = targetProp.anyDeclHasFlag(2 /* Private */); var sourcePropIsPrivate = sourceProp.anyDeclHasFlag(2 /* Private */); - if (targetPropIsPrivate != sourcePropIsPrivate) { + if (targetPropIsPrivate !== sourcePropIsPrivate) { if (comparisonInfo) { - var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var names = getNames(true); + var code; if (targetPropIsPrivate) { - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(enclosingSymbol), targetProp.getContainer().toString(enclosingSymbol)])); + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2; } else { - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(enclosingSymbol), targetProp.getContainer().toString(enclosingSymbol)])); + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2; } + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName])); comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; } return false; @@ -46992,12 +48390,13 @@ var TypeScript; var targetDecl = targetProp.getDeclarations()[0]; var sourceDecl = sourceProp.getDeclarations()[0]; - if (!targetDecl.isEqual(sourceDecl)) { + if (targetDecl !== sourceDecl) { if (comparisonInfo) { - var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var names = getNames(true); comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_define_property_2_as_private, [sourceProp.getContainer().toString(enclosingSymbol), targetProp.getContainer().toString(enclosingSymbol), targetProp.getScopedNameEx().toString()])); + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_0_and_1_define_static_property_2_as_private : TypeScript.DiagnosticCode.Types_0_and_1_define_property_2_as_private; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.sourceTypeName, names.targetTypeName, names.propertyName])); } return false; @@ -47006,9 +48405,9 @@ var TypeScript; if (sourceProp.isOptional && !targetProp.isOptional) { if (comparisonInfo) { - var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var names = getNames(true); comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(enclosingSymbol), targetProp.getContainer().toString(enclosingSymbol)])); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2, [names.propertyName, names.sourceTypeName, names.targetTypeName])); } return false; } @@ -47018,8 +48417,9 @@ var TypeScript; var sourcePropType = sourceProp.type; var targetPropType = targetProp.type; - if (comparisonCache.valueAt(sourcePropType.pullSymbolID, targetPropType.pullSymbolID)) { - return true; + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourcePropType, targetPropType, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; } var comparisonInfoPropertyTypeCheck = null; @@ -47027,23 +48427,26 @@ var TypeScript; comparisonInfoPropertyTypeCheck = new TypeComparisonInfo(comparisonInfo); } - if (this.sourceIsRelatableToTargetInEnclosingTypes(sourcePropType, targetPropType, source, target, assignableTo, comparisonCache, ast, context, comparisonInfoPropertyTypeCheck, isComparingInstantiatedSignatures)) { - return true; - } + context.walkMemberTypes(targetProp.name); + var isSourcePropertyRelatableToTargetProperty = this.sourceIsRelatableToTargetInEnclosingTypes(sourcePropType, targetPropType, assignableTo, comparisonCache, ast, context, comparisonInfoPropertyTypeCheck, isComparingInstantiatedSignatures); + context.postWalkMemberTypes(); - if (comparisonInfo) { + if (!isSourcePropertyRelatableToTargetProperty && comparisonInfo) { var enclosingSymbol = this.getEnclosingSymbolForAST(ast); comparisonInfo.flags |= 32 /* IncompatiblePropertyTypes */; var message; + var names = getNames(false); if (comparisonInfoPropertyTypeCheck && comparisonInfoPropertyTypeCheck.message) { - message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3, [targetProp.getScopedNameEx().toString(), source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoPropertyTypeCheck.message]); + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3 : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName, comparisonInfoPropertyTypeCheck.message]); } else { - message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible, [targetProp.getScopedNameEx().toString(), source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName]); } comparisonInfo.addMessage(message); } - return false; + return isSourcePropertyRelatableToTargetProperty; }; PullTypeResolver.prototype.sourceCallSignaturesAreRelatableToTargetCallSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { @@ -47056,7 +48459,7 @@ var TypeScript; } var sourceCallSigs = source.getCallSignatures(); - if (!this.signatureGroupIsRelatableToTarget(sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { if (comparisonInfo) { var message; var enclosingSymbol = this.getEnclosingSymbolForAST(ast); @@ -47090,7 +48493,7 @@ var TypeScript; } var sourceConstructSigs = source.getConstructSignatures(); - if (!this.signatureGroupIsRelatableToTarget(sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { if (comparisonInfo) { var enclosingSymbol = this.getEnclosingSymbolForAST(ast); var message; @@ -47116,12 +48519,13 @@ var TypeScript; }; PullTypeResolver.prototype.sourceIndexSignaturesAreRelatableToTargetIndexSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - var targetIndexSigs = this.getBothKindsOfIndexSignatures(target, context); + var targetIndexSigs = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(target, context); var targetStringSig = targetIndexSigs.stringSignature; var targetNumberSig = targetIndexSigs.numericSignature; if (targetStringSig || targetNumberSig) { - var sourceIndexSigs = this.getBothKindsOfIndexSignatures(source, context); + var sourceIndexSigs = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(source, context); + var enclosingTypeIndexSigs = context.getBothKindOfIndexSignatures(true, false); var sourceStringSig = sourceIndexSigs.stringSignature; var sourceNumberSig = sourceIndexSigs.numericSignature; @@ -47133,7 +48537,9 @@ var TypeScript; if (targetStringSig) { if (sourceStringSig) { - comparable = this.signatureIsAssignableToTarget(sourceStringSig, targetStringSig, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, true); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetStringSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); } else { comparable = false; } @@ -47141,9 +48547,13 @@ var TypeScript; if (comparable && targetNumberSig) { if (sourceNumberSig) { - comparable = this.signatureIsAssignableToTarget(sourceNumberSig, targetNumberSig, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, false, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceNumberSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); } else if (sourceStringSig) { - comparable = this.sourceIsAssignableToTarget(sourceStringSig.returnType, targetNumberSig.returnType, ast, context, comparisonInfoSignatuesTypeCheck); + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); } else { comparable = false; } @@ -47168,7 +48578,7 @@ var TypeScript; return true; }; - PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (source, target, sourceSG, targetSG, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { if (sourceSG === targetSG) { return true; } @@ -47177,27 +48587,37 @@ var TypeScript; return false; } - var mSig = null; - var nSig = null; var foundMatch = false; var targetExcludeDefinition = targetSG.length > 1; var sourceExcludeDefinition = sourceSG.length > 1; + var sigsCompared = 0; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo, true); + comparisonInfoSignatuesTypeCheck.message = comparisonInfo.message; + } for (var iMSig = 0; iMSig < targetSG.length; iMSig++) { - mSig = targetSG[iMSig]; + var mSig = targetSG[iMSig]; if (mSig.isStringConstantOverloadSignature() || (targetExcludeDefinition && mSig.isDefinition())) { continue; } for (var iNSig = 0; iNSig < sourceSG.length; iNSig++) { - nSig = sourceSG[iNSig]; + var nSig = sourceSG[iNSig]; if (nSig.isStringConstantOverloadSignature() || (sourceExcludeDefinition && nSig.isDefinition())) { continue; } - if (this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + context.walkSignatures(nSig.kind, iNSig, iMSig); + var isSignatureRelatableToTarget = this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, ast, context, sigsCompared == 0 ? comparisonInfoSignatuesTypeCheck : null, isComparingInstantiatedSignatures); + context.postWalkSignatures(); + + sigsCompared++; + + if (isSignatureRelatableToTarget) { foundMatch = true; break; } @@ -47207,6 +48627,11 @@ var TypeScript; foundMatch = false; continue; } + + if (comparisonInfo && sigsCompared == 1) { + comparisonInfo.message = comparisonInfoSignatuesTypeCheck.message; + } + return false; } @@ -47214,6 +48639,19 @@ var TypeScript; }; PullTypeResolver.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourceSig, targetSig, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, true); + var isRelatable = this.signatureIsRelatableToTargetWorker(sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTargetWorker = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; var sourceParameters = sourceSig.parameters; var targetParameters = targetSig.parameters; @@ -47221,43 +48659,37 @@ var TypeScript; return false; } - var targetVarArgCount = targetSig.nonOptionalParamCount; - var sourceVarArgCount = sourceSig.nonOptionalParamCount; + var targetNonOptionalParamCount = targetSig.nonOptionalParamCount; + var sourceNonOptionalParamCount = sourceSig.nonOptionalParamCount; - if (sourceVarArgCount > targetVarArgCount) { + if (!targetSig.hasVarArgs && sourceNonOptionalParamCount > targetParameters.length) { if (comparisonInfo) { comparisonInfo.flags |= 3 /* SourceSignatureHasTooManyParameters */; - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signature_expects_0_or_fewer_parameters, [targetVarArgCount])); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signature_expects_0_or_fewer_parameters, [targetParameters.length])); } return false; } - if (sourceSig.isGeneric()) { - var rootSourceSig = sourceSig.getRootSymbol(); - var rootTargetSig = targetSig.getRootSymbol(); - - if (comparisonCache.valueAt(rootSourceSig.pullSymbolID, rootTargetSig.pullSymbolID) != undefined) { - return true; - } - - comparisonCache.setValueAt(rootSourceSig.pullSymbolID, rootTargetSig.pullSymbolID, false); - - sourceSig = this.instantiateSignatureInContext(sourceSig, targetSig, context); - - if (!sourceSig) { - return false; - } else { - sourceParameters = sourceSig.parameters; - } + if (this.signaturesAreIdentical(sourceSig, targetSig, context)) { + return true; } - comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, false); + if (targetSig.isGeneric()) { + targetSig = this.instantiateSignatureToAny(targetSig); + } + + if (sourceSig.isGeneric()) { + sourceSig = this.instantiateSignatureToAny(sourceSig); + } var sourceReturnType = sourceSig.returnType; var targetReturnType = targetSig.returnType; - if (targetReturnType != this.semanticInfoChain.voidTypeSymbol) { - if (!this.sourceIsRelatableToTargetInEnclosingTypes(sourceReturnType, targetReturnType, sourceSig.functionType, targetSig.functionType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + if (targetReturnType !== this.semanticInfoChain.voidTypeSymbol) { + context.walkReturnTypes(); + var returnTypesAreRelatable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceReturnType, targetReturnType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.postWalkReturnTypes(); + if (!returnTypesAreRelatable) { if (comparisonInfo) { comparisonInfo.flags |= 16 /* IncompatibleReturnTypes */; } @@ -47266,51 +48698,24 @@ var TypeScript; } } - var len = (sourceVarArgCount < targetVarArgCount && (sourceSig.hasVarArgs || (sourceParameters.length > sourceVarArgCount))) ? targetVarArgCount : sourceVarArgCount; - - if (!len) { - len = (sourceParameters.length < targetParameters.length) ? sourceParameters.length : targetParameters.length; - } - - var sourceParamType = null; - var targetParamType = null; - var sourceParamName = ""; - var targetParamName = ""; - - for (var iSource = 0, iTarget = 0; iSource < len; iSource++, iTarget++) { - if (iSource < sourceParameters.length && (!sourceSig.hasVarArgs || iSource < sourceVarArgCount)) { - sourceParamType = sourceParameters[iSource].type; - sourceParamName = sourceParameters[iSource].name; - } else if (iSource === sourceVarArgCount) { - sourceParamType = sourceParameters[iSource].type; - if (sourceParamType.isArrayNamedTypeReference()) { - sourceParamType = sourceParamType.getElementType(); - } - sourceParamName = sourceParameters[iSource].name; + return targetSig.forAllCorrespondingParameterTypesInThisAndOtherSignature(sourceSig, function (targetParamType, sourceParamType, iParam) { + context.walkParameterTypes(iParam); + var areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(sourceParamType, targetParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + if (!areParametersRelatable) { + context.swapEnclosingTypeWalkers(); + areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(targetParamType, sourceParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.swapEnclosingTypeWalkers(); } + context.postWalkParameterTypes(); - if (iTarget < targetParameters.length && !targetSig.hasVarArgs && (!targetVarArgCount || (iTarget < targetVarArgCount))) { - targetParamType = targetParameters[iTarget].type; - targetParamName = targetParameters[iTarget].name; - } else if (targetSig.hasVarArgs && iTarget === targetVarArgCount) { - targetParamType = targetParameters[iTarget].type; - - if (targetParamType.isArrayNamedTypeReference()) { - targetParamType = targetParamType.getElementType(); - } - targetParamName = targetParameters[iTarget].name; - } - - if (!(this.sourceIsRelatableToTargetInEnclosingTypes(sourceParamType, targetParamType, sourceSig.functionType, targetSig.functionType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) || this.sourceIsRelatableToTargetInEnclosingTypes(targetParamType, sourceParamType, targetSig.functionType, sourceSig.functionType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures))) { + if (!areParametersRelatable) { if (comparisonInfo) { comparisonInfo.flags |= 64 /* IncompatibleParameterTypes */; } - - return false; } - } - return true; + return areParametersRelatable; + }); }; PullTypeResolver.prototype.resolveOverloads = function (application, group, haveTypeArgumentsAtCallSite, context, diagnostics) { @@ -47324,7 +48729,8 @@ var TypeScript; return false; } - if (haveTypeArgumentsAtCallSite && !signature.isGeneric()) { + var rootSignature = signature.getRootSymbol(); + if (haveTypeArgumentsAtCallSite && !rootSignature.isGeneric()) { return false; } @@ -47423,13 +48829,13 @@ var TypeScript; return 1 /* AssignableButWithProvisionalErrors */; } else if (arg.kind() === 219 /* SimpleArrowFunctionExpression */) { var simpleArrowFunction = arg; - return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, null, TypeScript.Parameters.fromIdentifier(simpleArrowFunction.identifier), null, simpleArrowFunction.block, simpleArrowFunction.expression, argIndex, context, comparisonInfo); + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, null, TypeScript.ASTHelpers.parametersFromIdentifier(simpleArrowFunction.identifier), null, simpleArrowFunction.block, simpleArrowFunction.expression, argIndex, context, comparisonInfo); } else if (arg.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { var arrowFunction = arg; - return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, arrowFunction.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(arrowFunction.callSignature.parameterList), TypeScript.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, argIndex, context, comparisonInfo); + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, argIndex, context, comparisonInfo); } else if (arg.kind() === 222 /* FunctionExpression */) { var functionExpression = arg; - return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, functionExpression.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(functionExpression.callSignature.parameterList), TypeScript.getType(functionExpression), functionExpression.block, null, argIndex, context, comparisonInfo); + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, functionExpression.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(functionExpression.callSignature.parameterList), TypeScript.ASTHelpers.getType(functionExpression), functionExpression.block, null, argIndex, context, comparisonInfo); } else if (arg.kind() === 215 /* ObjectLiteralExpression */) { return this.overloadIsApplicableForObjectLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); } else if (arg.kind() === 214 /* ArrayLiteralExpression */) { @@ -47444,13 +48850,13 @@ var TypeScript; return 2 /* AssignableWithNoProvisionalErrors */; } - context.pushContextualType(paramType, true, null); + context.pushProvisionalType(paramType); var argSym = this.resolveAnyFunctionExpression(arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, true, context); var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); - context.popContextualType(); + context.popAnyContextualType(); return applicabilityStatus; }; @@ -47460,12 +48866,12 @@ var TypeScript; return 2 /* AssignableWithNoProvisionalErrors */; } - context.pushContextualType(paramType, true, null); + context.pushProvisionalType(paramType); var argSym = this.resolveObjectLiteralExpression(arg, true, context); var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); - context.popContextualType(); + context.popAnyContextualType(); return applicabilityStatus; }; @@ -47475,12 +48881,12 @@ var TypeScript; return 2 /* AssignableWithNoProvisionalErrors */; } - context.pushContextualType(paramType, true, null); + context.pushProvisionalType(paramType); var argSym = this.resolveArrayLiteralExpression(arg, true, context); var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); - context.popContextualType(); + context.popAnyContextualType(); return applicabilityStatus; }; @@ -47516,92 +48922,34 @@ var TypeScript; return 0 /* NotAssignable */; }; - PullTypeResolver.prototype.inferArgumentTypesForSignature = function (signature, argContext, comparisonInfo, context) { - var cxt = null; + PullTypeResolver.prototype.inferArgumentTypesForSignature = function (argContext, comparisonInfo, context) { + var inferenceResultTypes = argContext.inferTypeArguments(); + var typeParameters = argContext.signatureBeingInferred.getTypeParameters(); + TypeScript.Debug.assert(typeParameters.length == inferenceResultTypes.length); - var parameters = signature.parameters; - var typeParameters = signature.getTypeParameters(); - - var parameterType = null; - var argCount = argContext.getInferenceArgumentCount(); - - for (var i = 0; i < typeParameters.length; i++) { - argContext.addInferenceRoot(typeParameters[i]); - } - - for (var i = 0; i < argCount; i++) { - if (i >= parameters.length) { - break; - } - - parameterType = parameters[i].type; - - if (signature.hasVarArgs && (i >= signature.nonOptionalParamCount - 1) && parameterType.isArrayNamedTypeReference()) { - parameterType = parameterType.getElementType(); - } - - var inferenceCandidates = argContext.getInferenceCandidates(); - - if (inferenceCandidates.length) { - for (var j = 0; j < inferenceCandidates.length; j++) { - argContext.resetRelationshipCache(); - var substitutions = inferenceCandidates[j]; - - context.pushContextualType(parameterType, true, substitutions); - - this.relateTypeToTypeParameters(argContext.getArgumentTypeSymbolAtIndex(i, context), parameterType, false, argContext, context); - - cxt = context.popContextualType(); - } - } else { - context.pushContextualType(parameterType, true, []); - - this.relateTypeToTypeParameters(argContext.getArgumentTypeSymbolAtIndex(i, context), parameterType, false, argContext, context); - - cxt = context.popContextualType(); - } - } - - var inferenceResults = argContext.inferArgumentTypes(this, context); - - if (inferenceResults.unfit) { - return null; - } - - var resultTypes = []; - - for (var i = 0; i < typeParameters.length; i++) { - for (var j = 0; j < inferenceResults.results.length; j++) { - if ((inferenceResults.results[j].param == typeParameters[i]) && inferenceResults.results[j].type) { - resultTypes[resultTypes.length] = inferenceResults.results[j].type; - break; + var typeReplacementMapForConstraints = null; + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (typeParameters[i].getConstraint()) { + typeReplacementMapForConstraints = typeReplacementMapForConstraints || TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, inferenceResultTypes); + var associatedConstraint = this.instantiateType(typeParameters[i].getConstraint(), typeReplacementMapForConstraints); + if (!this.sourceIsAssignableToTargetWithNewEnclosingTypes(inferenceResultTypes[i], associatedConstraint, null, context, null, false)) { + inferenceResultTypes[i] = associatedConstraint; } } } - if (!argCount && !resultTypes.length && typeParameters.length) { - for (var i = 0; i < typeParameters.length; i++) { - resultTypes[resultTypes.length] = this.semanticInfoChain.emptyTypeSymbol; - } - } else if (resultTypes.length < typeParameters.length) { - for (var i = resultTypes.length; i < typeParameters.length; i++) { - resultTypes[i] = this.semanticInfoChain.emptyTypeSymbol; - } - } - - var inferringAtCallExpression = argContext.argumentASTs && argContext.argumentASTs.parent && argContext.argumentASTs.parent.kind() === 226 /* ArgumentList */ && (argContext.argumentASTs.parent.parent.kind() === 213 /* InvocationExpression */ || argContext.argumentASTs.parent.parent.kind() === 216 /* ObjectCreationExpression */); - - if (inferringAtCallExpression) { - if (!this.typeParametersAreInScopeAtArgumentList(typeParameters, argContext.argumentASTs)) { - for (var i = 0; i < resultTypes.length; i++) { - if (resultTypes[i].wrapsSomeTypeParameter(argContext.candidateCache)) { - resultTypes[i] = this.semanticInfoChain.emptyTypeSymbol; + if (argContext.isInvocationInferenceContext()) { + var invocationContext = argContext; + if (!this.typeParametersAreInScopeAtArgumentList(typeParameters, invocationContext.argumentASTs)) { + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (inferenceResultTypes[i].wrapsSomeTypeParameter(argContext.candidateCache)) { + inferenceResultTypes[i] = this.semanticInfoChain.anyTypeSymbol; } } } } - return resultTypes; + return inferenceResultTypes; }; PullTypeResolver.prototype.typeParametersAreInScopeAtArgumentList = function (typeParameters, args) { @@ -47610,19 +48958,23 @@ var TypeScript; return enclosingDecl.getParentPath().indexOf(typeParameterParentDecl) > -1; }; - PullTypeResolver.prototype.relateTypeToTypeParametersInEnclosingType = function (expressionType, parameterType, expressionTypeEnclosingType, parameterTypeEnclosingType, shouldFix, argContext, context) { + PullTypeResolver.prototype.relateTypeToTypeParametersInEnclosingType = function (expressionType, parameterType, argContext, context) { if (expressionType && parameterType) { - var expressionTypeGenerativeTypeClassification = expressionTypeEnclosingType ? expressionType.getGenerativeTypeClassification(expressionTypeEnclosingType) : 0 /* Unknown */; - var parameterTypeGenerativeTypeClassification = parameterTypeEnclosingType ? parameterType.getGenerativeTypeClassification(parameterTypeEnclosingType) : 0 /* Unknown */; - if (expressionTypeGenerativeTypeClassification == 3 /* InfinitelyExpanding */ || parameterTypeGenerativeTypeClassification == 3 /* InfinitelyExpanding */) { - this.relateInifinitelyExpandingTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + this.relateInifinitelyExpandingTypeToTypeParameters(expressionType, parameterType, argContext, context); return; } } - this.relateTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); }; - PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, shouldFix, argContext, context) { + PullTypeResolver.prototype.relateTypeToTypeParametersWithNewEnclosingTypes = function (expressionType, parameterType, argContext, context) { + var enclosingTypeWalkers = context.resetEnclosingTypeWalkers(); + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.setEnclosingTypeWalkers(enclosingTypeWalkers); + }; + + PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { if (!expressionType || !parameterType) { return; } @@ -47632,82 +48984,73 @@ var TypeScript; } if (parameterType.isTypeParameter()) { - argContext.addCandidateForInference(parameterType, expressionType, shouldFix); + var typeParameter = parameterType; + argContext.addCandidateForInference(typeParameter, expressionType); return; } - var parameterDeclarations = parameterType.getDeclarations(); - var expressionDeclarations = expressionType.getDeclarations(); - - if (!parameterType.isArrayNamedTypeReference() && parameterDeclarations.length && expressionDeclarations.length && !(parameterType.isTypeParameter() || expressionType.isTypeParameter()) && (parameterDeclarations[0].isEqual(expressionDeclarations[0]) || (expressionType.isGeneric() && parameterType.isGeneric() && this.sourceIsSubtypeOfTarget(this.instantiateTypeToAny(expressionType, context), this.instantiateTypeToAny(parameterType, context), null, context, null))) && expressionType.isGeneric()) { - this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); - } - - if (expressionType.isArrayNamedTypeReference() && parameterType.isArrayNamedTypeReference()) { - this.relateArrayTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); - + if (parameterType.isNamedTypeSymbol() && !parameterType.isGeneric() && !parameterType.getTypeArguments()) { return; } - this.relateObjectTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); - }; - - PullTypeResolver.prototype.relateTypeArgumentsOfTypeToTypeParameters = function (expressionType, parameterType, shouldFix, argContext, context) { - var typeParameters = parameterType.getTypeArgumentsOrTypeParameters(); - var typeArguments = expressionType.getTypeArguments(); - - if (!typeArguments) { - typeParameters = parameterType.getTypeArguments(); - typeArguments = expressionType.getTypeArgumentsOrTypeParameters(); - } - - if (typeParameters && typeArguments && typeParameters.length === typeArguments.length) { - for (var i = 0; i < typeParameters.length; i++) { - if (typeArguments[i] != typeParameters[i]) { - this.relateTypeToTypeParameters(typeArguments[i], typeParameters[i], true, argContext, context); - } - } + if (TypeScript.PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType(expressionType, parameterType)) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } else { + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(expressionType, parameterType); + this.relateObjectTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); } }; - PullTypeResolver.prototype.relateInifinitelyExpandingTypeToTypeParameters = function (expressionType, parameterType, shouldFix, argContext, context) { + PullTypeResolver.prototype.relateTypeArgumentsOfTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + var parameterSideTypeArguments = parameterType.getTypeArguments(); + var argumentSideTypeArguments = expressionType.getTypeArguments(); + + TypeScript.Debug.assert(parameterSideTypeArguments && argumentSideTypeArguments && parameterSideTypeArguments.length === argumentSideTypeArguments.length); + for (var i = 0; i < parameterSideTypeArguments.length; i++) { + this.relateTypeToTypeParametersWithNewEnclosingTypes(argumentSideTypeArguments[i], parameterSideTypeArguments[i], argContext, context); + } + }; + + PullTypeResolver.prototype.relateInifinitelyExpandingTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { if (!expressionType || !parameterType) { return; } var expressionTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(expressionType); var parameterTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(parameterType); - if (expressionTypeNamedTypeReference != parameterTypeNamedTypeReference) { + if (expressionTypeNamedTypeReference !== parameterTypeNamedTypeReference) { return; } var expressionTypeTypeArguments = expressionType.getTypeArguments(); - var parameterTypeParameters = parameterType.getTypeParameters(); + var parameterTypeArguments = parameterType.getTypeArguments(); - if (expressionTypeTypeArguments && parameterTypeParameters && expressionTypeTypeArguments.length === parameterTypeParameters.length) { + if (expressionTypeTypeArguments && parameterTypeArguments && expressionTypeTypeArguments.length === parameterTypeArguments.length) { for (var i = 0; i < expressionTypeTypeArguments.length; i++) { - this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); } } }; PullTypeResolver.prototype.relateFunctionSignatureToTypeParameters = function (expressionSignature, parameterSignature, argContext, context) { - var expressionParams = expressionSignature.parameters; + var _this = this; var expressionReturnType = expressionSignature.returnType; - - var parameterParams = parameterSignature.parameters; var parameterReturnType = parameterSignature.returnType; - var len = parameterParams.length < expressionParams.length ? parameterParams.length : expressionParams.length; + parameterSignature.forAllCorrespondingParameterTypesInThisAndOtherSignature(expressionSignature, function (parameterSignatureParameterType, expressionSignatureParameterType, i) { + context.walkParameterTypes(i); + _this.relateTypeToTypeParametersInEnclosingType(expressionSignatureParameterType, parameterSignatureParameterType, argContext, context); + context.postWalkParameterTypes(); + return true; + }); - for (var i = 0; i < len; i++) { - this.relateTypeToTypeParametersInEnclosingType(expressionParams[i].type, parameterParams[i].type, expressionSignature.functionType, parameterSignature.functionType, true, argContext, context); - } - - this.relateTypeToTypeParametersInEnclosingType(expressionReturnType, parameterReturnType, expressionSignature.functionType, parameterSignature.functionType, false, argContext, context); + context.walkReturnTypes(); + this.relateTypeToTypeParametersInEnclosingType(expressionReturnType, parameterReturnType, argContext, context); + context.postWalkReturnTypes(); }; - PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, shouldFix, argContext, context) { + PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, argContext, context) { var parameterTypeMembers = parameterType.getMembers(); var parameterSignatures; @@ -47718,58 +49061,98 @@ var TypeScript; return; } - var objectTypeArguments = objectType.getTypeArguments(); - var parameterTypeParameters = parameterType.getTypeParameters(); - - if (objectTypeArguments) { - if (objectTypeArguments.length === parameterTypeParameters.length) { - for (var i = 0; i < objectTypeArguments.length; i++) { - argContext.addCandidateForInference(parameterTypeParameters[i], objectTypeArguments[i], shouldFix); - } - } else if (parameterType == this.semanticInfoChain.anyTypeSymbol) { - for (var i = 0; i < objectTypeArguments.length; i++) { - this.relateTypeToTypeParameters(parameterType, objectTypeArguments[i], shouldFix, argContext, context); - } - } - } - for (var i = 0; i < parameterTypeMembers.length; i++) { - objectMember = this.getMemberSymbol(parameterTypeMembers[i].name, 68147712 /* SomeValue */, objectType); + objectMember = this.getNamedPropertySymbol(parameterTypeMembers[i].name, 68147712 /* SomeValue */, objectType); if (objectMember) { - this.relateTypeToTypeParametersInEnclosingType(objectMember.type, parameterTypeMembers[i].type, objectType, parameterType, shouldFix, argContext, context); + this.resolveDeclaredSymbol(objectMember); + this.resolveDeclaredSymbol(parameterTypeMembers[i]); + context.walkMemberTypes(parameterTypeMembers[i].name); + this.relateTypeToTypeParametersInEnclosingType(objectMember.type, parameterTypeMembers[i].type, argContext, context); + context.postWalkMemberTypes(); } } - parameterSignatures = parameterType.getCallSignatures(); - objectSignatures = objectType.getCallSignatures(); + this.relateSignatureGroupToTypeParameters(objectType.getCallSignatures(), parameterType.getCallSignatures(), 1048576 /* CallSignature */, argContext, context); - if ((parameterSignatures.length == 1) && (objectSignatures.length == 1) && !objectSignatures[0].isGeneric() && (parameterSignatures[0].nonOptionalParamCount >= objectSignatures[0].nonOptionalParamCount)) { - this.relateFunctionSignatureToTypeParameters(objectSignatures[0], parameterSignatures[0], argContext, context); - } + this.relateSignatureGroupToTypeParameters(objectType.getConstructSignatures(), parameterType.getConstructSignatures(), 2097152 /* ConstructSignature */, argContext, context); - parameterSignatures = parameterType.getConstructSignatures(); - objectSignatures = objectType.getConstructSignatures(); - - if ((parameterSignatures.length == 1) && (objectSignatures.length == 1) && !objectSignatures[0].isGeneric() && (parameterSignatures[0].nonOptionalParamCount >= objectSignatures[0].nonOptionalParamCount)) { - this.relateFunctionSignatureToTypeParameters(objectSignatures[0], parameterSignatures[0], argContext, context); - } - - var parameterIndexSignatures = this.getBothKindsOfIndexSignatures(parameterType, context); - var objectIndexSignatures = this.getBothKindsOfIndexSignatures(objectType, context); + var parameterIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parameterType, context); + var objectIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(objectType, context); + var indexSigInfo = context.getBothKindOfIndexSignatures(false, false); if (parameterIndexSignatures.stringSignature && objectIndexSignatures.stringSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, true, true, true); this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.stringSignature, parameterIndexSignatures.stringSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); } if (parameterIndexSignatures.numericSignature && objectIndexSignatures.numericSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, false, false, true); this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.numericSignature, parameterIndexSignatures.numericSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); } }; - PullTypeResolver.prototype.relateArrayTypeToTypeParameters = function (argArrayType, parameterArrayType, shouldFix, argContext, context) { - var argElement = argArrayType.getElementType(); - var paramElement = parameterArrayType.getElementType(); + PullTypeResolver.prototype.relateSignatureGroupToTypeParameters = function (argumentSignatures, parameterSignatures, signatureKind, argContext, context) { + for (var i = 0; i < parameterSignatures.length; i++) { + var paramSignature = parameterSignatures[i]; + if (argumentSignatures.length > 0 && paramSignature.isGeneric()) { + paramSignature = this.instantiateSignatureToAny(paramSignature); + } + for (var j = 0; j < argumentSignatures.length; j++) { + var argumentSignature = argumentSignatures[j]; + if (argumentSignature.nonOptionalParamCount > paramSignature.nonOptionalParamCount) { + continue; + } - this.relateTypeToTypeParameters(argElement, paramElement, shouldFix, argContext, context); + if (argumentSignature.isGeneric()) { + argumentSignature = this.instantiateSignatureToAny(argumentSignature); + } + + context.walkSignatures(signatureKind, j, i); + this.relateFunctionSignatureToTypeParameters(argumentSignature, paramSignature, argContext, context); + context.postWalkSignatures(); + } + } + }; + + PullTypeResolver.prototype.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference = function (expressionSymbol, context) { + var inferentialType = context.getContextualType(); + TypeScript.Debug.assert(inferentialType); + var expressionType = expressionSymbol.type; + if (this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(expressionType, true) && this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(inferentialType, false)) { + var genericExpressionSignature = expressionType.getCallSignatures()[0]; + var contextualSignature = inferentialType.getCallSignatures()[0]; + + var instantiatedSignature = this.instantiateSignatureInContext(genericExpressionSignature, contextualSignature, context, true); + if (instantiatedSignature === null) { + return expressionSymbol; + } + + var newType = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + newType.appendCallSignature(instantiatedSignature); + return newType; + } + + return expressionSymbol; + }; + + PullTypeResolver.prototype.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers = function (type, callSignatureShouldBeGeneric) { + TypeScript.Debug.assert(type); + if (type.getCallSignatures().length !== 1) { + return false; + } + + var callSignatureIsGeneric = type.getCallSignatures()[0].isGeneric(); + if (callSignatureIsGeneric !== callSignatureShouldBeGeneric) { + return false; + } + + var typeHasOtherMembers = type.getConstructSignatures().length || type.getIndexSignatures().length || type.getAllMembers(68147712 /* SomeValue */, 0 /* all */).length; + if (typeHasOtherMembers) { + return false; + } + + return true; }; PullTypeResolver.prototype.instantiateTypeToAny = function (typeToSpecialize, context) { @@ -47806,6 +49189,32 @@ var TypeScript; return type; }; + PullTypeResolver.prototype.instantiateSignatureToAny = function (signature) { + var typeParameters = signature.getTypeParameters(); + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + var typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var typeParameterArgumentMap = TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, typeArguments); + return this.instantiateSignature(signature, typeParameterArgumentMap); + }; + PullTypeResolver.typeCheck = function (compilationSettings, semanticInfoChain, document) { var sourceUnit = document.sourceUnit(); @@ -47826,66 +49235,23 @@ var TypeScript; }; PullTypeResolver.prototype.validateVariableDeclarationGroups = function (enclosingDecl, context) { - var importDeclarationNames = null; - if (enclosingDecl.kind & (4 /* Container */ | 32 /* DynamicModule */ | 1 /* Script */)) { - var childDecls = enclosingDecl.getChildDecls(); - for (var i = 0, n = childDecls.length; i < n; i++) { - var childDecl = childDecls[i]; - if (childDecl.kind === 128 /* TypeAlias */) { - importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); - importDeclarationNames[childDecl.name] = true; - } - } - } - - var declGroups = enclosingDecl.getVariableDeclGroups(); - - for (var i = 0, i_max = declGroups.length; i < i_max; i++) { - var firstSymbol = null; - var firstSymbolType = null; - - if (enclosingDecl.kind === 1 /* Script */ && declGroups[i].length) { - var name = declGroups[i][0].name; - var candidateSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 512 /* Variable */, enclosingDecl); - if (candidateSymbol && candidateSymbol.isResolved) { - if (!candidateSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */)) { - firstSymbol = candidateSymbol; - firstSymbolType = candidateSymbol.type; - } - } - - var importSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 128 /* TypeAlias */, null); - if (importSymbol && importSymbol.isAlias()) { - importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); - } + var _this = this; + this.scanVariableDeclarationGroups(enclosingDecl, function (_) { + }, function (subsequentDecl, firstSymbol) { + if (TypeScript.hasFlag(subsequentDecl.kind, 2048 /* Parameter */) || TypeScript.hasFlag(subsequentDecl.flags, 8388608 /* PropertyParameter */)) { + return; } - for (var j = 0, j_max = declGroups[i].length; j < j_max; j++) { - var decl = declGroups[i][j]; - var boundDeclAST = this.semanticInfoChain.getASTForDecl(decl); + var boundDeclAST = _this.semanticInfoChain.getASTForDecl(subsequentDecl); - var name = decl.name; + var symbol = subsequentDecl.getSymbol(); + var symbolType = symbol.type; + var firstSymbolType = firstSymbol.type; - if (importDeclarationNames && importDeclarationNames[name]) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Variable_declaration_cannot_have_the_same_name_as_an_import_declaration)); - continue; - } - - var symbol = decl.getSymbol(); - var symbolType = symbol.type; - - if (j === 0 && !firstSymbol) { - firstSymbol = symbol; - firstSymbolType = symbolType; - continue; - } - - if (symbolType && firstSymbolType && symbolType !== firstSymbolType && !this.typesAreIdentical(symbolType, firstSymbolType)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, [symbol.getScopedName(), firstSymbolType.toString(), symbolType.toString()])); - continue; - } + if (symbolType && firstSymbolType && symbolType !== firstSymbolType && !_this.typesAreIdentical(symbolType, firstSymbolType, context)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, [symbol.getScopedName(), firstSymbolType.toString(firstSymbol), symbolType.toString(symbol)])); } - } + }); }; PullTypeResolver.prototype.typeCheckFunctionOverloads = function (funcDecl, context, signature, allSignatures) { @@ -47906,13 +49272,19 @@ var TypeScript; } if (!signature.isDefinition()) { + var signatureParentDecl = signature.getDeclarations()[0].getParentDecl(); for (var i = 0; i < allSignatures.length; i++) { if (allSignatures[i] === signature) { break; } - if (this.signaturesAreIdentical(allSignatures[i], signature, false)) { - if (!this.typesAreIdentical(allSignatures[i].returnType, signature.returnType)) { + var allSignaturesParentDecl = allSignatures[i].getDeclarations()[0].getParentDecl(); + if (allSignaturesParentDecl !== signatureParentDecl) { + continue; + } + + if (this.signaturesAreIdenticalWithNewEnclosingTypes(allSignatures[i], signature, context, false)) { + if (!this.signatureReturnTypesAreIdentical(allSignatures[i], signature, context)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overloads_cannot_differ_only_by_return_type)); } else if (funcDecl.kind() === 137 /* ConstructorDeclaration */) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_constructor_overload_signature)); @@ -47948,17 +49320,17 @@ var TypeScript; continue; } - if (this.signatureIsSubtypeOfTarget(signature, allSignatures[i], null, context)) { + if (this.signatureIsAssignableToTarget(signature, allSignatures[i], null, context)) { foundSubtypeSignature = true; break; } } if (!foundSubtypeSignature) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature)); } } - } else if (definitionSignature && definitionSignature != signature) { + } else if (definitionSignature && definitionSignature !== signature) { var comparisonInfo = new TypeComparisonInfo(); if (!definitionSignature.isResolved) { @@ -47982,16 +49354,16 @@ var TypeScript; signatureForVisibilityCheck = allSignatures[0]; } - if (funcDecl.kind() !== 137 /* ConstructorDeclaration */ && functionDeclaration.kind !== 2097152 /* ConstructSignature */ && signatureForVisibilityCheck && signature != signatureForVisibilityCheck) { + if (funcDecl.kind() !== 137 /* ConstructorDeclaration */ && functionDeclaration.kind !== 2097152 /* ConstructSignature */ && signatureForVisibilityCheck && signature !== signatureForVisibilityCheck) { var errorCode; - if (signatureForVisibilityCheck.anyDeclHasFlag(2 /* Private */) != signature.anyDeclHasFlag(2 /* Private */)) { + if (signatureForVisibilityCheck.anyDeclHasFlag(2 /* Private */) !== signature.anyDeclHasFlag(2 /* Private */)) { errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_public_or_private; - } else if (signatureForVisibilityCheck.anyDeclHasFlag(1 /* Exported */) != signature.anyDeclHasFlag(1 /* Exported */)) { + } else if (signatureForVisibilityCheck.anyDeclHasFlag(1 /* Exported */) !== signature.anyDeclHasFlag(1 /* Exported */)) { errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_exported_or_not_exported; - } else if (signatureForVisibilityCheck.anyDeclHasFlag(8 /* Ambient */) != signature.anyDeclHasFlag(8 /* Ambient */)) { + } else if (signatureForVisibilityCheck.anyDeclHasFlag(8 /* Ambient */) !== signature.anyDeclHasFlag(8 /* Ambient */)) { errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_ambient_or_non_ambient; - } else if (signatureForVisibilityCheck.anyDeclHasFlag(128 /* Optional */) != signature.anyDeclHasFlag(128 /* Optional */)) { + } else if (signatureForVisibilityCheck.anyDeclHasFlag(128 /* Optional */) !== signature.anyDeclHasFlag(128 /* Optional */)) { errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_optional_or_required; } @@ -48045,7 +49417,7 @@ var TypeScript; this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getCallSignatures(), privacyErrorReporter); this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getConstructSignatures(), privacyErrorReporter); this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getIndexSignatures(), privacyErrorReporter); - } else if (typeSymbol.kind == 8192 /* TypeParameter */) { + } else if (typeSymbol.kind === 8192 /* TypeParameter */) { this.checkSymbolPrivacy(declSymbol, typeSymbol.getConstraint(), privacyErrorReporter); } @@ -48059,27 +49431,27 @@ var TypeScript; if (declSymbol.isExternallyVisible()) { var symbolIsVisible = symbol.isExternallyVisible(); - if (symbolIsVisible && symbol.kind != 8192 /* TypeParameter */) { + if (symbolIsVisible && symbol.kind !== 8192 /* TypeParameter */) { var symbolPath = symbol.pathToRoot(); var declSymbolPath = declSymbol.pathToRoot(); - if (symbolPath[symbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1].kind == 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1] != symbolPath[symbolPath.length - 1]) { + if (symbolPath[symbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1] !== symbolPath[symbolPath.length - 1]) { symbolIsVisible = false; var declSymbolScope = declSymbolPath[declSymbolPath.length - 1]; for (var i = symbolPath.length - 1; i >= 0; i--) { var aliasSymbols = symbolPath[i].getExternalAliasedSymbols(declSymbolScope); if (aliasSymbols) { symbolIsVisible = true; - aliasSymbols[0].setTypeUsedExternally(true); + aliasSymbols[0].setTypeUsedExternally(); break; } } symbol = symbolPath[symbolPath.length - 1]; } - } else if (symbol.kind == 128 /* TypeAlias */) { + } else if (symbol.kind === 128 /* TypeAlias */) { var aliasSymbol = symbol; symbolIsVisible = true; - aliasSymbol.setTypeUsedExternally(true); + aliasSymbol.setTypeUsedExternally(); } if (!symbolIsVisible) { @@ -48111,7 +49483,7 @@ var TypeScript; } }; - PullTypeResolver.prototype.typeParameterOfTypeDeclarationPrivacyErrorReporter = function (classOrInterface, indexOfTypeParameter, typeParameter, symbol, context) { + PullTypeResolver.prototype.typeParameterOfTypeDeclarationPrivacyErrorReporter = function (classOrInterface, typeParameterAST, typeParameter, symbol, context) { var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); var enclosingDecl = this.getEnclosingDecl(decl); var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; @@ -48119,8 +49491,6 @@ var TypeScript; var typeParameters = classOrInterface.kind() === 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; - var typeParameterAST = typeParameters.typeParameters.nonSeparatorAt(indexOfTypeParameter); - var typeSymbol = symbol; var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { @@ -48254,7 +49624,7 @@ var TypeScript; if (functionSymbol && functionSymbol.isType() && !functionSymbol.isNamedTypeSymbol()) { return; } - } else if (functionSymbol.kind == 65536 /* Method */ && !isStatic && !functionSymbol.getContainer().isNamedTypeSymbol()) { + } else if (functionSymbol.kind === 65536 /* Method */ && !isStatic && !functionSymbol.getContainer().isNamedTypeSymbol()) { return; } functionSignature = functionDecl.getSignatureSymbol(); @@ -48659,7 +50029,7 @@ var TypeScript; }; PullTypeResolver.prototype.typeCheckMembersAgainstIndexer = function (containerType, containerTypeDecl, context) { - var indexSignatures = this.getBothKindsOfIndexSignatures(containerType, context); + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(containerType, context); var stringSignature = indexSignatures.stringSignature; var numberSignature = indexSignatures.numericSignature; @@ -48672,7 +50042,7 @@ var TypeScript; var relevantSignature = this.determineRelevantIndexerForMember(memberSymbol, numberSignature, stringSignature); if (relevantSignature) { var comparisonInfo = new TypeComparisonInfo(); - if (!this.sourceIsSubtypeOfTarget(memberSymbol.type, relevantSignature.returnType, member.ast(), context, comparisonInfo)) { + if (!this.sourceIsAssignableToTarget(memberSymbol.type, relevantSignature.returnType, member.ast(), context, comparisonInfo)) { this.reportErrorThatMemberIsNotSubtypeOfIndexer(memberSymbol, relevantSignature, member.ast(), context, comparisonInfo); } } @@ -48695,15 +50065,15 @@ var TypeScript; var enclosingSymbol = this.getEnclosingSymbolForAST(astForError); if (indexSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { if (comparisonInfo.message) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); } else { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); } } else { if (comparisonInfo.message) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_subtypes_of_string_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); } else { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_subtypes_of_string_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); } } }; @@ -48756,7 +50126,7 @@ var TypeScript; foundError1 = !this.typeCheckIfTypeMemberPropertyOkToOverride(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, enclosingDecl, comparisonInfo); if (!foundError1) { - foundError2 = !this.sourcePropertyIsSubtypeOfTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, classOrInterface, context, comparisonInfo); + foundError2 = !this.sourcePropertyIsAssignableToTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, classOrInterface, context, comparisonInfo); } if (foundError1 || foundError2) { @@ -48767,15 +50137,15 @@ var TypeScript; } if (!foundError && typeSymbol.hasOwnCallSignatures()) { - foundError = !this.sourceCallSignaturesAreSubtypeOfTargetCallSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); } if (!foundError && typeSymbol.hasOwnConstructSignatures()) { - foundError = !this.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); } if (!foundError && typeSymbol.hasOwnIndexSignatures()) { - foundError = !this.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); } if (!foundError && typeSymbol.isClass()) { @@ -48793,17 +50163,7 @@ var TypeScript; this.resolveDeclaredSymbol(extendedConstructorTypeProp, context); } - var typeConstructorTypePropType = typeConstructorTypeMembers[i].type; - var extendedConstructorTypePropType = extendedConstructorTypeProp.type; - if (!this.sourceIsSubtypeOfTarget(typeConstructorTypePropType, extendedConstructorTypePropType, classOrInterface, context, comparisonInfoForPropTypeCheck)) { - var propMessage; - var enclosingSymbol = this.getEnclosingSymbolForAST(classOrInterface); - if (comparisonInfoForPropTypeCheck.message) { - propMessage = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3, [extendedConstructorTypeProp.getScopedNameEx().toString(), typeSymbol.toString(enclosingSymbol), extendedType.toString(enclosingSymbol), comparisonInfoForPropTypeCheck.message]); - } else { - propMessage = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible, [extendedConstructorTypeProp.getScopedNameEx().toString(), typeSymbol.toString(enclosingSymbol), extendedType.toString(enclosingSymbol)]); - } - comparisonInfo.addMessage(propMessage); + if (!this.sourcePropertyIsAssignableToTargetProperty(typeConstructorType, extendedConstructorType, typeConstructorTypeMembers[i], extendedConstructorTypeProp, classOrInterface, context, comparisonInfo)) { foundError = true; break; } @@ -48830,13 +50190,13 @@ var TypeScript; PullTypeResolver.prototype.typeCheckIfClassImplementsType = function (classDecl, classSymbol, implementedType, enclosingDecl, context) { var comparisonInfo = new TypeComparisonInfo(); - var foundError = !this.sourceMembersAreSubtypeOfTargetMembers(classSymbol, implementedType, classDecl, context, comparisonInfo); + var foundError = !this.sourceMembersAreAssignableToTargetMembers(classSymbol, implementedType, classDecl, context, comparisonInfo); if (!foundError) { - foundError = !this.sourceCallSignaturesAreSubtypeOfTargetCallSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); if (!foundError) { - foundError = !this.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); if (!foundError) { - foundError = !this.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); } } } @@ -48847,15 +50207,39 @@ var TypeScript; } }; - PullTypeResolver.prototype.hasClassTypeSymbolConflictAsValue = function (valueDeclAST, typeSymbol, enclosingDecl, context) { + PullTypeResolver.prototype.computeValueSymbolFromAST = function (valueDeclAST, context) { + var prevInTypeCheck = context.inTypeCheck; + context.inTypeCheck = false; + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); - var valueSymbol = this.computeNameExpression(valueDeclAST, context, false); + + if (valueDeclAST.kind() == 11 /* IdentifierName */) { + var valueSymbol = this.computeNameExpression(valueDeclAST, context); + } else { + TypeScript.Debug.assert(valueDeclAST.kind() == 121 /* QualifiedName */); + var qualifiedName = valueDeclAST; + + var lhs = this.computeValueSymbolFromAST(qualifiedName.left, context); + var valueSymbol = this.computeDottedNameExpressionFromLHS(lhs.symbol, qualifiedName.left, qualifiedName.right, context, false); + } var valueSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); this.semanticInfoChain.setAliasSymbolForAST(valueDeclAST, typeSymbolAlias); + context.inTypeCheck = prevInTypeCheck; + + return { symbol: valueSymbol, alias: valueSymbolAlias }; + }; + + PullTypeResolver.prototype.hasClassTypeSymbolConflictAsValue = function (baseDeclAST, typeSymbol, enclosingDecl, context) { + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(baseDeclAST); + + var valueDeclAST = baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST; + var valueSymbolInfo = this.computeValueSymbolFromAST(valueDeclAST, context); + var valueSymbol = valueSymbolInfo.symbol; + var valueSymbolAlias = valueSymbolInfo.alias; if (typeSymbolAlias && valueSymbolAlias) { - return typeSymbolAlias != valueSymbolAlias; + return typeSymbolAlias !== valueSymbolAlias; } if (!valueSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */)) { @@ -48865,7 +50249,7 @@ var TypeScript; var associatedContainerType = valueSymbol.type ? valueSymbol.type.getAssociatedContainerType() : null; if (associatedContainerType) { - return associatedContainerType != typeSymbol.getRootSymbol(); + return associatedContainerType !== typeSymbol.getRootSymbol(); } return true; @@ -48896,9 +50280,9 @@ var TypeScript; } } return; - } else if (typeDeclIsClass && isExtendedType && baseDeclAST.kind() == 11 /* IdentifierName */) { + } else if (typeDeclIsClass && isExtendedType) { if (this.hasClassTypeSymbolConflictAsValue(baseDeclAST, baseType, enclosingDecl, context)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.Type_reference_0_in_extends_clause_does_not_reference_constructor_function_for_1, [baseDeclAST.text(), baseType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1, [TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST), baseType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); } } @@ -48911,11 +50295,15 @@ var TypeScript; } if (isExtendedType) { - this.typeCheckIfTypeExtendsType(classOrInterface, name, typeSymbol, baseType, enclosingDecl, context); + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfTypeExtendsType(classOrInterface, name, typeSymbol, baseType, enclosingDecl, context); + }); } else { TypeScript.Debug.assert(classOrInterface.kind() === 131 /* ClassDeclaration */); - this.typeCheckIfClassImplementsType(classOrInterface, typeSymbol, baseType, enclosingDecl, context); + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfClassImplementsType(classOrInterface, typeSymbol, baseType, enclosingDecl, context); + }); } this.checkSymbolPrivacy(typeSymbol, baseType, function (errorSymbol) { @@ -48925,14 +50313,12 @@ var TypeScript; PullTypeResolver.prototype.typeCheckBases = function (classOrInterface, name, heritageClauses, typeSymbol, enclosingDecl, context) { var _this = this; - var extendsClause = TypeScript.getExtendsHeritageClause(heritageClauses); - var implementsClause = TypeScript.getImplementsHeritageClause(heritageClauses); + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); if (!extendsClause && !implementsClause) { return; } - var typeDeclIsClass = classOrInterface.kind() === 131 /* ClassDeclaration */; - if (extendsClause) { for (var i = 0; i < extendsClause.typeNames.nonSeparatorCount(); i++) { this.typeCheckBase(classOrInterface, name, typeSymbol, extendsClause.typeNames.nonSeparatorAt(i), true, enclosingDecl, context); @@ -48978,7 +50364,7 @@ var TypeScript; } var baseTypes = typeSymbol.getExtendedTypes(); for (var i = 0; i < baseTypes.length; i++) { - if (this.checkNamedPropertyTypeIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedMembersMap, context) || this.checkIndexSignatureIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedIndexSignatures, typeHasOwnNumberIndexer, typeHasOwnStringIndexer, context)) { + if (this.checkNamedPropertyIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedMembersMap, context) || this.checkIndexSignatureIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedIndexSignatures, typeHasOwnNumberIndexer, typeHasOwnStringIndexer, context)) { return; } } @@ -48990,7 +50376,7 @@ var TypeScript; this.checkInheritedMembersAgainstInheritedIndexSignatures(name, typeSymbol, inheritedIndexSignatures, inheritedMembersMap, context); }; - PullTypeResolver.prototype.checkNamedPropertyTypeIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, inheritedMembersMap, context) { + PullTypeResolver.prototype.checkNamedPropertyIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, inheritedMembersMap, context) { var baseMembers = baseTypeSymbol.getAllMembers(4096 /* Property */ | 65536 /* Method */, 0 /* all */); for (var i = 0; i < baseMembers.length; i++) { var member = baseMembers[i]; @@ -49000,10 +50386,12 @@ var TypeScript; continue; } + this.resolveDeclaredSymbol(member, context); + if (inheritedMembersMap[memberName]) { var prevMember = inheritedMembersMap[memberName]; - if (prevMember.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(member.type, prevMember.memberSymbol.type)) { - var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_not_identical, [memberName, prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + if (prevMember.baseOrigin !== baseTypeSymbol && !this.propertiesAreIdenticalWithNewEnclosingTypes(baseTypeSymbol, prevMember.baseOrigin, member, prevMember.memberSymbol, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Named_properties_0_of_types_1_and_2_are_not_identical, [memberName, prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); return true; } @@ -49025,14 +50413,15 @@ var TypeScript; var currentInheritedSignature = indexSignaturesFromThisBaseType[i]; var parameterTypeIsString = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.stringTypeSymbol; - var parameterTypeIsNumber = !parameterTypeIsString; + var parameterTypeIsNumber = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + if (parameterTypeIsString && derivedTypeHasOwnStringSignature || parameterTypeIsNumber && derivedTypeHasOwnNumberSignature) { continue; } if (parameterTypeIsString) { if (allInheritedSignatures.stringSignatureWithBaseOrigin) { - if (allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.stringSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType)) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.stringSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_string_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); return true; @@ -49042,7 +50431,7 @@ var TypeScript; } } else if (parameterTypeIsNumber) { if (allInheritedSignatures.numberSignatureWithBaseOrigin) { - if (allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.numberSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType)) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.numberSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_number_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); return true; @@ -49082,16 +50471,16 @@ var TypeScript; continue; } - var memberIsSubtype = this.sourceIsSubtypeOfTarget(memberWithBaseOrigin.memberSymbol.type, relevantSignature.returnType, interfaceName, context, comparisonInfo); + var memberIsSubtype = this.sourceIsAssignableToTarget(memberWithBaseOrigin.memberSymbol.type, relevantSignature.returnType, interfaceName, context, comparisonInfo); if (!memberIsSubtype) { var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); if (relevantSignatureIsNumberSignature) { - var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_a_subtype_of_number_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); } else { - var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_a_subtype_of_string_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); } @@ -49109,11 +50498,11 @@ var TypeScript; } var comparisonInfo = new TypeComparisonInfo(); - var signatureIsSubtype = this.sourceIsSubtypeOfTarget(inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature.returnType, inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature.returnType, interfaceName, context, comparisonInfo); + var signatureIsSubtype = this.sourceIsAssignableToTarget(inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature.returnType, inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature.returnType, interfaceName, context, comparisonInfo); if (!signatureIsSubtype) { var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); - var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_number_indexer_in_type_0_is_not_a_subtype_of_string_indexer_type_in_type_1_NL_2, [ + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2, [ inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [ @@ -49159,7 +50548,7 @@ var TypeScript; return false; } - if (astSymbol.kind === 32768 /* ConstructorMethod */) { + if (astSymbol.kind === 32768 /* ConstructorMethod */ || astSymbol.kind === 16384 /* Function */) { return false; } } @@ -49216,8 +50605,7 @@ var TypeScript; return false; }; - PullTypeResolver.prototype.instantiateType = function (type, typeParameterArgumentMap, instantiateFunctionTypeParameters) { - if (typeof instantiateFunctionTypeParameters === "undefined") { instantiateFunctionTypeParameters = false; } + PullTypeResolver.prototype.instantiateType = function (type, typeParameterArgumentMap) { if (type.isPrimitive()) { return type; } @@ -49230,48 +50618,63 @@ var TypeScript; return typeParameterArgumentMap[type.pullSymbolID]; } - if (type.isTypeParameter() && type.isFunctionTypeParameter()) { - return type; + type._resolveDeclaredSymbol(); + if (type.isTypeParameter()) { + return this.instantiateTypeParameter(type, typeParameterArgumentMap); } - type._resolveDeclaredSymbol(); if (type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap, instantiateFunctionTypeParameters); + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); } return type; }; - PullTypeResolver.prototype.instantiateSignature = function (signature, typeParameterArgumentMap, instantiateFunctionTypeParameters) { - if (typeof instantiateFunctionTypeParameters === "undefined") { instantiateFunctionTypeParameters = false; } + PullTypeResolver.prototype.instantiateTypeParameter = function (typeParameter, typeParameterArgumentMap) { + var constraint = typeParameter.getConstraint(); + if (!constraint) { + return typeParameter; + } + + var instantiatedConstraint = this.instantiateType(constraint, typeParameterArgumentMap); + + if (instantiatedConstraint == constraint) { + return typeParameter; + } + + var rootTypeParameter = typeParameter.getRootSymbol(); + var instantiation = rootTypeParameter.getSpecialization([instantiatedConstraint]); + if (instantiation) { + return instantiation; + } + + instantiation = new TypeScript.PullInstantiatedTypeParameterSymbol(rootTypeParameter, instantiatedConstraint); + return instantiation; + }; + + PullTypeResolver.prototype.instantiateSignature = function (signature, typeParameterArgumentMap) { if (!signature.wrapsSomeTypeParameter(typeParameterArgumentMap)) { return signature; } - var typeArguments = []; + var rootSignature = signature.getRootSymbol(); + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(this, signature, mutableTypeParameterMap); - TypeScript.nSpecializedSignaturesCreated++; - - var instantiatedSignature = new TypeScript.PullSignatureSymbol(signature.kind); - instantiatedSignature.setRootSymbol(signature); - - var typeParameters = signature.getTypeParameters(); - var constraint = null; - var typeParameter = null; - - for (var i = 0; i < typeParameters.length; i++) { - typeParameter = typeParameters[i]; - - instantiatedSignature.addTypeParameter(typeParameter); + var instantiatedSignature = rootSignature.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiatedSignature) { + return instantiatedSignature; } - instantiatedSignature.returnType = this.instantiateType((signature.returnType || this.semanticInfoChain.anyTypeSymbol), typeParameterArgumentMap, instantiateFunctionTypeParameters); + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(signature, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; - if (instantiateFunctionTypeParameters) { - instantiatedSignature.functionType = this.instantiateType(signature.functionType, typeParameterArgumentMap, instantiateFunctionTypeParameters); - } + instantiatedSignature = new TypeScript.PullInstantiatedSignatureSymbol(rootSignature, typeParameterArgumentMap); - var parameters = signature.parameters; + instantiatedSignature.returnType = this.instantiateType((rootSignature.returnType || this.semanticInfoChain.anyTypeSymbol), typeParameterArgumentMap); + instantiatedSignature.functionType = this.instantiateType(rootSignature.functionType, typeParameterArgumentMap); + + var parameters = rootSignature.parameters; var parameter = null; if (parameters) { @@ -49288,7 +50691,7 @@ var TypeScript; } instantiatedSignature.addParameter(parameter, parameter.isOptional); - parameter.type = this.instantiateType(parameters[j].type, typeParameterArgumentMap, instantiateFunctionTypeParameters); + parameter.type = this.instantiateType(parameters[j].type, typeParameterArgumentMap); } } @@ -49300,7 +50703,7 @@ var TypeScript; TypeScript.PullTypeResolver = PullTypeResolver; var TypeComparisonInfo = (function () { - function TypeComparisonInfo(sourceComparisonInfo) { + function TypeComparisonInfo(sourceComparisonInfo, useSameIndent) { this.onlyCaptureFirstError = false; this.flags = 0 /* SuccessfulComparison */; this.message = ""; @@ -49310,7 +50713,10 @@ var TypeScript; this.flags = sourceComparisonInfo.flags; this.onlyCaptureFirstError = sourceComparisonInfo.onlyCaptureFirstError; this.stringConstantVal = sourceComparisonInfo.stringConstantVal; - this.indent = sourceComparisonInfo.indent + 1; + this.indent = sourceComparisonInfo.indent; + if (!useSameIndent) { + this.indent++; + } } } TypeComparisonInfo.prototype.indentString = function () { @@ -49441,25 +50847,24 @@ var TypeScript; this._resolver = null; this._topLevelDecls = null; this._fileNames = null; - var span = new TypeScript.TextSpan(0, 0); - var globalDecl = new TypeScript.RootPullDecl("", "", 0 /* Global */, 0 /* None */, span, this, false); + var globalDecl = new TypeScript.RootPullDecl("", "", 0 /* Global */, 0 /* None */, this, false); this.documents[0] = new TypeScript.Document(this.compiler, this, "", [], null, 0 /* None */, 0, false, null, globalDecl); - this.anyTypeDecl = new TypeScript.NormalPullDecl("any", "any", 2 /* Primitive */, 0 /* None */, globalDecl, span); - this.booleanTypeDecl = new TypeScript.NormalPullDecl("boolean", "boolean", 2 /* Primitive */, 0 /* None */, globalDecl, span); - this.numberTypeDecl = new TypeScript.NormalPullDecl("number", "number", 2 /* Primitive */, 0 /* None */, globalDecl, span); - this.stringTypeDecl = new TypeScript.NormalPullDecl("string", "string", 2 /* Primitive */, 0 /* None */, globalDecl, span); - this.voidTypeDecl = new TypeScript.NormalPullDecl("void", "void", 2 /* Primitive */, 0 /* None */, globalDecl, span); + this.anyTypeDecl = new TypeScript.NormalPullDecl("any", "any", 2 /* Primitive */, 0 /* None */, globalDecl); + this.booleanTypeDecl = new TypeScript.NormalPullDecl("boolean", "boolean", 2 /* Primitive */, 0 /* None */, globalDecl); + this.numberTypeDecl = new TypeScript.NormalPullDecl("number", "number", 2 /* Primitive */, 0 /* None */, globalDecl); + this.stringTypeDecl = new TypeScript.NormalPullDecl("string", "string", 2 /* Primitive */, 0 /* None */, globalDecl); + this.voidTypeDecl = new TypeScript.NormalPullDecl("void", "void", 2 /* Primitive */, 0 /* None */, globalDecl); - this.nullTypeDecl = new TypeScript.RootPullDecl("null", "", 2 /* Primitive */, 0 /* None */, span, this, false); - this.undefinedTypeDecl = new TypeScript.RootPullDecl("undefined", "", 2 /* Primitive */, 0 /* None */, span, this, false); - this.undefinedValueDecl = new TypeScript.NormalPullDecl("undefined", "undefined", 512 /* Variable */, 8 /* Ambient */, globalDecl, span); + this.nullTypeDecl = new TypeScript.RootPullDecl("null", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedTypeDecl = new TypeScript.RootPullDecl("undefined", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedValueDecl = new TypeScript.NormalPullDecl("undefined", "undefined", 512 /* Variable */, 8 /* Ambient */, globalDecl); this.invalidate(); } SemanticInfoChain.prototype.getDocument = function (fileName) { var document = this.fileNameToDocument[fileName]; - return document ? document : null; + return document || null; }; SemanticInfoChain.prototype.lineMap = function (fileName) { @@ -49505,8 +50910,7 @@ var TypeScript; this.undefinedTypeSymbol = this.addPrimitiveTypeSymbol(this.undefinedTypeDecl); this.undefinedValueSymbol = this.addPrimitiveValueSymbol(this.undefinedValueDecl, this.undefinedTypeSymbol); - var span = new TypeScript.TextSpan(0, 0); - var emptyTypeDecl = new TypeScript.PullSynthesizedDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, null, span, this); + var emptyTypeDecl = new TypeScript.PullSynthesizedDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, null, this); var emptyTypeSymbol = new TypeScript.PullTypeSymbol("{}", 8388608 /* ObjectType */); emptyTypeDecl.setSymbol(emptyTypeSymbol); emptyTypeSymbol.addDeclaration(emptyTypeDecl); @@ -49567,7 +50971,7 @@ var TypeScript; break; } - if (doNotGoPastThisDecl && topLevelDecl.name == doNotGoPastThisDecl.fileName()) { + if (doNotGoPastThisDecl && topLevelDecl.name === doNotGoPastThisDecl.fileName()) { return null; } } @@ -49604,13 +51008,6 @@ var TypeScript; SemanticInfoChain.prototype.findExternalModule = function (id) { id = TypeScript.normalizePath(id); - var dtsFile = id + ".d.ts"; - var dtsCacheID = this.getDeclPathCacheID([dtsFile], 32 /* DynamicModule */); - var symbol = this.symbolCache[dtsCacheID]; - if (symbol) { - return symbol; - } - var tsFile = id + ".ts"; var tsCacheID = this.getDeclPathCacheID([tsFile], 32 /* DynamicModule */); symbol = this.symbolCache[tsCacheID]; @@ -49618,27 +51015,44 @@ var TypeScript; return symbol; } - symbol = null; + var dtsFile = id + ".d.ts"; + var dtsCacheID = this.getDeclPathCacheID([dtsFile], 32 /* DynamicModule */); + var symbol = this.symbolCache[dtsCacheID]; + if (symbol) { + return symbol; + } + + var dtsSymbol; for (var i = 0; i < this.documents.length; i++) { var document = this.documents[i]; var topLevelDecl = document.topLevelDecl(); if (topLevelDecl.isExternalModule()) { - var isDtsFile = document.fileName == dtsFile; - if (isDtsFile || document.fileName == tsFile) { + var isTsFile = document.fileName === tsFile; + if (isTsFile || document.fileName === dtsFile) { var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; symbol = dynamicModuleDecl.getSymbol(); - this.symbolCache[dtsCacheID] = isDtsFile ? symbol : null; - this.symbolCache[tsCacheID] = !TypeScript.isDTSFile ? symbol : null; - return symbol; + + if (isTsFile) { + this.symbolCache[tsCacheID] = symbol; + + return symbol; + } else { + dtsSymbol = symbol; + } } } } + if (dtsSymbol) { + this.symbolCache[dtsCacheID] = symbol; + return dtsSymbol; + } + this.symbolCache[dtsCacheID] = null; this.symbolCache[tsCacheID] = null; - return symbol; + return null; }; SemanticInfoChain.prototype.findAmbientExternalModuleInGlobalContext = function (id) { @@ -49685,25 +51099,21 @@ var TypeScript; var decls = TypeScript.sentinelEmptyArray; var path; var foundDecls = TypeScript.sentinelEmptyArray; - var keepSearching = (declKind & 164 /* SomeContainer */) || (declKind & 16 /* Interface */); for (var i = 0; i < declPath.length; i++) { path = declPath[i]; decls = TypeScript.sentinelEmptyArray; + var kind = (i === declPath.length - 1) ? declKind : 164 /* SomeContainer */; for (var j = 0; j < declsToSearch.length; j++) { - foundDecls = declsToSearch[j].searchChildDecls(path, declKind); + foundDecls = declsToSearch[j].searchChildDecls(path, kind); for (var k = 0; k < foundDecls.length; k++) { - if (decls == TypeScript.sentinelEmptyArray) { + if (decls === TypeScript.sentinelEmptyArray) { decls = []; } decls[decls.length] = foundDecls[k]; } - - if (foundDecls.length && !keepSearching) { - break; - } } declsToSearch = decls; @@ -49752,9 +51162,20 @@ var TypeScript; var symbol = null; if (decls.length) { - symbol = decls[0].getSymbol(); + var decl = decls[0]; + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + var valueDecl = decl.getValueDecl(); + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + } + symbol = decl.getSymbol(); if (symbol) { + for (var i = 1; i < decls.length; i++) { + decls[i].ensureSymbolIsBound(); + } + this.symbolCache[cacheID] = symbol; } } @@ -49806,7 +51227,6 @@ var TypeScript; } TypeScript.pullSymbolID = 0; - TypeScript.globalTyvarID = 0; this.resetGlobalSymbols(); @@ -49814,7 +51234,7 @@ var TypeScript; }; SemanticInfoChain.prototype.settingsChangeAffectsSyntax = function (before, after) { - return before.allowAutomaticSemicolonInsertion() !== after.allowAutomaticSemicolonInsertion() || before.codeGenTarget() !== after.codeGenTarget() || before.propagateEnumConstants() != after.propagateEnumConstants(); + return before.allowAutomaticSemicolonInsertion() !== after.allowAutomaticSemicolonInsertion() || before.codeGenTarget() !== after.codeGenTarget() || before.propagateEnumConstants() !== after.propagateEnumConstants(); }; SemanticInfoChain.prototype.setSymbolForAST = function (ast, symbol) { @@ -49822,7 +51242,7 @@ var TypeScript; }; SemanticInfoChain.prototype.getSymbolForAST = function (ast) { - return this.astSymbolMap[ast.syntaxID()]; + return this.astSymbolMap[ast.syntaxID()] || null; }; SemanticInfoChain.prototype.setAliasSymbolForAST = function (ast, symbol) { @@ -49872,7 +51292,7 @@ var TypeScript; SemanticInfoChain.prototype.getDiagnostics = function (fileName) { var diagnostics = this.fileNameToDiagnostics[fileName]; - return diagnostics ? diagnostics : []; + return diagnostics || []; }; SemanticInfoChain.prototype.getBinder = function () { @@ -49902,9 +51322,8 @@ var TypeScript; containingSymbol.addIndexSignature(indexSignature); - var span = TypeScript.TextSpan.fromBounds(ast.start(), ast.end()); - var indexSigDecl = new TypeScript.PullSynthesizedDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, containingDecl, span, containingDecl.semanticInfoChain()); - var indexParamDecl = new TypeScript.PullSynthesizedDecl(indexParamName, indexParamName, 2048 /* Parameter */, 0 /* None */, indexSigDecl, span, containingDecl.semanticInfoChain()); + var indexSigDecl = new TypeScript.PullSynthesizedDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, containingDecl, containingDecl.semanticInfoChain); + var indexParamDecl = new TypeScript.PullSynthesizedDecl(indexParamName, indexParamName, 2048 /* Parameter */, 0 /* None */, indexSigDecl, containingDecl.semanticInfoChain); indexSigDecl.setSignatureSymbol(indexSignature); indexParamDecl.setSymbol(indexParameterSymbol); indexSignature.addDeclaration(indexSigDecl); @@ -49961,14 +51380,28 @@ var TypeScript; return this._topLevelDecls; }; - SemanticInfoChain.prototype.addDiagnosticFromAST = function (ast, diagnosticKey, arguments) { - if (typeof arguments === "undefined") { arguments = null; } - this.addDiagnostic(this.diagnosticFromAST(ast, diagnosticKey, arguments)); + SemanticInfoChain.prototype.addDiagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + this.addDiagnostic(this.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations)); }; - SemanticInfoChain.prototype.diagnosticFromAST = function (ast, diagnosticKey, arguments) { - if (typeof arguments === "undefined") { arguments = null; } - return new TypeScript.Diagnostic(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width(), diagnosticKey, arguments); + SemanticInfoChain.prototype.diagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + return new TypeScript.Diagnostic(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width(), diagnosticKey, _arguments, additionalLocations); + }; + + SemanticInfoChain.prototype.locationFromAST = function (ast) { + return new TypeScript.Location(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width()); + }; + + SemanticInfoChain.prototype.duplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + return this.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0, [identifier], additionalLocationAST ? [this.locationFromAST(additionalLocationAST)] : null); + }; + + SemanticInfoChain.prototype.addDuplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + this.addDiagnostic(this.duplicateIdentifierDiagnosticFromAST(ast, identifier, additionalLocationAST)); }; return SemanticInfoChain; })(); @@ -50039,7 +51472,6 @@ var TypeScript; function preCollectImportDecls(ast, context) { var importDecl = ast; var declFlags = 0 /* None */; - var span = TypeScript.TextSpan.fromBounds(importDecl.start(), importDecl.end()); var parent = context.getParent(); @@ -50047,19 +51479,17 @@ var TypeScript; declFlags |= 1 /* Exported */; } - var decl = new TypeScript.NormalPullDecl(importDecl.identifier.valueText(), importDecl.identifier.text(), 128 /* TypeAlias */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(importDecl.identifier.valueText(), importDecl.identifier.text(), 128 /* TypeAlias */, declFlags, parent); context.semanticInfoChain.setDeclForAST(ast, decl); context.semanticInfoChain.setASTForDecl(decl, ast); } function preCollectScriptDecls(sourceUnit, context) { - var span = TypeScript.TextSpan.fromBounds(sourceUnit.start(), sourceUnit.end()); - var fileName = sourceUnit.fileName(); var isExternalModule = context.document.isExternalModule(); - var decl = new TypeScript.RootPullDecl(fileName, fileName, 1 /* Script */, 0 /* None */, span, context.semanticInfoChain, isExternalModule); + var decl = new TypeScript.RootPullDecl(fileName, fileName, 1 /* Script */, 0 /* None */, context.semanticInfoChain, isExternalModule); context.semanticInfoChain.setDeclForAST(sourceUnit, decl); context.semanticInfoChain.setASTForDecl(decl, sourceUnit); @@ -50075,10 +51505,9 @@ var TypeScript; var moduleContainsExecutableCode = containsExecutableCode(sourceUnit.moduleElements); var kind = 32 /* DynamicModule */; - var span = TypeScript.TextSpan.fromBounds(sourceUnit.start(), sourceUnit.end()); var valueText = TypeScript.quoteStr(fileName); - var decl = new TypeScript.NormalPullDecl(valueText, fileName, kind, declFlags, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(valueText, fileName, kind, declFlags, context.getParent()); context.semanticInfoChain.setASTForDecl(decl, sourceUnit); @@ -50095,7 +51524,6 @@ var TypeScript; function preCollectEnumDecls(enumDecl, context) { var declFlags = 0 /* None */; var enumName = enumDecl.identifier.valueText(); - var kind = 4 /* Container */; if ((TypeScript.hasModifier(enumDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(enumDecl, context)) && !containingModuleHasExportAssignment(enumDecl)) { declFlags |= 1 /* Exported */; @@ -50106,18 +51534,13 @@ var TypeScript; } declFlags |= 4096 /* Enum */; - kind = 64 /* Enum */; + var kind = 64 /* Enum */; - var span = TypeScript.TextSpan.fromBounds(enumDecl.start(), enumDecl.end()); - - var enumDeclaration = new TypeScript.NormalPullDecl(enumName, enumDecl.identifier.text(), kind, declFlags, context.getParent(), span); + var enumDeclaration = new TypeScript.NormalPullDecl(enumName, enumDecl.identifier.text(), kind, declFlags, context.getParent()); context.semanticInfoChain.setDeclForAST(enumDecl, enumDeclaration); context.semanticInfoChain.setASTForDecl(enumDeclaration, enumDecl); - var enumIndexerDecl = new TypeScript.NormalPullDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, enumDeclaration, span); - var enumIndexerParameter = new TypeScript.NormalPullDecl("x", "x", 2048 /* Parameter */, 0 /* None */, enumIndexerDecl, span); - - var valueDecl = new TypeScript.NormalPullDecl(enumDeclaration.name, enumDeclaration.getDisplayName(), 512 /* Variable */, enumDeclaration.flags, context.getParent(), enumDeclaration.getSpan()); + var valueDecl = new TypeScript.NormalPullDecl(enumDeclaration.name, enumDeclaration.getDisplayName(), 512 /* Variable */, enumDeclaration.flags, context.getParent()); enumDeclaration.setValueDecl(valueDecl); context.semanticInfoChain.setASTForDecl(valueDecl, enumDecl); @@ -50127,9 +51550,7 @@ var TypeScript; function createEnumElementDecls(propertyDecl, context) { var parent = context.getParent(); - var span = TypeScript.TextSpan.fromBounds(propertyDecl.start(), propertyDecl.end()); - - var decl = new TypeScript.PullEnumElementDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), parent, span); + var decl = new TypeScript.PullEnumElementDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), parent); context.semanticInfoChain.setDeclForAST(propertyDecl, decl); context.semanticInfoChain.setASTForDecl(decl, propertyDecl); } @@ -50151,13 +51572,11 @@ var TypeScript; var kind = isDynamic ? 32 /* DynamicModule */ : 4 /* Container */; - var span = TypeScript.TextSpan.fromBounds(moduleDecl.start(), moduleDecl.end()); - if (moduleDecl.stringLiteral) { var valueText = TypeScript.quoteStr(moduleDecl.stringLiteral.valueText()); var text = moduleDecl.stringLiteral.text(); - var decl = new TypeScript.NormalPullDecl(valueText, text, kind, declFlags, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(valueText, text, kind, declFlags, context.getParent()); context.semanticInfoChain.setDeclForAST(moduleDecl, decl); context.semanticInfoChain.setDeclForAST(moduleDecl.stringLiteral, decl); @@ -50178,7 +51597,7 @@ var TypeScript; specificFlags |= 1 /* Exported */; } - var decl = new TypeScript.NormalPullDecl(moduleName.valueText(), moduleName.text(), kind, specificFlags, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(moduleName.valueText(), moduleName.text(), kind, specificFlags, context.getParent()); context.semanticInfoChain.setDeclForAST(moduleDecl, decl); context.semanticInfoChain.setDeclForAST(moduleName, decl); @@ -50210,7 +51629,7 @@ var TypeScript; function createModuleVariableDecl(decl, moduleNameAST, context) { decl.setFlags(decl.flags | getInitializationFlag(decl)); - var valueDecl = new TypeScript.NormalPullDecl(decl.name, decl.getDisplayName(), 512 /* Variable */, decl.flags, context.getParent(), decl.getSpan()); + var valueDecl = new TypeScript.NormalPullDecl(decl.name, decl.getDisplayName(), 512 /* Variable */, decl.flags, context.getParent()); decl.setValueDecl(valueDecl); context.semanticInfoChain.setASTForDecl(valueDecl, moduleNameAST); } @@ -50225,7 +51644,11 @@ var TypeScript; if (containsExecutableCode(moduleDecl.moduleElements)) { return true; } - } else if (member.kind() !== 128 /* InterfaceDeclaration */ && member.kind() !== 133 /* ImportDeclaration */) { + } else if (member.kind() === 133 /* ImportDeclaration */) { + if (TypeScript.hasModifier(member.modifiers, 1 /* Exported */)) { + return true; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */) { return true; } } @@ -50235,7 +51658,6 @@ var TypeScript; function preCollectClassDecls(classDecl, context) { var declFlags = 0 /* None */; - var constructorDeclKind = 512 /* Variable */; if ((TypeScript.hasModifier(classDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(classDecl, context)) && !containingModuleHasExportAssignment(classDecl)) { declFlags |= 1 /* Exported */; @@ -50245,12 +51667,11 @@ var TypeScript; declFlags |= 8 /* Ambient */; } - var span = TypeScript.TextSpan.fromBounds(classDecl.start(), classDecl.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 8 /* Class */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 8 /* Class */, declFlags, parent); - var constructorDecl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), constructorDeclKind, declFlags | 16384 /* ClassConstructorVariable */, parent, span); + var constructorDecl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 512 /* Variable */, declFlags | 16384 /* ClassConstructorVariable */, parent); decl.setValueDecl(constructorDecl); @@ -50268,15 +51689,13 @@ var TypeScript; var declFlags = 0 /* None */; - var span = TypeScript.TextSpan.fromBounds(objectType.start(), objectType.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", 8388608 /* ObjectType */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", 8388608 /* ObjectType */, declFlags, parent); context.semanticInfoChain.setDeclForAST(objectType, decl); context.semanticInfoChain.setASTForDecl(decl, objectType); @@ -50290,10 +51709,9 @@ var TypeScript; declFlags |= 1 /* Exported */; } - var span = TypeScript.TextSpan.fromBounds(interfaceDecl.start(), interfaceDecl.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(interfaceDecl.identifier.valueText(), interfaceDecl.identifier.text(), 16 /* Interface */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(interfaceDecl.identifier.valueText(), interfaceDecl.identifier.text(), 16 /* Interface */, declFlags, parent); context.semanticInfoChain.setDeclForAST(interfaceDecl, decl); context.semanticInfoChain.setASTForDecl(decl, interfaceDecl); @@ -50319,15 +51737,13 @@ var TypeScript; declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var span = TypeScript.TextSpan.fromBounds(argDecl.start(), argDecl.end()); - - var decl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 2048 /* Parameter */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 2048 /* Parameter */, declFlags, parent); if (argDecl.equalsValueClause) { parent.flags |= 33554432 /* HasDefaultArgs */; } - if (parent.kind == 32768 /* ConstructorMethod */) { + if (parent.kind === 32768 /* ConstructorMethod */) { decl.setFlag(67108864 /* ConstructorParameter */); } @@ -50335,12 +51751,14 @@ var TypeScript; var isInConstructor = parent.kind === 32768 /* ConstructorMethod */; if (isPublicOrPrivate && isInConstructor) { var parentsParent = context.parentChain[context.parentChain.length - 2]; - var propDecl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 4096 /* Property */, declFlags, parentsParent, span); + + var propDeclFlags = declFlags & ~128 /* Optional */; + var propDecl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 4096 /* Property */, propDeclFlags, parentsParent); propDecl.setValueDecl(decl); decl.setFlag(8388608 /* PropertyParameter */); propDecl.setFlag(8388608 /* PropertyParameter */); - if (parent.kind == 32768 /* ConstructorMethod */) { + if (parent.kind === 32768 /* ConstructorMethod */) { propDecl.setFlag(67108864 /* ConstructorParameter */); } @@ -50358,15 +51776,13 @@ var TypeScript; function preCollectTypeParameterDecl(typeParameterDecl, context) { var declFlags = 0 /* None */; - var span = TypeScript.TextSpan.fromBounds(typeParameterDecl.start(), typeParameterDecl.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(typeParameterDecl.identifier.valueText(), typeParameterDecl.identifier.text(), 8192 /* TypeParameter */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(typeParameterDecl.identifier.valueText(), typeParameterDecl.identifier.text(), 8192 /* TypeParameter */, declFlags, parent); context.semanticInfoChain.setASTForDecl(decl, typeParameterDecl); context.semanticInfoChain.setDeclForAST(typeParameterDecl, decl); } @@ -50380,9 +51796,7 @@ var TypeScript; declFlags |= 128 /* Optional */; } - var span = TypeScript.TextSpan.fromBounds(propertyDecl.start(), propertyDecl.end()); - - var decl = new TypeScript.NormalPullDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(propertyDecl, decl); context.semanticInfoChain.setASTForDecl(decl, propertyDecl); } @@ -50401,10 +51815,9 @@ var TypeScript; declFlags |= 16 /* Static */; } - var span = TypeScript.TextSpan.fromBounds(memberDecl.start(), memberDecl.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(memberDecl.variableDeclarator.propertyName.valueText(), memberDecl.variableDeclarator.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(memberDecl.variableDeclarator.propertyName.valueText(), memberDecl.variableDeclarator.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(memberDecl, decl); context.semanticInfoChain.setDeclForAST(memberDecl.variableDeclarator, decl); context.semanticInfoChain.setASTForDecl(decl, memberDecl); @@ -50414,7 +51827,7 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 512 /* Variable */; - var modifiers = TypeScript.getVariableDeclaratorModifiers(varDecl); + var modifiers = TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl); if ((TypeScript.hasModifier(modifiers, 1 /* Exported */) || isParsingAmbientModule(varDecl, context)) && !containingModuleHasExportAssignment(varDecl)) { declFlags |= 1 /* Exported */; } @@ -50423,15 +51836,13 @@ var TypeScript; declFlags |= 8 /* Ambient */; } - var span = TypeScript.TextSpan.fromBounds(varDecl.start(), varDecl.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(varDecl.propertyName.valueText(), varDecl.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(varDecl.propertyName.valueText(), varDecl.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(varDecl, decl); context.semanticInfoChain.setASTForDecl(decl, varDecl); @@ -50453,15 +51864,13 @@ var TypeScript; var declFlags = 2048 /* Signature */; var declType = 16777216 /* FunctionType */; - var span = TypeScript.TextSpan.fromBounds(functionTypeDeclAST.start(), functionTypeDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(functionTypeDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, functionTypeDeclAST); @@ -50472,15 +51881,13 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 33554432 /* ConstructorType */; - var span = TypeScript.TextSpan.fromBounds(constructorTypeDeclAST.start(), constructorTypeDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(constructorTypeDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, constructorTypeDeclAST); @@ -50503,15 +51910,13 @@ var TypeScript; declFlags |= 2048 /* Signature */; } - var span = TypeScript.TextSpan.fromBounds(funcDeclAST.start(), funcDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(funcDeclAST.identifier.valueText(), funcDeclAST.identifier.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(funcDeclAST.identifier.valueText(), funcDeclAST.identifier.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(funcDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, funcDeclAST); @@ -50526,8 +51931,6 @@ var TypeScript; declFlags |= 8192 /* ArrowFunction */; } - var span = TypeScript.TextSpan.fromBounds(functionExpressionDeclAST.start(), functionExpressionDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { @@ -50536,7 +51939,7 @@ var TypeScript; var name = id ? id.text() : ""; var displayNameText = displayName ? displayName.text() : ""; - var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, parent, span, displayNameText); + var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, parent, displayNameText); context.semanticInfoChain.setDeclForAST(functionExpressionDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, functionExpressionDeclAST); @@ -50552,9 +51955,7 @@ var TypeScript; declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var span = TypeScript.TextSpan.fromBounds(simpleArrow.identifier.start(), simpleArrow.identifier.end()); - - var decl = new TypeScript.NormalPullDecl(simpleArrow.identifier.valueText(), simpleArrow.identifier.text(), 2048 /* Parameter */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(simpleArrow.identifier.valueText(), simpleArrow.identifier.text(), 2048 /* Parameter */, declFlags, parent); context.semanticInfoChain.setASTForDecl(decl, simpleArrow.identifier); context.semanticInfoChain.setDeclForAST(simpleArrow.identifier, decl); @@ -50581,10 +51982,9 @@ var TypeScript; declFlags |= 2048 /* Signature */; } - var span = TypeScript.TextSpan.fromBounds(funcDecl.start(), funcDecl.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(funcDecl.propertyName.valueText(), funcDecl.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(funcDecl.propertyName.valueText(), funcDecl.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(funcDecl, decl); context.semanticInfoChain.setASTForDecl(decl, funcDecl); @@ -50595,11 +51995,9 @@ var TypeScript; var declFlags = 2048 /* Signature */; var declType = 4194304 /* IndexSignature */; - var span = TypeScript.TextSpan.fromBounds(indexSignatureDeclAST.start(), indexSignatureDeclAST.end()); - var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(indexSignatureDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, indexSignatureDeclAST); @@ -50616,15 +52014,13 @@ var TypeScript; var declFlags = 2048 /* Signature */; var declType = 1048576 /* CallSignature */; - var span = TypeScript.TextSpan.fromBounds(callSignature.start(), callSignature.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(callSignature, decl); context.semanticInfoChain.setASTForDecl(decl, callSignature); @@ -50642,10 +52038,9 @@ var TypeScript; declFlags |= 128 /* Optional */; } - var span = TypeScript.TextSpan.fromBounds(method.start(), method.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(method.propertyName.valueText(), method.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(method.propertyName.valueText(), method.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(method, decl); context.semanticInfoChain.setASTForDecl(decl, method); @@ -50656,15 +52051,13 @@ var TypeScript; var declFlags = 2048 /* Signature */; var declType = 2097152 /* ConstructSignature */; - var span = TypeScript.TextSpan.fromBounds(constructSignatureDeclAST.start(), constructSignatureDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(constructSignatureDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, constructSignatureDeclAST); @@ -50679,8 +52072,6 @@ var TypeScript; declFlags |= 2048 /* Signature */; } - var span = TypeScript.TextSpan.fromBounds(constructorDeclAST.start(), constructorDeclAST.end()); - var parent = context.getParent(); if (parent) { @@ -50691,7 +52082,7 @@ var TypeScript; } } - var decl = new TypeScript.NormalPullDecl(parent.name, parent.getDisplayName(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(parent.name, parent.getDisplayName(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(constructorDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, constructorDeclAST); @@ -50712,15 +52103,13 @@ var TypeScript; declFlags |= 4 /* Public */; } - var span = TypeScript.TextSpan.fromBounds(getAccessorDeclAST.start(), getAccessorDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(getAccessorDeclAST.propertyName.valueText(), getAccessorDeclAST.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(getAccessorDeclAST.propertyName.valueText(), getAccessorDeclAST.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(getAccessorDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, getAccessorDeclAST); @@ -50745,15 +52134,13 @@ var TypeScript; declFlags |= 4 /* Public */; } - var span = TypeScript.TextSpan.fromBounds(setAccessorDeclAST.start(), setAccessorDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(setAccessorDeclAST.propertyName.valueText(), setAccessorDeclAST.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(setAccessorDeclAST.propertyName.valueText(), setAccessorDeclAST.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(setAccessorDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, setAccessorDeclAST); @@ -50764,15 +52151,13 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 268435456 /* CatchBlock */; - var span = TypeScript.TextSpan.fromBounds(ast.start(), ast.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(ast, decl); context.semanticInfoChain.setASTForDecl(decl, ast); @@ -50781,15 +52166,13 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 1024 /* CatchVariable */; - var span = TypeScript.TextSpan.fromBounds(ast.identifier.start(), ast.identifier.end()); - var parent = context.getParent(); if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(ast.identifier.valueText(), ast.identifier.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(ast.identifier.valueText(), ast.identifier.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(ast.identifier, decl); context.semanticInfoChain.setASTForDecl(decl, ast.identifier); @@ -50802,11 +52185,9 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 134217728 /* WithBlock */; - var span = TypeScript.TextSpan.fromBounds(ast.start(), ast.end()); - var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(ast, decl); context.semanticInfoChain.setASTForDecl(decl, ast); @@ -50814,8 +52195,7 @@ var TypeScript; } function preCollectObjectLiteralDecls(ast, context) { - var span = TypeScript.TextSpan.fromBounds(ast.start(), ast.end()); - var decl = new TypeScript.NormalPullDecl("", "", 256 /* ObjectLiteral */, 0 /* None */, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl("", "", 256 /* ObjectLiteral */, 0 /* None */, context.getParent()); context.semanticInfoChain.setDeclForAST(ast, decl); context.semanticInfoChain.setASTForDecl(decl, ast); @@ -50827,7 +52207,7 @@ var TypeScript; var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); var span = TypeScript.TextSpan.fromBounds(propertyAssignment.start(), propertyAssignment.end()); - var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); @@ -50835,9 +52215,8 @@ var TypeScript; function preCollectFunctionPropertyAssignmentDecls(propertyAssignment, context) { var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); - var span = TypeScript.TextSpan.fromBounds(propertyAssignment.start(), propertyAssignment.end()); - var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); @@ -51043,7 +52422,7 @@ var TypeScript; function computeEnumElementConstantValue(expression, enumMemberDecls, context) { TypeScript.Debug.assert(expression); - if (TypeScript.isIntegerLiteralAST(expression)) { + if (TypeScript.ASTHelpers.isIntegerLiteralAST(expression)) { var token; switch (expression.kind()) { case 164 /* PlusExpression */: @@ -51111,12 +52490,13 @@ var TypeScript; function PullSymbolBinder(semanticInfoChain) { this.semanticInfoChain = semanticInfoChain; this.declsBeingBound = []; + this.inBindingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); } PullSymbolBinder.prototype.getParent = function (decl, returnInstanceType) { if (typeof returnInstanceType === "undefined") { returnInstanceType = false; } var parentDecl = decl.getParentDecl(); - if (parentDecl.kind == 1 /* Script */) { + if (parentDecl.kind === 1 /* Script */) { return null; } @@ -51129,9 +52509,9 @@ var TypeScript; parent = parentDecl.getSymbol(); if (parent) { var parentDeclKind = parentDecl.kind; - if (parentDeclKind == 262144 /* GetAccessor */) { + if (parentDeclKind === 262144 /* GetAccessor */) { parent = parent.getGetter(); - } else if (parentDeclKind == 524288 /* SetAccessor */) { + } else if (parentDeclKind === 524288 /* SetAccessor */) { parent = parent.getSetter(); } } @@ -51175,7 +52555,7 @@ var TypeScript; PullSymbolBinder.prototype.getExistingSymbol = function (decl, searchKind, parent) { var lookingForValue = (searchKind & 68147712 /* SomeValue */) !== 0; - var lookingForType = (searchKind & 58728539 /* SomeType */) !== 0; + var lookingForType = (searchKind & 58728795 /* SomeType */) !== 0; var lookingForContainer = (searchKind & 164 /* SomeContainer */) !== 0; var name = decl.name; if (parent) { @@ -51232,7 +52612,7 @@ var TypeScript; var isExported = (decl.flags & 1 /* Exported */) !== 0; var prevDecls = prevSymbol.getDeclarations(); var prevIsExported = (prevDecls[prevDecls.length - 1].flags & 1 /* Exported */) !== 0; - if ((isExported !== prevIsExported) && !prevSymbol.isSignature() && (decl.kind & 7340032 /* SomeSignature */) == 0) { + if ((isExported !== prevIsExported) && !prevSymbol.isSignature() && (decl.kind & 7340032 /* SomeSignature */) === 0) { if (reportError) { var ast = this.semanticInfoChain.getASTForDecl(decl); this.semanticInfoChain.addDiagnosticFromAST(ast, TypeScript.DiagnosticCode.All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported, [decl.getDisplayName()]); @@ -51243,6 +52623,16 @@ var TypeScript; return true; }; + PullSymbolBinder.prototype.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList = function (signature, currentSignatures) { + var signatureDecl = signature.getDeclarations()[0]; + TypeScript.Debug.assert(signatureDecl); + var enclosingDecl = signatureDecl.getParentDecl(); + var indexToInsert = TypeScript.ArrayUtilities.indexOf(currentSignatures, function (someSignature) { + return someSignature.getDeclarations()[0].getParentDecl() !== enclosingDecl; + }); + return indexToInsert < 0 ? currentSignatures.length : indexToInsert; + }; + PullSymbolBinder.prototype.bindEnumDeclarationToPullSymbol = function (enumContainerDecl) { var enumName = enumContainerDecl.name; @@ -51260,7 +52650,6 @@ var TypeScript; var enumAST = this.semanticInfoChain.getASTForDecl(enumContainerDecl); var isExported = enumContainerDecl.flags & 1 /* Exported */; - var isInitializedModule = (enumContainerDecl.flags & 102400 /* SomeInitializedModule */) != 0; var createdNewSymbol = false; @@ -51268,9 +52657,7 @@ var TypeScript; if (enumContainerSymbol) { if (enumContainerSymbol.kind !== enumDeclKind) { - if (isInitializedModule) { - this.semanticInfoChain.addDiagnosticFromAST(enumAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [enumContainerDecl.getDisplayName()]); - } + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(enumAST.identifier, enumContainerDecl.getDisplayName(), enumContainerSymbol.getDeclarations()[0].ast()); enumContainerSymbol = null; } else if (!this.checkThatExportsMatch(enumContainerDecl, enumContainerSymbol)) { enumContainerSymbol = null; @@ -51294,7 +52681,7 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(enumAST.identifier, enumContainerSymbol); this.semanticInfoChain.setSymbolForAST(enumAST, enumContainerSymbol); - if (!enumInstanceSymbol && isInitializedModule) { + if (!enumInstanceSymbol) { var variableSymbol = null; if (parentInstanceSymbol) { if (isExported) { @@ -51327,11 +52714,11 @@ var TypeScript; var augmentedDecl = null; for (var i = 0; i < siblingDecls.length; i++) { - if (siblingDecls[i] == enumContainerDecl) { + if (siblingDecls[i] === enumContainerDecl) { break; } - if ((siblingDecls[i].name == enumName) && (siblingDecls[i].kind & 68147712 /* SomeValue */)) { + if ((siblingDecls[i].name === enumName) && (siblingDecls[i].kind & 68147712 /* SomeValue */)) { augmentedDecl = siblingDecls[i]; break; } @@ -51371,20 +52758,6 @@ var TypeScript; } } - var moduleDeclarations = enumContainerSymbol.getDeclarations(); - - if (moduleDeclarations.length > 1 && enumAST.enumElements.nonSeparatorCount() > 0) { - var multipleEnums = TypeScript.ArrayUtilities.where(moduleDeclarations, function (d) { - return d.kind === 64 /* Enum */; - }).length > 1; - if (multipleEnums) { - var firstVariable = enumAST.enumElements.nonSeparatorAt(0); - if (!firstVariable.equalsValueClause) { - this.semanticInfoChain.addDiagnosticFromAST(firstVariable, TypeScript.DiagnosticCode.Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element, null); - } - } - } - if (createdNewSymbol && parent) { if (enumContainerDecl.flags & 1 /* Exported */) { parent.addEnclosedMemberType(enumContainerSymbol); @@ -51393,65 +52766,111 @@ var TypeScript; } } - this.bindEnumIndexerDeclsToPullSymbols(enumContainerDecl, enumContainerSymbol); - + if (createdNewSymbol) { + this.bindEnumIndexerDeclsToPullSymbols(enumContainerSymbol); + } var valueDecl = enumContainerDecl.getValueDecl(); if (valueDecl) { valueDecl.ensureSymbolIsBound(); } - - var otherDecls = this.findDeclsInContext(enumContainerDecl, enumContainerDecl.kind, true); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } }; - PullSymbolBinder.prototype.bindEnumIndexerDeclsToPullSymbols = function (enumContainerDecl, enumContainerSymbol) { - var indexSigDecl = enumContainerDecl.getChildDecls().filter(function (decl) { - return decl.kind == 4194304 /* IndexSignature */; - })[0]; - var indexParamDecl = indexSigDecl.getChildDecls()[0]; - - var syntheticIndexerParameterSymbol = new TypeScript.PullSymbol(indexParamDecl.name, 2048 /* Parameter */); + PullSymbolBinder.prototype.bindEnumIndexerDeclsToPullSymbols = function (enumContainerSymbol) { + var enumContainerInstanceTypeSymbol = enumContainerSymbol.getInstanceSymbol().type; + var syntheticIndexerParameterSymbol = new TypeScript.PullSymbol("x", 2048 /* Parameter */); syntheticIndexerParameterSymbol.type = this.semanticInfoChain.numberTypeSymbol; syntheticIndexerParameterSymbol.setResolved(); + syntheticIndexerParameterSymbol.setIsSynthesized(); var syntheticIndexerSignatureSymbol = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); syntheticIndexerSignatureSymbol.addParameter(syntheticIndexerParameterSymbol); syntheticIndexerSignatureSymbol.returnType = this.semanticInfoChain.stringTypeSymbol; syntheticIndexerSignatureSymbol.setResolved(); + syntheticIndexerSignatureSymbol.setIsSynthesized(); - var enumContainerInstanceTypeSymbol = enumContainerSymbol.getInstanceSymbol().type; enumContainerInstanceTypeSymbol.addIndexSignature(syntheticIndexerSignatureSymbol); + }; - indexSigDecl.setSignatureSymbol(syntheticIndexerSignatureSymbol); - indexParamDecl.setSymbol(syntheticIndexerParameterSymbol); + PullSymbolBinder.prototype.findExistingVariableSymbolForModuleValueDecl = function (decl) { + var isExported = TypeScript.hasFlag(decl.flags, 1 /* Exported */); + var modName = decl.name; + var parentInstanceSymbol = this.getParent(decl, true); + var parentDecl = decl.getParentDecl(); - syntheticIndexerSignatureSymbol.addDeclaration(indexSigDecl); - syntheticIndexerParameterSymbol.addDeclaration(indexParamDecl); + var variableSymbol = null; + + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + var isExportedOrHasTheSameParent = isExported || (parentDecl === variableSymbolParentDecl); + + var canReuseVariableSymbol = isExportedOrHasTheSameParent && this.checkThatExportsMatch(decl, variableSymbol, false); + + if (!canReuseVariableSymbol) { + variableSymbol = null; + } + } + } + } else if (!isExported) { + var siblingDecls = parentDecl.getChildDecls(); + + for (var i = 0; i < siblingDecls.length; i++) { + var sibling = siblingDecls[i]; + + var siblingIsSomeValue = TypeScript.hasFlag(sibling.kind, 68147712 /* SomeValue */); + var siblingIsFunctionOrHasImplictVarFlag = TypeScript.hasFlag(sibling.kind, 1032192 /* SomeFunction */) || TypeScript.hasFlag(sibling.flags, 118784 /* ImplicitVariable */); + + var isSiblingAnAugmentableVariable = sibling !== decl && sibling !== decl.getValueDecl() && sibling.name === modName && siblingIsSomeValue && siblingIsFunctionOrHasImplictVarFlag; + + if (isSiblingAnAugmentableVariable) { + if (sibling.hasSymbol()) { + variableSymbol = sibling.getSymbol(); + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + + break; + } + } + } + } + return variableSymbol; }; PullSymbolBinder.prototype.bindModuleDeclarationToPullSymbol = function (moduleContainerDecl) { var modName = moduleContainerDecl.name; var moduleContainerTypeSymbol = null; - var moduleInstanceSymbol = null; - var moduleInstanceTypeSymbol = null; - var moduleKind = moduleContainerDecl.kind; var parent = this.getParent(moduleContainerDecl); var parentInstanceSymbol = this.getParent(moduleContainerDecl, true); var parentDecl = moduleContainerDecl.getParentDecl(); var moduleNameAST = this.semanticInfoChain.getASTForDecl(moduleContainerDecl); - var moduleDeclAST = TypeScript.getEnclosingModuleDeclaration(moduleNameAST); + var moduleDeclAST = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(moduleNameAST); if (!moduleDeclAST) { - TypeScript.Debug.assert(moduleContainerDecl.kind === 32 /* DynamicModule */); + TypeScript.Debug.assert(moduleKind === 32 /* DynamicModule */); TypeScript.Debug.assert(moduleNameAST.kind() === 120 /* SourceUnit */); moduleDeclAST = moduleNameAST; @@ -51459,9 +52878,9 @@ var TypeScript; var isExported = TypeScript.hasFlag(moduleContainerDecl.flags, 1 /* Exported */); var searchKind = 164 /* SomeContainer */; - var isInitializedModule = (moduleContainerDecl.flags & 102400 /* SomeInitializedModule */) != 0; + var isInitializedModule = (moduleContainerDecl.flags & 102400 /* SomeInitializedModule */) !== 0; - if (parent && moduleKind == 32 /* DynamicModule */) { + if (parent && moduleKind === 32 /* DynamicModule */) { this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_must_be_defined_in_global_context, null); } @@ -51472,20 +52891,18 @@ var TypeScript; if (moduleContainerTypeSymbol) { if (moduleContainerTypeSymbol.kind !== moduleKind) { if (isInitializedModule) { - this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [moduleContainerDecl.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(moduleNameAST, moduleContainerDecl.getDisplayName(), moduleContainerTypeSymbol.getDeclarations()[0].ast()); } moduleContainerTypeSymbol = null; - } else if (moduleKind == 32 /* DynamicModule */) { + } else if (moduleKind === 32 /* DynamicModule */) { this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_be_reopened); } else if (!this.checkThatExportsMatch(moduleContainerDecl, moduleContainerTypeSymbol)) { moduleContainerTypeSymbol = null; } } - if (moduleContainerTypeSymbol) { - moduleInstanceSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); - } else { + if (!moduleContainerTypeSymbol) { moduleContainerTypeSymbol = new TypeScript.PullContainerSymbol(modName, moduleKind); createdNewSymbol = true; @@ -51500,74 +52917,7 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(moduleNameAST, moduleContainerTypeSymbol); this.semanticInfoChain.setSymbolForAST(moduleDeclAST, moduleContainerTypeSymbol); - if (!moduleInstanceSymbol && isInitializedModule) { - var variableSymbol = null; - if (parentInstanceSymbol) { - if (isExported) { - variableSymbol = parentInstanceSymbol.findMember(modName, false); - - if (!variableSymbol) { - variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); - } - } else { - variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); - - if (!variableSymbol) { - variableSymbol = parentInstanceSymbol.findMember(modName, false); - } - } - - if (variableSymbol) { - var declarations = variableSymbol.getDeclarations(); - - if (declarations.length) { - var variableSymbolParentDecl = declarations[0].getParentDecl(); - - if (parentDecl !== variableSymbolParentDecl) { - variableSymbol = null; - } - } - } - } else if (!isExported) { - var siblingDecls = parentDecl.getChildDecls(); - - for (var i = 0; i < siblingDecls.length; i++) { - var sibling = siblingDecls[i]; - if (sibling !== moduleContainerDecl && sibling.name === modName && TypeScript.hasFlag(sibling.kind, 68147712 /* SomeValue */)) { - if (sibling.hasSymbol()) { - variableSymbol = sibling.getSymbol(); - if (variableSymbol.isContainer()) { - variableSymbol = variableSymbol.getInstanceSymbol(); - } else if (variableSymbol && variableSymbol.isType()) { - variableSymbol = variableSymbol.getConstructorMethod(); - } - - break; - } - } - } - } - - if (variableSymbol) { - moduleInstanceSymbol = variableSymbol; - moduleInstanceTypeSymbol = variableSymbol.type; - } else { - moduleInstanceSymbol = new TypeScript.PullSymbol(modName, 512 /* Variable */); - } - - moduleContainerTypeSymbol.setInstanceSymbol(moduleInstanceSymbol); - - if (!moduleInstanceTypeSymbol) { - moduleInstanceTypeSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); - moduleInstanceSymbol.type = moduleInstanceTypeSymbol; - } - - moduleInstanceTypeSymbol.addDeclaration(moduleContainerDecl); - - if (!moduleInstanceTypeSymbol.getAssociatedContainerType()) { - moduleInstanceTypeSymbol.setAssociatedContainerType(moduleContainerTypeSymbol); - } - } + var currentModuleValueDecl = moduleContainerDecl.getValueDecl(); var moduleDeclarations = moduleContainerTypeSymbol.getDeclarations(); @@ -51581,24 +52931,29 @@ var TypeScript; } } - var valueDecl = moduleContainerDecl.getValueDecl(); + if (currentModuleValueDecl) { + currentModuleValueDecl.ensureSymbolIsBound(); - if (valueDecl) { - valueDecl.ensureSymbolIsBound(); - - if (!valueDecl.hasSymbol()) { - valueDecl.setSymbol(moduleInstanceSymbol); - if (!moduleInstanceSymbol.hasDeclaration(valueDecl)) { - moduleInstanceSymbol.addDeclaration(valueDecl); + var instanceSymbol = null; + var instanceTypeSymbol = null; + if (currentModuleValueDecl.hasSymbol()) { + instanceSymbol = currentModuleValueDecl.getSymbol(); + } else { + instanceSymbol = new TypeScript.PullSymbol(modName, 512 /* Variable */); + currentModuleValueDecl.setSymbol(instanceSymbol); + if (!instanceSymbol.hasDeclaration(currentModuleValueDecl)) { + instanceSymbol.addDeclaration(currentModuleValueDecl); } } - } - var otherDecls = this.findDeclsInContext(moduleContainerDecl, moduleContainerDecl.kind, true); + if (!instanceSymbol.type) { + instanceSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); + moduleContainerTypeSymbol.setInstanceSymbol(instanceSymbol); + + if (!instanceSymbol.type.getAssociatedContainerType()) { + instanceSymbol.type.setAssociatedContainerType(moduleContainerTypeSymbol); } } }; @@ -51621,7 +52976,7 @@ var TypeScript; } if (importSymbol) { - this.semanticInfoChain.addDiagnosticFromAST(importDeclAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [importDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(importDeclAST, importDeclaration.getDisplayName(), importSymbol.getDeclarations()[0].ast()); importSymbol = null; } @@ -51647,6 +53002,28 @@ var TypeScript; } }; + PullSymbolBinder.prototype.ensurePriorDeclarationsAreBound = function (container, currentDecl) { + if (!container) { + return; + } + + var parentDecls = container.getDeclarations(); + for (var i = 0; i < parentDecls.length; ++i) { + var parentDecl = parentDecls[i]; + var childDecls = parentDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl === currentDecl) { + return; + } + + if (childDecl.name === currentDecl.name) { + childDecl.ensureSymbolIsBound(); + } + } + } + }; + PullSymbolBinder.prototype.bindClassDeclarationToPullSymbol = function (classDecl) { var className = classDecl.name; var classSymbol = null; @@ -51657,19 +53034,20 @@ var TypeScript; var classAST = this.semanticInfoChain.getASTForDecl(classDecl); var parent = this.getParent(classDecl); + + this.ensurePriorDeclarationsAreBound(parent, classDecl); + var parentDecl = classDecl.getParentDecl(); var isExported = classDecl.flags & 1 /* Exported */; var isGeneric = false; - classSymbol = this.getExistingSymbol(classDecl, 58728539 /* SomeType */, parent); + classSymbol = this.getExistingSymbol(classDecl, 58728795 /* SomeType */, parent); if (classSymbol && classSymbol.kind === 16 /* Interface */) { - this.semanticInfoChain.addDiagnosticFromAST(classAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [classDecl.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(classAST.identifier, classDecl.getDisplayName(), classSymbol.getDeclarations()[0].ast()); classSymbol = null; } - var decls; - classSymbol = new TypeScript.PullTypeSymbol(className, 8 /* Class */); if (!parent) { @@ -51691,6 +53069,23 @@ var TypeScript; } } + var typeParameterDecls = classDecl.getTypeParameters(); + + for (var i = 0; i < typeParameterDecls.length; i++) { + var typeParameterSymbol = classSymbol.findTypeParameter(typeParameterDecls[i].name); + + if (typeParameterSymbol) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterSymbol.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameterSymbol.getName()]); + } + + typeParameterSymbol = new TypeScript.PullTypeParameterSymbol(typeParameterDecls[i].name); + + classSymbol.addTypeParameter(typeParameterSymbol); + typeParameterSymbol.addDeclaration(typeParameterDecls[i]); + typeParameterDecls[i].setSymbol(typeParameterSymbol); + } + constructorSymbol = classSymbol.getConstructorMethod(); constructorTypeSymbol = constructorSymbol ? constructorSymbol.type : null; @@ -51726,32 +53121,13 @@ var TypeScript; constructorTypeSymbol.setAssociatedContainerType(classSymbol); - var typeParameters = classDecl.getTypeParameters(); - var typeParameter; - - for (var i = 0; i < typeParameters.length; i++) { - typeParameter = classSymbol.findTypeParameter(typeParameters[i].name); - - if (typeParameter != null) { - var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); - this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); - } - - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, false); - - classSymbol.addTypeParameter(typeParameter); - constructorTypeSymbol.addConstructorTypeParameter(typeParameter); - typeParameter.addDeclaration(typeParameters[i]); - typeParameters[i].setSymbol(typeParameter); - } - var valueDecl = classDecl.getValueDecl(); if (valueDecl) { valueDecl.ensureSymbolIsBound(); } - this.bindStaticPrototypePropertyOfClass(classSymbol, constructorTypeSymbol); + this.bindStaticPrototypePropertyOfClass(classAST, classSymbol, constructorTypeSymbol); }; PullSymbolBinder.prototype.bindInterfaceDeclarationToPullSymbol = function (interfaceDecl) { @@ -51764,11 +53140,11 @@ var TypeScript; var acceptableSharedKind = 16 /* Interface */; - interfaceSymbol = this.getExistingSymbol(interfaceDecl, 58728539 /* SomeType */, parent); + interfaceSymbol = this.getExistingSymbol(interfaceDecl, 58728795 /* SomeType */, parent); if (interfaceSymbol) { if (!(interfaceSymbol.kind & acceptableSharedKind)) { - this.semanticInfoChain.addDiagnosticFromAST(interfaceAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [interfaceDecl.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(interfaceAST.identifier, interfaceDecl.getDisplayName(), interfaceSymbol.getDeclarations()[0].ast()); interfaceSymbol = null; } else if (!this.checkThatExportsMatch(interfaceDecl, interfaceSymbol)) { interfaceSymbol = null; @@ -51805,7 +53181,7 @@ var TypeScript; typeParameter = interfaceSymbol.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, false); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); interfaceSymbol.addTypeParameter(typeParameter); } else { @@ -51826,14 +53202,6 @@ var TypeScript; typeParameter.addDeclaration(typeParameters[i]); typeParameters[i].setSymbol(typeParameter); } - - var otherDecls = this.findDeclsInContext(interfaceDecl, interfaceDecl.kind, true); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } }; PullSymbolBinder.prototype.bindObjectTypeDeclarationToPullSymbol = function (objectDecl) { @@ -51874,9 +53242,7 @@ var TypeScript; signature.addDeclaration(constructorTypeDeclaration); constructorTypeDeclaration.setSignatureSymbol(signature); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(funcDecl.parameterList), constructorTypeSymbol, signature); - - constructorTypeSymbol.addConstructSignature(signature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), constructorTypeSymbol, signature); var typeParameters = constructorTypeDeclaration.getTypeParameters(); var typeParameter; @@ -51885,9 +53251,9 @@ var TypeScript; typeParameter = constructorTypeSymbol.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, false); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); - constructorTypeSymbol.addConstructorTypeParameter(typeParameter); + signature.addTypeParameter(typeParameter); } else { var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); @@ -51896,12 +53262,15 @@ var TypeScript; typeParameter.addDeclaration(typeParameters[i]); typeParameters[i].setSymbol(typeParameter); } + + constructorTypeSymbol.appendConstructSignature(signature); }; PullSymbolBinder.prototype.bindVariableDeclarationToPullSymbol = function (variableDeclaration) { var declFlags = variableDeclaration.flags; var declKind = variableDeclaration.kind; var varDeclAST = this.semanticInfoChain.getASTForDecl(variableDeclaration); + var nameAST = varDeclAST.kind() === 131 /* ClassDeclaration */ ? varDeclAST.identifier : varDeclAST.kind() === 225 /* VariableDeclarator */ ? varDeclAST.propertyName : varDeclAST.kind() === 132 /* EnumDeclaration */ ? varDeclAST.identifier : varDeclAST; var isExported = (declFlags & 1 /* Exported */) !== 0; @@ -51916,12 +53285,15 @@ var TypeScript; var parentDecl = variableDeclaration.getParentDecl(); var isImplicit = (declFlags & 118784 /* ImplicitVariable */) !== 0; - var isModuleValue = (declFlags & (32768 /* InitializedModule */)) != 0; - var isEnumValue = (declFlags & 4096 /* Enum */) != 0; - var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) != 0; - + var isModuleValue = (declFlags & (32768 /* InitializedModule */)) !== 0; + var isEnumValue = (declFlags & 4096 /* Enum */) !== 0; + var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) !== 0; variableSymbol = this.getExistingSymbol(variableDeclaration, 68147712 /* SomeValue */, parent); + if (!variableSymbol && isModuleValue) { + variableSymbol = this.findExistingVariableSymbolForModuleValueDecl(variableDeclaration.getContainerDecl()); + } + if (variableSymbol && !variableSymbol.isType()) { parentHadSymbol = true; } @@ -51937,28 +53309,29 @@ var TypeScript; var prevIsClassConstructorVariable = variableSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */); var prevIsModuleValue = variableSymbol.allDeclsHaveFlag(32768 /* InitializedModule */); var prevIsImplicit = variableSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */); - var prevIsFunction = prevKind == 16384 /* Function */; + var prevIsFunction = TypeScript.ArrayUtilities.any(variableSymbol.getDeclarations(), function (decl) { + return decl.kind === 16384 /* Function */; + }); var prevIsAmbient = variableSymbol.allDeclsHaveFlag(8 /* Ambient */); - var isAmbientOrPrevIsAmbient = prevIsAmbient || (variableDeclaration.flags & 8 /* Ambient */) != 0; + var isAmbientOrPrevIsAmbient = prevIsAmbient || (variableDeclaration.flags & 8 /* Ambient */) !== 0; var prevDecl = variableSymbol.getDeclarations()[0]; var prevParentDecl = prevDecl.getParentDecl(); - var bothAreGlobal = parentDecl && (parentDecl.kind == 1 /* Script */) && (prevParentDecl.kind == 1 /* Script */); - var shareParent = bothAreGlobal || prevDecl.getParentDecl() == variableDeclaration.getParentDecl(); - var prevIsParam = shareParent && prevKind == 2048 /* Parameter */ && declKind == 512 /* Variable */; + var bothAreGlobal = parentDecl && (parentDecl.kind === 1 /* Script */) && (prevParentDecl.kind === 1 /* Script */); + var shareParent = bothAreGlobal || prevDecl.getParentDecl() === variableDeclaration.getParentDecl(); + var prevIsParam = shareParent && prevKind === 2048 /* Parameter */ && declKind == 512 /* Variable */; var acceptableRedeclaration = prevIsParam || (isImplicit && ((!isEnumValue && !isClassConstructorVariable && prevIsFunction) || ((isModuleValue || isEnumValue) && (prevIsModuleValue || prevIsEnum)) || (isClassConstructorVariable && prevIsModuleValue && isAmbientOrPrevIsAmbient) || (isModuleValue && prevIsClassConstructorVariable))); if (acceptableRedeclaration && (prevIsClassConstructorVariable || prevIsFunction) && !isAmbientOrPrevIsAmbient) { - if (prevDecl.fileName() != variableDeclaration.fileName()) { - this.semanticInfoChain.addDiagnostic(TypeScript.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2, [declName, declName, prevDecl.fileName()])); + if (prevDecl.fileName() !== variableDeclaration.fileName()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2, [declName, declName, prevDecl.fileName()])); variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); } } if (!acceptableRedeclaration || prevIsParam) { - if (!prevIsParam && (isImplicit || prevIsImplicit || (prevKind & 1032192 /* SomeFunction */) !== 0) || !shareParent) { - var diagnostic = TypeScript.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Duplicate_identifier_0, [variableDeclaration.getDisplayName()]); - this.semanticInfoChain.addDiagnostic(diagnostic); + if (!prevIsParam && (isImplicit || prevIsImplicit || TypeScript.hasFlag(prevKind, 1032192 /* SomeFunction */)) || !shareParent) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(nameAST, variableDeclaration.getDisplayName(), variableSymbol.getDeclarations()[0].ast()); variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); } else { this.checkThatExportsMatch(variableDeclaration, variableSymbol); @@ -51983,7 +53356,7 @@ var TypeScript; variableSymbol.addDeclaration(variableDeclaration); variableDeclaration.setSymbol(variableSymbol); - this.semanticInfoChain.setSymbolForAST(varDeclAST.propertyName, variableSymbol); + this.semanticInfoChain.setSymbolForAST(nameAST, variableSymbol); this.semanticInfoChain.setSymbolForAST(varDeclAST, variableSymbol); } else if (!parentHadSymbol) { if (isClassConstructorVariable) { @@ -52001,22 +53374,10 @@ var TypeScript; } if (!classTypeSymbol) { - var parentDecl = variableDeclaration.getParentDecl(); - - if (parentDecl) { - var childDecls = parentDecl.searchChildDecls(declName, 58728539 /* SomeType */); - - if (childDecls.length) { - for (var i = 0; i < childDecls.length; i++) { - if (childDecls[i].getValueDecl() === variableDeclaration) { - classTypeSymbol = childDecls[i].getSymbol(); - } - } - } - } - + var containerDecl = variableDeclaration.getContainerDecl(); + classTypeSymbol = containerDecl.getSymbol(); if (!classTypeSymbol) { - classTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 58728539 /* SomeType */, variableDeclaration); + classTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 58728795 /* SomeType */, variableDeclaration); } } @@ -52060,20 +53421,8 @@ var TypeScript; } if (!moduleContainerTypeSymbol) { - var parentDecl = variableDeclaration.getParentDecl(); - - if (parentDecl) { - var searchKind = (declFlags & (32768 /* InitializedModule */ | 65536 /* InitializedDynamicModule */)) ? 164 /* SomeContainer */ : 64 /* Enum */; - var childDecls = parentDecl.searchChildDecls(declName, searchKind); - - if (childDecls.length) { - for (var i = 0; i < childDecls.length; i++) { - if (childDecls[i].getValueDecl() === variableDeclaration) { - moduleContainerTypeSymbol = childDecls[i].getSymbol(); - } - } - } - } + var containerDecl = variableDeclaration.getContainerDecl(); + moduleContainerTypeSymbol = containerDecl.getSymbol(); if (!moduleContainerTypeSymbol) { moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 164 /* SomeContainer */, variableDeclaration); @@ -52089,6 +53438,10 @@ var TypeScript; if (moduleContainerTypeSymbol) { variableSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + variableSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } if (!variableSymbol.hasDeclaration(variableDeclaration)) { variableSymbol.addDeclaration(variableDeclaration); @@ -52105,6 +53458,11 @@ var TypeScript; variableDeclaration.setSymbol(variableSymbol); } + var containerDecl = variableDeclaration.getContainerDecl(); + if (variableSymbol && variableSymbol.type && containerDecl && !variableSymbol.type.hasDeclaration(containerDecl)) { + variableSymbol.type.addDeclaration(containerDecl); + } + if (parent && !parentHadSymbol) { if (declFlags & 1 /* Exported */) { parent.addMember(variableSymbol); @@ -52112,14 +53470,6 @@ var TypeScript; parent.addEnclosedNonMember(variableSymbol); } } - - var otherDecls = this.findDeclsInContext(variableDeclaration, variableDeclaration.kind, false); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } }; PullSymbolBinder.prototype.bindCatchVariableToPullSymbol = function (variableDeclaration) { @@ -52153,7 +53503,7 @@ var TypeScript; var propertySymbol = parent.findMember(declName, false); if (propertySymbol) { - this.semanticInfoChain.addDiagnostic(TypeScript.diagnosticFromDecl(propertyDeclaration, TypeScript.DiagnosticCode.Duplicate_identifier_0, [propertyDeclaration.getDisplayName()])); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(propDeclAST.propertyName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); } if (propertySymbol) { @@ -52208,7 +53558,7 @@ var TypeScript; propertySymbol = parent.findMember(declName, false); if (propertySymbol) { - this.semanticInfoChain.addDiagnostic(TypeScript.diagnosticFromDecl(propertyDeclaration, TypeScript.DiagnosticCode.Duplicate_identifier_0, [propertyDeclaration.getDisplayName()])); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(astName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); } if (propertySymbol) { @@ -52253,28 +53603,33 @@ var TypeScript; parameterSymbol.isVarArg = true; } - if (decl.flags & 128 /* Optional */) { - parameterSymbol.isOptional = true; - } - if (params[id.valueText()]) { this.semanticInfoChain.addDiagnosticFromAST(argDecl, TypeScript.DiagnosticCode.Duplicate_identifier_0, [id.text()]); } else { params[id.valueText()] = true; } + if (decl) { + var isParameterOptional = false; + if (isProperty) { decl.ensureSymbolIsBound(); var valDecl = decl.getValueDecl(); if (valDecl) { + isParameterOptional = TypeScript.hasFlag(valDecl.flags, 128 /* Optional */); + valDecl.setSymbol(parameterSymbol); parameterSymbol.addDeclaration(valDecl); } } else { + isParameterOptional = TypeScript.hasFlag(decl.flags, 128 /* Optional */); + parameterSymbol.addDeclaration(decl); decl.setSymbol(parameterSymbol); } + + parameterSymbol.isOptional = isParameterOptional; } signatureSymbol.addParameter(parameterSymbol, parameterSymbol.isOptional); @@ -52298,6 +53653,7 @@ var TypeScript; var isSignature = (declFlags & 2048 /* Signature */) !== 0; var parent = this.getParent(functionDeclaration, true); + var parentDecl = functionDeclaration.getParentDecl(); var parentHadSymbol = false; @@ -52307,11 +53663,21 @@ var TypeScript; functionSymbol = this.getExistingSymbol(functionDeclaration, 68147712 /* SomeValue */, parent); if (functionSymbol) { - var previousIsAmbient = functionSymbol.allDeclsHaveFlag(8 /* Ambient */); - var isAmbientOrPreviousIsAmbient = previousIsAmbient || functionDeclaration.flags & 8 /* Ambient */; - var acceptableRedeclaration = functionSymbol.kind === 16384 /* Function */ && (isSignature || functionSymbol.allDeclsHaveFlag(2048 /* Signature */)) || functionSymbol.allDeclsHaveFlag(32768 /* InitializedModule */) && isAmbientOrPreviousIsAmbient; + var acceptableRedeclaration; + + if (functionSymbol.kind === 16384 /* Function */) { + acceptableRedeclaration = isSignature || functionSymbol.allDeclsHaveFlag(2048 /* Signature */); + } else { + var isCurrentDeclAmbient = TypeScript.hasFlag(functionDeclaration.flags, 8 /* Ambient */); + acceptableRedeclaration = TypeScript.ArrayUtilities.all(functionSymbol.getDeclarations(), function (decl) { + var isInitializedModuleOrAmbientDecl = TypeScript.hasFlag(decl.flags, 32768 /* InitializedModule */) && (isCurrentDeclAmbient || TypeScript.hasFlag(decl.flags, 8 /* Ambient */)); + var isSignature = TypeScript.hasFlag(decl.flags, 2048 /* Signature */); + return isInitializedModuleOrAmbientDecl || isSignature; + }); + } + if (!acceptableRedeclaration) { - this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [functionDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.identifier, functionDeclaration.getDisplayName(), functionSymbol.getDeclarations()[0].ast()); functionSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(funcName); } } @@ -52346,7 +53712,7 @@ var TypeScript; } } - var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); signature.addDeclaration(functionDeclaration); functionDeclaration.setSignatureSymbol(signature); @@ -52356,7 +53722,7 @@ var TypeScript; } var funcDecl = this.semanticInfoChain.getASTForDecl(functionDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList), functionTypeSymbol, signature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), functionTypeSymbol, signature); var typeParameters = functionDeclaration.getTypeParameters(); var typeParameter; @@ -52365,7 +53731,7 @@ var TypeScript; typeParameter = signature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); signature.addTypeParameter(typeParameter); } else { @@ -52377,15 +53743,7 @@ var TypeScript; typeParameters[i].setSymbol(typeParameter); } - functionTypeSymbol.addCallSignature(signature); - - var otherDecls = this.findDeclsInContext(functionDeclaration, functionDeclaration.kind, false); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } + functionTypeSymbol.appendCallSignature(signature); }; PullSymbolBinder.prototype.bindFunctionExpressionToPullSymbol = function (functionExpressionDeclaration) { @@ -52393,10 +53751,10 @@ var TypeScript; var declFlags = functionExpressionDeclaration.flags; var ast = this.semanticInfoChain.getASTForDecl(functionExpressionDeclaration); - var parameters = ast.kind() === 219 /* SimpleArrowFunctionExpression */ ? TypeScript.Parameters.fromIdentifier(ast.identifier) : TypeScript.Parameters.fromParameterList(TypeScript.getParameterList(ast)); + var parameters = ast.kind() === 219 /* SimpleArrowFunctionExpression */ ? TypeScript.ASTHelpers.parametersFromIdentifier(ast.identifier) : TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(ast)); var funcExpAST = ast; - var functionName = declKind == 131072 /* FunctionExpression */ ? functionExpressionDeclaration.getFunctionExpressionName() : functionExpressionDeclaration.name; + var functionName = declKind === 131072 /* FunctionExpression */ ? functionExpressionDeclaration.getFunctionExpressionName() : functionExpressionDeclaration.name; var functionSymbol = new TypeScript.PullSymbol(functionName, declKind); var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); functionTypeSymbol.setFunctionSymbol(functionSymbol); @@ -52414,7 +53772,7 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(funcExpAST, functionSymbol); - var signature = new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, true); if (parameters.lastParameterIsRest()) { signature.hasVarArgs = true; @@ -52427,7 +53785,7 @@ var TypeScript; typeParameter = signature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); signature.addTypeParameter(typeParameter); } else { @@ -52444,7 +53802,7 @@ var TypeScript; this.bindParameterSymbols(funcExpAST, parameters, functionTypeSymbol, signature); - functionTypeSymbol.addCallSignature(signature); + functionTypeSymbol.appendCallSignature(signature); }; PullSymbolBinder.prototype.bindFunctionTypeDeclarationToPullSymbol = function (functionTypeDeclaration) { @@ -52459,7 +53817,7 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(funcTypeAST, functionTypeSymbol); var isSignature = (declFlags & 2048 /* Signature */) !== 0; - var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); if (TypeScript.lastParameterIsRest(funcTypeAST.parameterList)) { signature.hasVarArgs = true; @@ -52472,7 +53830,7 @@ var TypeScript; typeParameter = signature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); signature.addTypeParameter(typeParameter); } else { @@ -52487,9 +53845,9 @@ var TypeScript; signature.addDeclaration(functionTypeDeclaration); functionTypeDeclaration.setSignatureSymbol(signature); - this.bindParameterSymbols(funcTypeAST, TypeScript.Parameters.fromParameterList(funcTypeAST.parameterList), functionTypeSymbol, signature); + this.bindParameterSymbols(funcTypeAST, TypeScript.ASTHelpers.parametersFromParameterList(funcTypeAST.parameterList), functionTypeSymbol, signature); - functionTypeSymbol.addCallSignature(signature); + functionTypeSymbol.appendCallSignature(signature); }; PullSymbolBinder.prototype.bindMethodDeclarationToPullSymbol = function (methodDeclaration) { @@ -52518,7 +53876,7 @@ var TypeScript; methodSymbol = parent.findMember(methodName, false); if (methodSymbol && (methodSymbol.kind !== 65536 /* Method */ || (!isSignature && !methodSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { - this.semanticInfoChain.addDiagnosticFromAST(methodAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [methodDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(methodAST, methodDeclaration.getDisplayName(), methodSymbol.getDeclarations()[0].ast()); methodSymbol = null; } @@ -52558,9 +53916,9 @@ var TypeScript; var sigKind = 1048576 /* CallSignature */; - var signature = isSignature ? new TypeScript.PullSignatureSymbol(sigKind) : new TypeScript.PullDefinitionSignatureSymbol(sigKind); + var signature = new TypeScript.PullSignatureSymbol(sigKind, !isSignature); - var parameterList = TypeScript.getParameterList(methodAST); + var parameterList = TypeScript.ASTHelpers.getParameterList(methodAST); if (TypeScript.lastParameterIsRest(parameterList)) { signature.hasVarArgs = true; } @@ -52577,7 +53935,7 @@ var TypeScript; typeParameter = signature.findTypeParameter(typeParameterName); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName); signature.addTypeParameter(typeParameter); } else { this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); @@ -52591,29 +53949,22 @@ var TypeScript; methodDeclaration.setSignatureSymbol(signature); var funcDecl = this.semanticInfoChain.getASTForDecl(methodDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(TypeScript.getParameterList(funcDecl)), methodTypeSymbol, signature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), methodTypeSymbol, signature); - methodTypeSymbol.addCallSignature(signature); - - var otherDecls = this.findDeclsInContext(methodDeclaration, methodDeclaration.kind, false); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(signature, methodTypeSymbol.getOwnCallSignatures()); + methodTypeSymbol.insertCallSignatureAtIndex(signature, signatureIndex); }; - PullSymbolBinder.prototype.bindStaticPrototypePropertyOfClass = function (classTypeSymbol, constructorTypeSymbol) { + PullSymbolBinder.prototype.bindStaticPrototypePropertyOfClass = function (classAST, classTypeSymbol, constructorTypeSymbol) { var prototypeStr = "prototype"; var prototypeSymbol = constructorTypeSymbol.findMember(prototypeStr, false); if (prototypeSymbol && !prototypeSymbol.getIsSynthesized()) { - this.semanticInfoChain.addDiagnostic(TypeScript.diagnosticFromDecl(prototypeSymbol.getDeclarations()[0], TypeScript.DiagnosticCode.Duplicate_identifier_0, [prototypeSymbol.getDisplayName()])); + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(prototypeSymbol.getDeclarations()[0], TypeScript.DiagnosticCode.Duplicate_identifier_0, [prototypeSymbol.getDisplayName()])); } if (!prototypeSymbol || !prototypeSymbol.getIsSynthesized()) { - var prototypeDecl = new TypeScript.PullSynthesizedDecl(prototypeStr, prototypeStr, 4096 /* Property */, 4 /* Public */ | 16 /* Static */, constructorTypeSymbol.getDeclarations()[0], classTypeSymbol.getDeclarations()[0].getSpan(), this.semanticInfoChain); + var prototypeDecl = new TypeScript.PullSynthesizedDecl(prototypeStr, prototypeStr, 4096 /* Property */, 4 /* Public */ | 16 /* Static */, constructorTypeSymbol.getDeclarations()[0], this.semanticInfoChain); prototypeSymbol = new TypeScript.PullSymbol(prototypeStr, 4096 /* Property */); prototypeSymbol.setIsSynthesized(); @@ -52679,36 +54030,20 @@ var TypeScript; constructorSymbol.setIsSynthesized(false); this.semanticInfoChain.setSymbolForAST(constructorAST, constructorSymbol); - var constructSignature = isSignature ? new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */) : new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */); - + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */, !isSignature); constructSignature.returnType = parent; + constructSignature.addTypeParametersFromReturnType(); constructSignature.addDeclaration(constructorDeclaration); constructorDeclaration.setSignatureSymbol(constructSignature); - this.bindParameterSymbols(constructorAST, TypeScript.Parameters.fromParameterList(constructorAST.parameterList), constructorTypeSymbol, constructSignature); + this.bindParameterSymbols(constructorAST, TypeScript.ASTHelpers.parametersFromParameterList(constructorAST.callSignature.parameterList), constructorTypeSymbol, constructSignature); - var typeParameters = constructorTypeSymbol.getTypeParameters(); - - for (var i = 0; i < typeParameters.length; i++) { - constructSignature.addTypeParameter(typeParameters[i]); - } - - if (TypeScript.lastParameterIsRest(constructorAST.parameterList)) { + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { constructSignature.hasVarArgs = true; } - constructorTypeSymbol.addConstructSignature(constructSignature); - - var otherDecls = this.findDeclsInContext(constructorDeclaration, constructorDeclaration.kind, false); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } - - this.bindStaticPrototypePropertyOfClass(parent, constructorTypeSymbol); + constructorTypeSymbol.appendConstructSignature(constructSignature); }; PullSymbolBinder.prototype.bindConstructSignatureDeclarationToPullSymbol = function (constructSignatureDeclaration) { @@ -52728,7 +54063,7 @@ var TypeScript; typeParameter = constructSignature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); constructSignature.addTypeParameter(typeParameter); } else { @@ -52744,11 +54079,12 @@ var TypeScript; constructSignatureDeclaration.setSignatureSymbol(constructSignature); var funcDecl = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(TypeScript.getParameterList(funcDecl)), null, constructSignature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), null, constructSignature); this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration), constructSignature); - parent.addConstructSignature(constructSignature); + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(constructSignature, parent.getOwnConstructSignatures()); + parent.insertConstructSignatureAtIndex(constructSignature, signatureIndex); }; PullSymbolBinder.prototype.bindCallSignatureDeclarationToPullSymbol = function (callSignatureDeclaration) { @@ -52768,7 +54104,7 @@ var TypeScript; typeParameter = callSignature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); callSignature.addTypeParameter(typeParameter); } else { @@ -52784,11 +54120,12 @@ var TypeScript; callSignatureDeclaration.setSignatureSymbol(callSignature); var funcDecl = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(funcDecl.parameterList), null, callSignature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), null, callSignature); this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(callSignatureDeclaration), callSignature); - parent.addCallSignature(callSignature); + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(callSignature, parent.getOwnCallSignatures()); + parent.insertCallSignatureAtIndex(callSignature, signatureIndex); }; PullSymbolBinder.prototype.bindIndexSignatureDeclarationToPullSymbol = function (indexSignatureDeclaration) { @@ -52798,7 +54135,7 @@ var TypeScript; indexSignatureDeclaration.setSignatureSymbol(indexSignature); var funcDecl = this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameter(funcDecl.parameter), null, indexSignature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter), null, indexSignature); this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration), indexSignature); @@ -52838,7 +54175,7 @@ var TypeScript; if (accessorSymbol) { if (!accessorSymbol.isAccessor()) { - this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [getAccessorDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, getAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); accessorSymbol = null; } else { getterSymbol = accessorSymbol.getGetter(); @@ -52885,14 +54222,14 @@ var TypeScript; parent.addMember(accessorSymbol); } - var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); signature.addDeclaration(getAccessorDeclaration); getAccessorDeclaration.setSignatureSymbol(signature); - this.bindParameterSymbols(funcDeclAST, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), getterTypeSymbol, signature); + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), getterTypeSymbol, signature); - getterTypeSymbol.addCallSignature(signature); + getterTypeSymbol.appendCallSignature(signature); }; PullSymbolBinder.prototype.bindSetAccessorDeclarationToPullSymbol = function (setAccessorDeclaration) { @@ -52926,7 +54263,7 @@ var TypeScript; if (accessorSymbol) { if (!accessorSymbol.isAccessor()) { - this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [setAccessorDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, setAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); accessorSymbol = null; } else { setterSymbol = accessorSymbol.getSetter(); @@ -52973,25 +54310,63 @@ var TypeScript; parent.addMember(accessorSymbol); } - var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); signature.addDeclaration(setAccessorDeclaration); setAccessorDeclaration.setSignatureSymbol(signature); - this.bindParameterSymbols(funcDeclAST, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), setterTypeSymbol, signature); + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), setterTypeSymbol, signature); - setterTypeSymbol.addCallSignature(signature); + setterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.getDeclsToBind = function (decl) { + var decls; + switch (decl.kind) { + case 64 /* Enum */: + case 32 /* DynamicModule */: + case 4 /* Container */: + case 16 /* Interface */: + decls = this.findDeclsInContext(decl, decl.kind, true); + break; + + case 512 /* Variable */: + case 16384 /* Function */: + case 65536 /* Method */: + case 32768 /* ConstructorMethod */: + decls = this.findDeclsInContext(decl, decl.kind, false); + break; + + default: + decls = [decl]; + } + TypeScript.Debug.assert(decls && decls.length > 0); + TypeScript.Debug.assert(TypeScript.ArrayUtilities.contains(decls, decl)); + return decls; + }; + + PullSymbolBinder.prototype.shouldBindDeclaration = function (decl) { + return !decl.hasBeenBound() && this.declsBeingBound.indexOf(decl.declID) < 0; }; PullSymbolBinder.prototype.bindDeclToPullSymbol = function (decl) { - if (decl.hasBeenBound()) { - return; + if (this.shouldBindDeclaration(decl)) { + this.bindAllDeclsToPullSymbol(decl); } + }; - if (this.declsBeingBound.indexOf(decl.declID) >= 0) { - return; + PullSymbolBinder.prototype.bindAllDeclsToPullSymbol = function (askedDecl) { + var allDecls = this.getDeclsToBind(askedDecl); + for (var i = 0; i < allDecls.length; i++) { + var decl = allDecls[i]; + + if (this.shouldBindDeclaration(decl)) { + this.bindSingleDeclToPullSymbol(decl); + } } + }; + PullSymbolBinder.prototype.bindSingleDeclToPullSymbol = function (decl) { this.declsBeingBound.push(decl.declID); switch (decl.kind) { @@ -53110,6 +54485,25 @@ var TypeScript; var TypeScript; (function (TypeScript) { (function (PullHelpers) { + function diagnosticFromDecl(decl, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + var ast = decl.ast(); + return decl.semanticInfoChain.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations); + } + PullHelpers.diagnosticFromDecl = diagnosticFromDecl; + + function resolveDeclaredSymbolToUseType(symbol) { + if (symbol.isSignature()) { + if (!symbol.returnType) { + symbol._resolveDeclaredSymbol(); + } + } else if (!symbol.type) { + symbol._resolveDeclaredSymbol(); + } + } + PullHelpers.resolveDeclaredSymbolToUseType = resolveDeclaredSymbolToUseType; + function getSignatureForFuncDecl(functionDecl) { var funcDecl = functionDecl.ast(); var funcSymbol = functionDecl.getSymbol(); @@ -53180,7 +54574,7 @@ var TypeScript; PullHelpers.symbolIsEnum = symbolIsEnum; function symbolIsModule(symbol) { - return symbol && (symbol.kind == 4 /* Container */ || isOneDeclarationOfKind(symbol, 4 /* Container */)); + return symbol && (symbol.kind === 4 /* Container */ || isOneDeclarationOfKind(symbol, 4 /* Container */)); } PullHelpers.symbolIsModule = symbolIsModule; @@ -53209,7 +54603,7 @@ var TypeScript; b = b.referencedTypeSymbol; } - return a == b; + return a === b; } PullHelpers.typeSymbolsAreIdentical = typeSymbolsAreIdentical; @@ -53217,7 +54611,7 @@ var TypeScript; var rootType = type.getRootSymbol(); while (true) { - if (type == rootType) { + if (type === rootType) { return type; } @@ -53235,7 +54629,7 @@ var TypeScript; return true; } - if (containerKind == 33554432 /* ConstructorType */ && !symbol.anyDeclHasFlag(16 /* Static */)) { + if (containerKind === 33554432 /* ConstructorType */ && !symbol.anyDeclHasFlag(16 /* Static */ | 1 /* Exported */)) { return true; } } @@ -53243,9 +54637,300 @@ var TypeScript; return false; } PullHelpers.isSymbolLocal = isSymbolLocal; + + function isExportedSymbolInClodule(symbol) { + var container = symbol.getContainer(); + return container && container.kind === 33554432 /* ConstructorType */ && symbolIsModule(container) && symbol.anyDeclHasFlag(1 /* Exported */); + } + PullHelpers.isExportedSymbolInClodule = isExportedSymbolInClodule; + + + + function walkSignatureSymbol(signatureSymbol, walker) { + var continueWalk = true; + var parameters = signatureSymbol.parameters; + if (parameters) { + for (var i = 0; continueWalk && i < parameters.length; i++) { + continueWalk = walker.signatureParameterWalk(parameters[i]); + } + } + + if (continueWalk) { + continueWalk = walker.signatureReturnTypeWalk(signatureSymbol.returnType); + } + + return continueWalk; + } + + function walkPullTypeSymbolStructure(typeSymbol, walker) { + var continueWalk = true; + + var members = typeSymbol.getMembers(); + for (var i = 0; continueWalk && i < members.length; i++) { + continueWalk = walker.memberSymbolWalk(members[i]); + } + + if (continueWalk) { + var callSigantures = typeSymbol.getCallSignatures(); + for (var i = 0; continueWalk && i < callSigantures.length; i++) { + continueWalk = walker.callSignatureWalk(callSigantures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(callSigantures[i], walker); + } + } + } + + if (continueWalk) { + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; continueWalk && i < constructSignatures.length; i++) { + continueWalk = walker.constructSignatureWalk(constructSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(constructSignatures[i], walker); + } + } + } + + if (continueWalk) { + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; continueWalk && i < indexSignatures.length; i++) { + continueWalk = walker.indexSignatureWalk(indexSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(indexSignatures[i], walker); + } + } + } + } + PullHelpers.walkPullTypeSymbolStructure = walkPullTypeSymbolStructure; + + var OtherPullDeclsWalker = (function () { + function OtherPullDeclsWalker() { + this.currentlyWalkingOtherDecls = []; + } + OtherPullDeclsWalker.prototype.walkOtherPullDecls = function (currentDecl, otherDecls, callBack) { + if (otherDecls) { + var isAlreadyWalkingOtherDecl = TypeScript.ArrayUtilities.any(this.currentlyWalkingOtherDecls, function (inWalkingOtherDecl) { + return TypeScript.ArrayUtilities.contains(otherDecls, inWalkingOtherDecl); + }); + + if (!isAlreadyWalkingOtherDecl) { + this.currentlyWalkingOtherDecls.push(currentDecl); + for (var i = 0; i < otherDecls.length; i++) { + if (otherDecls[i] !== currentDecl) { + callBack(otherDecls[i]); + } + } + var currentlyWalkingOtherDeclsDecl = this.currentlyWalkingOtherDecls.pop(); + TypeScript.Debug.assert(currentlyWalkingOtherDeclsDecl == currentDecl); + } + } + }; + return OtherPullDeclsWalker; + })(); + PullHelpers.OtherPullDeclsWalker = OtherPullDeclsWalker; })(TypeScript.PullHelpers || (TypeScript.PullHelpers = {})); var PullHelpers = TypeScript.PullHelpers; })(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var WrapsTypeParameterCache = (function () { + function WrapsTypeParameterCache() { + this._wrapsTypeParameterCache = TypeScript.BitVector.getBitVector(true); + } + WrapsTypeParameterCache.prototype.getWrapsTypeParameter = function (typeParameterArgumentMap) { + var mapHasTypeParameterNotCached = false; + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + var cachedValue = this._wrapsTypeParameterCache.valueAt(typeParameterID); + if (cachedValue) { + return typeParameterID; + } + mapHasTypeParameterNotCached = mapHasTypeParameterNotCached || cachedValue === undefined; + } + } + + if (!mapHasTypeParameterNotCached) { + return 0; + } + + return undefined; + }; + + WrapsTypeParameterCache.prototype.setWrapsTypeParameter = function (typeParameterArgumentMap, wrappingTypeParameterID) { + if (wrappingTypeParameterID) { + this._wrapsTypeParameterCache.setValueAt(wrappingTypeParameterID, true); + } else { + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + this._wrapsTypeParameterCache.setValueAt(typeParameterID, false); + } + } + } + }; + return WrapsTypeParameterCache; + })(); + TypeScript.WrapsTypeParameterCache = WrapsTypeParameterCache; + + (function (PullInstantiationHelpers) { + var MutableTypeArgumentMap = (function () { + function MutableTypeArgumentMap(typeParameterArgumentMap) { + this.typeParameterArgumentMap = typeParameterArgumentMap; + this.createdDuplicateTypeArgumentMap = false; + } + MutableTypeArgumentMap.prototype.ensureTypeArgumentCopy = function () { + if (!this.createdDuplicateTypeArgumentMap) { + var passedInTypeArgumentMap = this.typeParameterArgumentMap; + this.typeParameterArgumentMap = []; + for (var typeParameterID in passedInTypeArgumentMap) { + if (passedInTypeArgumentMap.hasOwnProperty(typeParameterID)) { + this.typeParameterArgumentMap[typeParameterID] = passedInTypeArgumentMap[typeParameterID]; + } + } + this.createdDuplicateTypeArgumentMap = true; + } + }; + return MutableTypeArgumentMap; + })(); + PullInstantiationHelpers.MutableTypeArgumentMap = MutableTypeArgumentMap; + + function instantiateTypeArgument(resolver, symbol, mutableTypeParameterMap) { + if (symbol.getIsSpecialized()) { + var rootTypeArgumentMap = symbol.getTypeParameterArgumentMap(); + var newTypeArgumentMap = []; + var allowedTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + var typeArg = rootTypeArgumentMap[typeParameterID]; + if (typeArg) { + newTypeArgumentMap[typeParameterID] = resolver.instantiateType(typeArg, mutableTypeParameterMap.typeParameterArgumentMap); + } + } + + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + if (newTypeArgumentMap[typeParameterID] && mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] != newTypeArgumentMap[typeParameterID]) { + mutableTypeParameterMap.ensureTypeArgumentCopy(); + mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] = newTypeArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.instantiateTypeArgument = instantiateTypeArgument; + + function cleanUpTypeArgumentMap(symbol, mutableTypeArgumentMap) { + var allowedToReferenceTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var typeParameterID in mutableTypeArgumentMap.typeParameterArgumentMap) { + if (mutableTypeArgumentMap.typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + if (!TypeScript.ArrayUtilities.any(allowedToReferenceTypeParameters, function (typeParameter) { + return typeParameter.pullSymbolID == typeParameterID; + })) { + mutableTypeArgumentMap.ensureTypeArgumentCopy(); + delete mutableTypeArgumentMap.typeParameterArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.cleanUpTypeArgumentMap = cleanUpTypeArgumentMap; + + function getAllowedToReferenceTypeParametersFromDecl(decl) { + var allowedToReferenceTypeParameters = []; + + var allowedToUseDeclTypeParameters = false; + var getTypeParametersFromParentDecl = false; + + switch (decl.kind) { + case 65536 /* Method */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + allowedToUseDeclTypeParameters = true; + break; + } + + case 16777216 /* FunctionType */: + case 33554432 /* ConstructorType */: + case 2097152 /* ConstructSignature */: + case 1048576 /* CallSignature */: + case 131072 /* FunctionExpression */: + case 16384 /* Function */: + allowedToUseDeclTypeParameters = true; + getTypeParametersFromParentDecl = true; + break; + + case 4096 /* Property */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + break; + } + + case 2048 /* Parameter */: + case 262144 /* GetAccessor */: + case 524288 /* SetAccessor */: + case 32768 /* ConstructorMethod */: + case 4194304 /* IndexSignature */: + case 8388608 /* ObjectType */: + case 256 /* ObjectLiteral */: + case 8192 /* TypeParameter */: + getTypeParametersFromParentDecl = true; + break; + + case 8 /* Class */: + case 16 /* Interface */: + allowedToUseDeclTypeParameters = true; + break; + } + + if (getTypeParametersFromParentDecl) { + allowedToReferenceTypeParameters = allowedToReferenceTypeParameters.concat(getAllowedToReferenceTypeParametersFromDecl(decl.getParentDecl())); + } + + if (allowedToUseDeclTypeParameters) { + var typeParameterDecls = decl.getTypeParameters(); + for (var i = 0; i < typeParameterDecls.length; i++) { + allowedToReferenceTypeParameters.push(typeParameterDecls[i].getSymbol()); + } + } + + return allowedToReferenceTypeParameters; + } + PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl = getAllowedToReferenceTypeParametersFromDecl; + + function createTypeParameterArgumentMap(typeParameters, typeArguments) { + return updateTypeParameterArgumentMap(typeParameters, typeArguments, {}); + } + PullInstantiationHelpers.createTypeParameterArgumentMap = createTypeParameterArgumentMap; + + function updateTypeParameterArgumentMap(typeParameters, typeArguments, typeParameterArgumentMap) { + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].getRootSymbol().pullSymbolID] = typeArguments[i]; + } + return typeParameterArgumentMap; + } + PullInstantiationHelpers.updateTypeParameterArgumentMap = updateTypeParameterArgumentMap; + + function updateMutableTypeParameterArgumentMap(typeParameters, typeArguments, mutableMap) { + for (var i = 0; i < typeParameters.length; i++) { + var typeParameterId = typeParameters[i].getRootSymbol().pullSymbolID; + if (mutableMap.typeParameterArgumentMap[typeParameterId] !== typeArguments[i]) { + mutableMap.ensureTypeArgumentCopy(); + mutableMap.typeParameterArgumentMap[typeParameterId] = typeArguments[i]; + } + } + } + PullInstantiationHelpers.updateMutableTypeParameterArgumentMap = updateMutableTypeParameterArgumentMap; + + function twoTypesAreInstantiationsOfSameNamedGenericType(type1, type2) { + var type1IsGeneric = type1.isGeneric() && type1.getTypeArguments() !== null; + var type2IsGeneric = type2.isGeneric() && type2.getTypeArguments() !== null; + + if (type1IsGeneric && type2IsGeneric) { + var type1Root = TypeScript.PullHelpers.getRootType(type1); + var type2Root = TypeScript.PullHelpers.getRootType(type2); + return type1Root === type2Root; + } + + return false; + } + PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType = twoTypesAreInstantiationsOfSameNamedGenericType; + })(TypeScript.PullInstantiationHelpers || (TypeScript.PullInstantiationHelpers = {})); + var PullInstantiationHelpers = TypeScript.PullInstantiationHelpers; +})(TypeScript || (TypeScript = {})); if (Error) Error.stackTraceLimit = 1000; @@ -53286,10 +54971,19 @@ var TypeScript; TypeScript.ioHostCreateDirectoryStructureTime = 0; TypeScript.ioHostWriteFileTime = 0; + (function (EmitOutputResult) { + EmitOutputResult[EmitOutputResult["Succeeded"] = 0] = "Succeeded"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfSyntaxErrors"] = 1] = "FailedBecauseOfSyntaxErrors"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfCompilerOptionsErrors"] = 2] = "FailedBecauseOfCompilerOptionsErrors"; + EmitOutputResult[EmitOutputResult["FailedToGenerateDeclarationsBecauseOfSemanticErrors"] = 3] = "FailedToGenerateDeclarationsBecauseOfSemanticErrors"; + })(TypeScript.EmitOutputResult || (TypeScript.EmitOutputResult = {})); + var EmitOutputResult = TypeScript.EmitOutputResult; + var EmitOutput = (function () { - function EmitOutput() { + function EmitOutput(emitOutputResult) { + if (typeof emitOutputResult === "undefined") { emitOutputResult = 0 /* Succeeded */; } this.outputFiles = []; - this.diagnostics = []; + this.emitOutputResult = emitOutputResult; } return EmitOutput; })(); @@ -53391,17 +55085,6 @@ var TypeScript; this.semanticInfoChain.removeDocument(fileName); }; - TypeScriptCompiler.prototype._isDynamicModuleCompilation = function () { - var fileNames = this.fileNames(); - for (var i = 0, n = fileNames.length; i < n; i++) { - var document = this.getDocument(fileNames[i]); - if (!document.isDeclareFile() && document.isExternalModule()) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.mapOutputFileName = function (document, emitOptions, extensionChanger) { if (document.emitToOwnOutputFile()) { var updatedFileName = document.fileName; @@ -53501,7 +55184,7 @@ var TypeScript; var emitOptions = new TypeScript.EmitOptions(this, resolvePath); if (emitOptions.diagnostic()) { - emitOutput.diagnostics.push(emitOptions.diagnostic()); + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; return emitOutput; } @@ -53533,7 +55216,7 @@ var TypeScript; var emitOptions = new TypeScript.EmitOptions(this, resolvePath); if (emitOptions.diagnostic()) { - emitOutput.diagnostics.push(emitOptions.diagnostic()); + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; return emitOutput; } @@ -53549,6 +55232,12 @@ var TypeScript; } }; + TypeScriptCompiler.prototype.canEmitDeclarations = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var document = this.getDocument(fileName); + return this._shouldEmitDeclarations(document); + }; + TypeScriptCompiler.mapToFileNameExtension = function (extension, fileName, wholeFileNameReplaced) { if (wholeFileNameReplaced) { return fileName; @@ -53609,7 +55298,7 @@ var TypeScript; var emitOptions = new TypeScript.EmitOptions(this, resolvePath); if (emitOptions.diagnostic()) { - emitOutput.diagnostics.push(emitOptions.diagnostic()); + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; return emitOutput; } @@ -53640,7 +55329,7 @@ var TypeScript; var emitOptions = new TypeScript.EmitOptions(this, resolvePath); if (emitOptions.diagnostic()) { - emitOutput.diagnostics.push(emitOptions.diagnostic()); + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; return emitOutput; } @@ -53715,6 +55404,15 @@ var TypeScript; return errors; }; + TypeScriptCompiler.prototype.getCompilerOptionsDiagnostics = function () { + var emitOptions = new TypeScript.EmitOptions(this, null); + var emitDiagnostic = emitOptions.diagnostic(); + if (emitDiagnostic) { + return [emitDiagnostic]; + } + return TypeScript.sentinelEmptyArray; + }; + TypeScriptCompiler.prototype.resolveAllFiles = function () { var fileNames = this.fileNames(); for (var i = 0, n = fileNames.length; i < n; i++) { @@ -53791,8 +55489,6 @@ var TypeScript; var contextualType = null; if ((i + 2 < n) && callExpression.argumentList === path[i + 1] && callExpression.argumentList.arguments === path[i + 2]) { - var arguments = callExpression.argumentList.arguments; - var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); if (isNew) { resolver.resolveObjectCreationExpression(callExpression, resolutionContext, callResolutionResults); @@ -53822,7 +55518,7 @@ var TypeScript; } } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); } break; @@ -53835,7 +55531,7 @@ var TypeScript; contextualType = currentContextualType.getElementType(); } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); } break; @@ -53862,7 +55558,7 @@ var TypeScript; } } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); } } @@ -53881,7 +55577,25 @@ var TypeScript; } } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 220 /* CastExpression */: + var castExpression = current; + if (!(i + 1 < n && path[i + 1] === castExpression.type)) { + if (propagateContextualTypes) { + var contextualType = null; + var typeSymbol = resolver.resolveAST(castExpression, inContextuallyTypedAssignment, resolutionContext).type; + + if (typeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = typeSymbol; + } + + resolutionContext.pushNewContextualType(contextualType); + } } break; @@ -53892,7 +55606,7 @@ var TypeScript; var contextualType = null; if (enclosingDecl && (enclosingDecl.kind & 1032192 /* SomeFunction */)) { - var typeAnnotation = TypeScript.getType(enclosingDeclAST); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); if (typeAnnotation) { var returnTypeSymbol = resolver.resolveTypeReference(typeAnnotation, resolutionContext); if (returnTypeSymbol) { @@ -53902,7 +55616,8 @@ var TypeScript; } else { var currentContextualType = resolutionContext.getContextualType(); if (currentContextualType && currentContextualType.isFunction()) { - var currentContextualTypeSignatureSymbol = currentContextualType.getDeclarations()[0].getSignatureSymbol(); + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; if (currentContextualTypeReturnTypeSymbol) { inContextuallyTypedAssignment = true; @@ -53912,7 +55627,7 @@ var TypeScript; } } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); } break; @@ -53927,6 +55642,10 @@ var TypeScript; case 163 /* WithStatement */: inWithBlock = true; break; + + case 146 /* Block */: + inContextuallyTypedAssignment = false; + break; } var decl = this.semanticInfoChain.getDeclForAST(current); @@ -53968,7 +55687,7 @@ var TypeScript; contextualType = varSymbol.type; } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); if (init) { resolver.resolveAST(init, inContextuallyTypedAssignment, resolutionContext); @@ -53999,7 +55718,7 @@ var TypeScript; var symbol = resolver.resolveAST(ast, context.inContextuallyTypedAssignment, context.resolutionContext); if (!symbol) { - TypeScript.Debug.assert(ast.kind() == 120 /* SourceUnit */, "No symbol was found for ast and ast was not source unit. Ast Kind: " + TypeScript.SyntaxKind[ast.kind()]); + TypeScript.Debug.assert(ast.kind() === 120 /* SourceUnit */, "No symbol was found for ast and ast was not source unit. Ast Kind: " + TypeScript.SyntaxKind[ast.kind()]); return null; } @@ -54140,6 +55859,32 @@ var TypeScript; TypeScriptCompiler.prototype.topLevelDecl = function (fileName) { return this.semanticInfoChain.topLevelDecl(fileName); }; + + TypeScriptCompiler.getLocationText = function (location) { + return location.fileName() + "(" + (location.line() + 1) + "," + (location.character() + 1) + ")"; + }; + + TypeScriptCompiler.getFullDiagnosticText = function (diagnostic) { + var result = ""; + if (diagnostic.fileName()) { + result += this.getLocationText(diagnostic) + ": "; + } + + result += diagnostic.message(); + + var additionalLocations = diagnostic.additionalLocations(); + if (additionalLocations.length > 0) { + result += " " + TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Additional_locations, null) + TypeScript.Environment.newLine; + + for (var i = 0, n = additionalLocations.length; i < n; i++) { + result += "\t" + this.getLocationText(additionalLocations[i]) + TypeScript.Environment.newLine; + } + } else { + result += TypeScript.Environment.newLine; + } + + return result; + }; return TypeScriptCompiler; })(); TypeScript.TypeScriptCompiler = TypeScriptCompiler; @@ -54220,11 +55965,11 @@ var TypeScript; case 0 /* Syntax */: case 1 /* Semantics */: - return this.index == this.fileNames.length; + return this.index === this.fileNames.length; case 3 /* Emit */: case 4 /* DeclarationEmit */: - return this.index == (this.fileNames.length + 1); + return this.index === (this.fileNames.length + 1); } return false; @@ -54344,10 +56089,10 @@ var TypeScript; function compareDataObjects(dst, src) { for (var e in dst) { - if (typeof dst[e] == "object") { + if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) return false; - } else if (typeof dst[e] != "function") { + } else if (typeof dst[e] !== "function") { if (dst[e] !== src[e]) return false; } @@ -54373,7 +56118,7 @@ var TypeScript; this.referencedTypeSymbol = referencedTypeSymbol; this.isResolved = true; - TypeScript.Debug.assert(referencedTypeSymbol != null, "Type root symbol may not be null"); + TypeScript.Debug.assert(referencedTypeSymbol !== null, "Type root symbol may not be null"); this.setRootSymbol(referencedTypeSymbol); @@ -54540,11 +56285,17 @@ var TypeScript; return this.referencedTypeSymbol.getTypeArgumentsOrTypeParameters(); }; - PullTypeReferenceSymbol.prototype.addCallSignature = function (callSignature) { - TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addCallSignature"); + PullTypeReferenceSymbol.prototype.appendCallSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendCallSignature"); }; - PullTypeReferenceSymbol.prototype.addConstructSignature = function (constructSignature) { - TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addConstructSignature"); + PullTypeReferenceSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertCallSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.appendConstructSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendConstructSignature"); + }; + PullTypeReferenceSymbol.prototype.insertConstructSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertConstructSignatureAtIndex"); }; PullTypeReferenceSymbol.prototype.addIndexSignature = function (indexSignature) { TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addIndexSignature"); @@ -54604,11 +56355,6 @@ var TypeScript; return this.referencedTypeSymbol.getTypesThatExplicitlyImplementThisType(); }; - PullTypeReferenceSymbol.prototype.hasBase = function (potentialBase, visited) { - if (typeof visited === "undefined") { visited = []; } - this.ensureReferencedTypeIsResolved(); - return this.referencedTypeSymbol.hasBase(potentialBase, visited); - }; PullTypeReferenceSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { this.ensureReferencedTypeIsResolved(); return this.referencedTypeSymbol.isValidBaseKind(baseType, isExtendedType); @@ -54653,25 +56399,26 @@ var TypeScript; TypeScript.nSpecializationsCreated = 0; TypeScript.nSpecializedSignaturesCreated = 0; + TypeScript.nSpecializedTypeParameterCreated = 0; var PullInstantiatedTypeReferenceSymbol = (function (_super) { __extends(PullInstantiatedTypeReferenceSymbol, _super); - function PullInstantiatedTypeReferenceSymbol(referencedTypeSymbol, _typeParameterArgumentMap) { + function PullInstantiatedTypeReferenceSymbol(referencedTypeSymbol, _typeParameterArgumentMap, isInstanceReferenceType) { _super.call(this, referencedTypeSymbol); this.referencedTypeSymbol = referencedTypeSymbol; this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.isInstanceReferenceType = isInstanceReferenceType; this._instantiatedMembers = null; this._allInstantiatedMemberNameCache = null; this._instantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); this._instantiatedCallSignatures = null; this._instantiatedConstructSignatures = null; this._instantiatedIndexSignatures = null; - this._typeArgumentReferences = null; + this._typeArgumentReferences = undefined; this._instantiatedConstructorMethod = null; this._instantiatedAssociatedContainerType = null; this._isArray = undefined; - this.isInstanceReferenceType = false; - this._generativeTypeClassification = 0 /* Unknown */; + this._generativeTypeClassification = []; TypeScript.nSpecializationsCreated++; } @@ -54680,72 +56427,43 @@ var TypeScript; }; PullInstantiatedTypeReferenceSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { - if (this._generativeTypeClassification == 0 /* Unknown */) { - var typeParameters = enclosingType.getTypeParameters(); - var typeReferenceTypeArguments = this.getRootSymbol().getTypeArguments(); - var referenceTypeArgument = null; - - if (!typeReferenceTypeArguments) { - var typeParametersMap = []; - - for (var i = 0; i < typeParameters.length; i++) { - typeParametersMap[typeParameters[i].pullSymbolID] = typeParameters[i]; - } - - var rootThis = TypeScript.PullHelpers.getRootType(this); - var wrapsSomeTypeParameters = rootThis.wrapsSomeTypeParameter(typeParametersMap); - - if (wrapsSomeTypeParameters && this.wrapsSomeNestedTypeIntoInfiniteExpansion(enclosingType)) { - this._generativeTypeClassification = 3 /* InfinitelyExpanding */; - } else if (wrapsSomeTypeParameters) { - this._generativeTypeClassification = 1 /* Open */; - } else { - this._generativeTypeClassification = 2 /* Closed */; - } - } else { - var i = 0; - - while (i < typeReferenceTypeArguments.length) { - referenceTypeArgument = typeReferenceTypeArguments[i].getRootSymbol(); - - if (referenceTypeArgument.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { - break; - } - - i++; - } - - if (i == typeParameters.length) { - this._generativeTypeClassification = 2 /* Closed */; - } - - if (this._generativeTypeClassification == 0 /* Unknown */) { - var i = 0; - - while ((this._generativeTypeClassification == 0 /* Unknown */) && (i < typeReferenceTypeArguments.length)) { - for (var j = 0; j < typeParameters.length; j++) { - if (typeParameters[j] == typeReferenceTypeArguments[i]) { - this._generativeTypeClassification = 1 /* Open */; - break; - } - } - - i++; - } - - if (this._generativeTypeClassification != 1 /* Open */) { - this._generativeTypeClassification = 3 /* InfinitelyExpanding */; - } - } - } + if (!this.isNamedTypeSymbol()) { + return 0 /* Unknown */; } - return this._generativeTypeClassification; + var generativeTypeClassification = this._generativeTypeClassification[enclosingType.pullSymbolID] || 0 /* Unknown */; + if (generativeTypeClassification === 0 /* Unknown */) { + var typeParameters = enclosingType.getTypeParameters(); + var enclosingTypeParameterMap = []; + for (var i = 0; i < typeParameters.length; i++) { + enclosingTypeParameterMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (typeArguments[i].wrapsSomeTypeParameter(enclosingTypeParameterMap, true)) { + generativeTypeClassification = 1 /* Open */; + break; + } + } + + if (generativeTypeClassification === 1 /* Open */) { + if (this.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType)) { + generativeTypeClassification = 3 /* InfinitelyExpanding */; + } + } else { + generativeTypeClassification = 2 /* Closed */; + } + + this._generativeTypeClassification[enclosingType.pullSymbolID] = generativeTypeClassification; + } + + return generativeTypeClassification; }; PullInstantiatedTypeReferenceSymbol.prototype.isArrayNamedTypeReference = function () { if (this._isArray === undefined) { - this._isArray = this.getRootSymbol().isArrayNamedTypeReference() || (this.getRootSymbol() == this._getResolver().getArrayNamedType()); + this._isArray = this.getRootSymbol().isArrayNamedTypeReference() || (this.getRootSymbol() === this._getResolver().getArrayNamedType()); } return this._isArray; }; @@ -54756,12 +56474,7 @@ var TypeScript; } var typeArguments = this.getTypeArguments(); - - if (typeArguments != null) { - return typeArguments[0]; - } - - return null; + return typeArguments ? typeArguments[0] : null; }; PullInstantiatedTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { @@ -54774,130 +56487,47 @@ var TypeScript; return this.referencedTypeSymbol; }; - PullInstantiatedTypeReferenceSymbol.create = function (resolver, type, typeParameterArgumentMap, instantiateFunctionTypeParameters) { - if (typeof instantiateFunctionTypeParameters === "undefined") { instantiateFunctionTypeParameters = false; } + PullInstantiatedTypeReferenceSymbol.create = function (resolver, type, typeParameterArgumentMap) { TypeScript.Debug.assert(resolver); + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(resolver, type, mutableTypeParameterMap); + var rootType = type.getRootSymbol(); - - var reconstructedTypeArgumentList = []; - var typeArguments = type.getTypeArguments(); - var typeParameters = rootType.getTypeParameters(); - - if (type.getIsSpecialized() && typeArguments && typeArguments.length) { - for (var i = 0; i < typeArguments.length; i++) { - reconstructedTypeArgumentList[reconstructedTypeArgumentList.length] = resolver.instantiateType(typeArguments[i], typeParameterArgumentMap, instantiateFunctionTypeParameters); - } - - for (var i = 0; i < typeArguments.length; i++) { - typeParameterArgumentMap[typeArguments[i].pullSymbolID] = reconstructedTypeArgumentList[i]; - } - } else { - var tyArg = null; - - for (var typeParameterID in typeParameterArgumentMap) { - if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { - tyArg = typeParameterArgumentMap[typeParameterID]; - - if (tyArg) { - reconstructedTypeArgumentList[reconstructedTypeArgumentList.length] = tyArg; - } - } - } + var instantiation = rootType.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiation) { + return instantiation; } - if (!instantiateFunctionTypeParameters) { - var instantiation = rootType.getSpecialization(reconstructedTypeArgumentList); + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(type, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; - if (instantiation) { - return instantiation; - } - } - - var isReferencedType = (type.kind & 8216 /* SomeInstantiatableType */) != 0; - - if (isReferencedType) { - if (typeParameters && reconstructedTypeArgumentList) { - if (typeParameters.length == reconstructedTypeArgumentList.length) { - for (var i = 0; i < typeParameters.length; i++) { - if (!TypeScript.PullHelpers.typeSymbolsAreIdentical(typeParameters[i], reconstructedTypeArgumentList[i])) { - isReferencedType = false; - break; - } - } - - if (isReferencedType) { - typeParameterArgumentMap = []; - } - } else { - isReferencedType = false; - } - } - } - - var instantiateRoot = isReferencedType; - - if (type.isTypeReference() && type.isGeneric()) { - var initializationMap = []; - - for (var typeParameterID in typeParameterArgumentMap) { - if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { - initializationMap[typeParameterID] = typeParameterArgumentMap[typeParameterID]; + var isInstanceReferenceType = (type.kind & 8216 /* SomeInstantiatableType */) != 0; + var resolvedTypeParameterArgumentMap = typeParameterArgumentMap; + if (isInstanceReferenceType) { + var typeParameters = rootType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + if (!TypeScript.PullHelpers.typeSymbolsAreIdentical(typeParameters[i], typeParameterArgumentMap[typeParameters[i].pullSymbolID])) { + isInstanceReferenceType = false; + break; } } - var oldMap = typeParameterArgumentMap; - - var outerTypeMap = type._typeParameterArgumentMap; - var innerSubstitution = null; - var outerSubstitution = null; - var canRelatePreInstantiatedTypeParametersToRootTypeParameters = true; - - for (var typeParameterID in outerTypeMap) { - if (outerTypeMap.hasOwnProperty(typeParameterID)) { - outerSubstitution = outerTypeMap[typeParameterID]; - innerSubstitution = typeParameterArgumentMap[outerSubstitution.pullSymbolID]; - - if (innerSubstitution && (!outerSubstitution.isTypeParameter() || !outerTypeMap[innerSubstitution.pullSymbolID] || !outerTypeMap[outerTypeMap[typeParameterID].pullSymbolID] || (outerTypeMap[outerTypeMap[typeParameterID].pullSymbolID] == outerSubstitution))) { - initializationMap[typeParameterID] = typeParameterArgumentMap[outerTypeMap[typeParameterID].pullSymbolID]; - - if (!outerSubstitution.isTypeParameter()) { - canRelatePreInstantiatedTypeParametersToRootTypeParameters = false; - } - } else { - canRelatePreInstantiatedTypeParametersToRootTypeParameters = false; - } - } - } - - if (canRelatePreInstantiatedTypeParametersToRootTypeParameters && typeParameters.length) { + if (isInstanceReferenceType) { typeParameterArgumentMap = []; - - for (var i = 0; i < typeParameters.length; i++) { - typeParameterArgumentMap[typeParameters[i].pullSymbolID] = initializationMap[typeParameters[i].pullSymbolID]; - } - - instantiateRoot = true; - } else { - typeParameterArgumentMap = initializationMap; } } - instantiation = new PullInstantiatedTypeReferenceSymbol(instantiateRoot ? rootType : type, typeParameterArgumentMap); + instantiation = new PullInstantiatedTypeReferenceSymbol(rootType, typeParameterArgumentMap, isInstanceReferenceType); - if (!instantiateFunctionTypeParameters) { - rootType.addSpecialization(instantiation, reconstructedTypeArgumentList); - } - - if (isReferencedType) { - instantiation.isInstanceReferenceType = true; - } + rootType.addSpecialization(instantiation, resolvedTypeParameterArgumentMap); return instantiation; }; PullInstantiatedTypeReferenceSymbol.prototype.isGeneric = function () { - return !!this.referencedTypeSymbol.getTypeParameters().length; + return this.getRootSymbol().isGeneric(); }; PullInstantiatedTypeReferenceSymbol.prototype.getTypeParameterArgumentMap = function () { @@ -54909,7 +56539,7 @@ var TypeScript; return this.getTypeParameters(); } - if (!this._typeArgumentReferences) { + if (this._typeArgumentReferences === undefined) { var typeParameters = this.referencedTypeSymbol.getTypeParameters(); if (typeParameters.length) { @@ -54929,6 +56559,8 @@ var TypeScript; } this._typeArgumentReferences = typeArguments; + } else { + this._typeArgumentReferences = null; } } @@ -54939,6 +56571,21 @@ var TypeScript; return this.getTypeArguments(); }; + PullInstantiatedTypeReferenceSymbol.prototype.populateInstantiatedMemberFromReferencedMember = function (referencedMember) { + var instantiatedMember; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(referencedMember); + + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + instantiatedMember = referencedMember; + } else { + instantiatedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + instantiatedMember.setRootSymbol(referencedMember); + instantiatedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + instantiatedMember.isOptional = referencedMember.isOptional; + } + this._instantiatedMemberNameCache[instantiatedMember.name] = instantiatedMember; + }; + PullInstantiatedTypeReferenceSymbol.prototype.getMembers = function () { this.ensureReferencedTypeIsResolved(); @@ -54959,21 +56606,10 @@ var TypeScript; this._getResolver().resolveDeclaredSymbol(referencedMember); if (!this._instantiatedMemberNameCache[referencedMember.name]) { - if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { - instantiatedMember = referencedMember; - } else { - instantiatedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); - instantiatedMember.setRootSymbol(referencedMember); - instantiatedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); - instantiatedMember.isOptional = referencedMember.isOptional; - } - - this._instantiatedMemberNameCache[instantiatedMember.name] = instantiatedMember; - } else { - instantiatedMember = this._instantiatedMemberNameCache[referencedMember.name]; + this.populateInstantiatedMemberFromReferencedMember(referencedMember); } - this._instantiatedMembers[this._instantiatedMembers.length] = instantiatedMember; + this._instantiatedMembers[this._instantiatedMembers.length] = this._instantiatedMemberNameCache[referencedMember.name]; } } @@ -54994,16 +56630,8 @@ var TypeScript; var referencedMemberSymbol = this.referencedTypeSymbol.findMember(name, lookInParent); if (referencedMemberSymbol) { - memberSymbol = new TypeScript.PullSymbol(referencedMemberSymbol.name, referencedMemberSymbol.kind); - memberSymbol.setRootSymbol(referencedMemberSymbol); - - this._getResolver().resolveDeclaredSymbol(referencedMemberSymbol); - - memberSymbol.type = this._getResolver().instantiateType(referencedMemberSymbol.type, this._typeParameterArgumentMap); - - memberSymbol.isOptional = referencedMemberSymbol.isOptional; - - this._instantiatedMemberNameCache[memberSymbol.name] = memberSymbol; + this.populateInstantiatedMemberFromReferencedMember(referencedMemberSymbol); + memberSymbol = this._instantiatedMemberNameCache[name]; } else { memberSymbol = null; } @@ -55070,6 +56698,9 @@ var TypeScript; if (!this._instantiatedConstructorMethod) { var referencedConstructorMethod = this.referencedTypeSymbol.getConstructorMethod(); this._instantiatedConstructorMethod = new TypeScript.PullSymbol(referencedConstructorMethod.name, referencedConstructorMethod.kind); + this._instantiatedConstructorMethod.setRootSymbol(referencedConstructorMethod); + this._instantiatedConstructorMethod.setResolved(); + this._instantiatedConstructorMethod.type = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedConstructorMethod.type, this._typeParameterArgumentMap); } @@ -55175,14 +56806,79 @@ var TypeScript; return this._instantiatedIndexSignatures; }; - - PullInstantiatedTypeReferenceSymbol.prototype.hasBase = function (potentialBase, visited) { - if (typeof visited === "undefined") { visited = []; } - return this.referencedTypeSymbol.hasBase(potentialBase, visited); - }; return PullInstantiatedTypeReferenceSymbol; })(PullTypeReferenceSymbol); TypeScript.PullInstantiatedTypeReferenceSymbol = PullInstantiatedTypeReferenceSymbol; + + var PullInstantiatedSignatureSymbol = (function (_super) { + __extends(PullInstantiatedSignatureSymbol, _super); + function PullInstantiatedSignatureSymbol(rootSignature, _typeParameterArgumentMap) { + _super.call(this, rootSignature.kind, rootSignature.isDefinition()); + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.setRootSymbol(rootSignature); + TypeScript.nSpecializedSignaturesCreated++; + + rootSignature.addSpecialization(this, _typeParameterArgumentMap); + } + PullInstantiatedSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedSignatureSymbol.prototype.getIsSpecialized = function () { + return true; + }; + + PullInstantiatedSignatureSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + + PullInstantiatedSignatureSymbol.prototype.getTypeParameters = function () { + var _this = this; + if (!this._typeParameters) { + var rootSymbol = this.getRootSymbol(); + var typeParameters = rootSymbol.getTypeParameters(); + var hasInstantiatedTypeParametersOfThisSignature = TypeScript.ArrayUtilities.all(typeParameters, function (typeParameter) { + return _this._typeParameterArgumentMap[typeParameter.pullSymbolID] !== undefined; + }); + + if (!hasInstantiatedTypeParametersOfThisSignature && typeParameters.length) { + this._typeParameters = []; + for (var i = 0; i < typeParameters.length; i++) { + this._typeParameters[this._typeParameters.length] = this._getResolver().instantiateTypeParameter(typeParameters[i], this._typeParameterArgumentMap); + } + } else { + this._typeParameters = TypeScript.sentinelEmptyArray; + } + } + + return this._typeParameters; + }; + + PullInstantiatedSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + var rootSymbol = this.getRootSymbol(); + return rootSymbol.getAllowedToReferenceTypeParameters(); + }; + return PullInstantiatedSignatureSymbol; + })(TypeScript.PullSignatureSymbol); + TypeScript.PullInstantiatedSignatureSymbol = PullInstantiatedSignatureSymbol; + + var PullInstantiatedTypeParameterSymbol = (function (_super) { + __extends(PullInstantiatedTypeParameterSymbol, _super); + function PullInstantiatedTypeParameterSymbol(rootTypeParameter, constraintType) { + _super.call(this, rootTypeParameter.name); + TypeScript.nSpecializedTypeParameterCreated++; + + this.setRootSymbol(rootTypeParameter); + this.setConstraint(constraintType); + + rootTypeParameter.addSpecialization(this, [constraintType]); + } + PullInstantiatedTypeParameterSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + return PullInstantiatedTypeParameterSymbol; + })(TypeScript.PullTypeParameterSymbol); + TypeScript.PullInstantiatedTypeParameterSymbol = PullInstantiatedTypeParameterSymbol; })(TypeScript || (TypeScript = {})); var TypeScript; (function (TypeScript) { @@ -55421,8 +57117,8 @@ var TypeScript; TypeScript.Debug.assert(start === 0); var bod = this.visitSyntaxList(node.moduleElements); - - var result = new TypeScript.SourceUnit(bod, this.fileName); + var comments = this.convertTokenLeadingComments(node.endOfFileToken, TypeScript.Syntax.childOffset(node, node.endOfFileToken)); + var result = new TypeScript.SourceUnit(bod, comments, this.fileName); this.setSpanExplicit(result, start, start + node.fullWidth()); return result; @@ -55999,17 +57695,17 @@ var TypeScript; this.movePast(node.openParenToken); - var arguments = this.visitSeparatedSyntaxList(node.arguments); + var _arguments = this.visitSeparatedSyntaxList(node.arguments); if (node.arguments.fullWidth() === 0 && node.closeParenToken.fullWidth() === 0) { var openParenTokenEnd = start + node.openParenToken.leadingTriviaWidth() + node.openParenToken.width(); - this.setSpanExplicit(arguments, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); + this.setSpanExplicit(_arguments, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); } var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); this.movePast(node.closeParenToken); - var result = new TypeScript.ArgumentList(typeArguments, arguments, closeParenToken); + var result = new TypeScript.ArgumentList(typeArguments, _arguments, closeParenToken); this.setSpan(result, start, node); return result; @@ -56230,14 +57926,14 @@ var TypeScript; SyntaxTreeToAstVisitor.prototype.visitConstructorDeclaration = function (node) { var start = this.position; - this.moveTo(node, node.parameterList); - var parameters = this.visitParameterList(node.parameterList); + this.moveTo(node, node.callSignature); + var callSignature = this.visitCallSignature(node.callSignature); var block = node.block ? node.block.accept(this) : null; this.movePast(node.semicolonToken); - var result = new TypeScript.ConstructorDeclaration(parameters, block); + var result = new TypeScript.ConstructorDeclaration(callSignature, block); this.setCommentsAndSpan(result, start, node); return result; @@ -57648,6 +59344,10 @@ var TypeScript; return commentArrayStructuralEquals(this.preComments(), ast.preComments(), includingPosition) && commentArrayStructuralEquals(this.postComments(), ast.postComments(), includingPosition); }; + + AST.prototype.isExpression = function () { + return false; + }; return AST; })(); TypeScript.AST = AST; @@ -57749,9 +59449,10 @@ var TypeScript; var SourceUnit = (function (_super) { __extends(SourceUnit, _super); - function SourceUnit(moduleElements, _fileName) { + function SourceUnit(moduleElements, endOfFileTokenLeadingComments, _fileName) { _super.call(this); this.moduleElements = moduleElements; + this.endOfFileTokenLeadingComments = endOfFileTokenLeadingComments; this._fileName = _fileName; moduleElements && (moduleElements.parent = this); } @@ -57800,6 +59501,10 @@ var TypeScript; Identifier.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; }; + + Identifier.prototype.isExpression = function () { + return true; + }; return Identifier; })(AST); TypeScript.Identifier = Identifier; @@ -57827,6 +59532,10 @@ var TypeScript; LiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition); }; + + LiteralExpression.prototype.isExpression = function () { + return true; + }; return LiteralExpression; })(AST); TypeScript.LiteralExpression = LiteralExpression; @@ -57853,6 +59562,10 @@ var TypeScript; ThisExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition); }; + + ThisExpression.prototype.isExpression = function () { + return true; + }; return ThisExpression; })(AST); TypeScript.ThisExpression = ThisExpression; @@ -57879,6 +59592,10 @@ var TypeScript; SuperExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition); }; + + SuperExpression.prototype.isExpression = function () { + return true; + }; return SuperExpression; })(AST); TypeScript.SuperExpression = SuperExpression; @@ -57908,6 +59625,10 @@ var TypeScript; NumericLiteral.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && (this._value === ast._value || (isNaN(this._value) && isNaN(ast._value))) && this._text === ast._text; }; + + NumericLiteral.prototype.isExpression = function () { + return true; + }; return NumericLiteral; })(AST); TypeScript.NumericLiteral = NumericLiteral; @@ -57930,6 +59651,10 @@ var TypeScript; RegularExpressionLiteral.prototype.kind = function () { return 12 /* RegularExpressionLiteral */; }; + + RegularExpressionLiteral.prototype.isExpression = function () { + return true; + }; return RegularExpressionLiteral; })(AST); TypeScript.RegularExpressionLiteral = RegularExpressionLiteral; @@ -57956,6 +59681,10 @@ var TypeScript; StringLiteral.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; }; + + StringLiteral.prototype.isExpression = function () { + return true; + }; return StringLiteral; })(AST); TypeScript.StringLiteral = StringLiteral; @@ -58279,6 +60008,10 @@ var TypeScript; PrefixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); }; + + PrefixUnaryExpression.prototype.isExpression = function () { + return true; + }; return PrefixUnaryExpression; })(AST); TypeScript.PrefixUnaryExpression = PrefixUnaryExpression; @@ -58297,6 +60030,10 @@ var TypeScript; ArrayLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expressions, ast.expressions, includingPosition); }; + + ArrayLiteralExpression.prototype.isExpression = function () { + return true; + }; return ArrayLiteralExpression; })(AST); TypeScript.ArrayLiteralExpression = ArrayLiteralExpression; @@ -58313,6 +60050,10 @@ var TypeScript; OmittedExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition); }; + + OmittedExpression.prototype.isExpression = function () { + return true; + }; return OmittedExpression; })(AST); TypeScript.OmittedExpression = OmittedExpression; @@ -58332,6 +60073,10 @@ var TypeScript; ParenthesizedExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + ParenthesizedExpression.prototype.isExpression = function () { + return true; + }; return ParenthesizedExpression; })(AST); TypeScript.ParenthesizedExpression = ParenthesizedExpression; @@ -58350,6 +60095,10 @@ var TypeScript; SimpleArrowFunctionExpression.prototype.kind = function () { return 219 /* SimpleArrowFunctionExpression */; }; + + SimpleArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; return SimpleArrowFunctionExpression; })(AST); TypeScript.SimpleArrowFunctionExpression = SimpleArrowFunctionExpression; @@ -58368,6 +60117,10 @@ var TypeScript; ParenthesizedArrowFunctionExpression.prototype.kind = function () { return 218 /* ParenthesizedArrowFunctionExpression */; }; + + ParenthesizedArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; return ParenthesizedArrowFunctionExpression; })(AST); TypeScript.ParenthesizedArrowFunctionExpression = ParenthesizedArrowFunctionExpression; @@ -58588,6 +60341,10 @@ var TypeScript; MemberAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); }; + + MemberAccessExpression.prototype.isExpression = function () { + return true; + }; return MemberAccessExpression; })(AST); TypeScript.MemberAccessExpression = MemberAccessExpression; @@ -58607,6 +60364,10 @@ var TypeScript; PostfixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); }; + + PostfixUnaryExpression.prototype.isExpression = function () { + return true; + }; return PostfixUnaryExpression; })(AST); TypeScript.PostfixUnaryExpression = PostfixUnaryExpression; @@ -58627,6 +60388,10 @@ var TypeScript; ElementAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentExpression, ast.argumentExpression, includingPosition); }; + + ElementAccessExpression.prototype.isExpression = function () { + return true; + }; return ElementAccessExpression; })(AST); TypeScript.ElementAccessExpression = ElementAccessExpression; @@ -58647,19 +60412,24 @@ var TypeScript; InvocationExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); }; + + InvocationExpression.prototype.isExpression = function () { + return true; + }; return InvocationExpression; })(AST); TypeScript.InvocationExpression = InvocationExpression; var ArgumentList = (function (_super) { __extends(ArgumentList, _super); - function ArgumentList(typeArgumentList, arguments, closeParenToken) { + function ArgumentList(typeArgumentList, _arguments, closeParenToken) { _super.call(this); this.typeArgumentList = typeArgumentList; - this.arguments = arguments; this.closeParenToken = closeParenToken; + this.arguments = _arguments; + typeArgumentList && (typeArgumentList.parent = this); - arguments && (arguments.parent = this); + _arguments && (_arguments.parent = this); } ArgumentList.prototype.kind = function () { return 226 /* ArgumentList */; @@ -58685,6 +60455,10 @@ var TypeScript; BinaryExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); }; + + BinaryExpression.prototype.isExpression = function () { + return true; + }; return BinaryExpression; })(AST); TypeScript.BinaryExpression = BinaryExpression; @@ -58707,6 +60481,10 @@ var TypeScript; ConditionalExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.whenTrue, ast.whenTrue, includingPosition) && structuralEquals(this.whenFalse, ast.whenFalse, includingPosition); }; + + ConditionalExpression.prototype.isExpression = function () { + return true; + }; return ConditionalExpression; })(AST); TypeScript.ConditionalExpression = ConditionalExpression; @@ -58887,11 +60665,11 @@ var TypeScript; var ConstructorDeclaration = (function (_super) { __extends(ConstructorDeclaration, _super); - function ConstructorDeclaration(parameterList, block) { + function ConstructorDeclaration(callSignature, block) { _super.call(this); - this.parameterList = parameterList; + this.callSignature = callSignature; this.block = block; - parameterList && (parameterList.parent = this); + callSignature && (callSignature.parent = this); block && (block.parent = this); } ConstructorDeclaration.prototype.kind = function () { @@ -59041,6 +60819,10 @@ var TypeScript; ObjectCreationExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); }; + + ObjectCreationExpression.prototype.isExpression = function () { + return true; + }; return ObjectCreationExpression; })(AST); TypeScript.ObjectCreationExpression = ObjectCreationExpression; @@ -59277,6 +61059,10 @@ var TypeScript; CastExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + CastExpression.prototype.isExpression = function () { + return true; + }; return CastExpression; })(AST); TypeScript.CastExpression = CastExpression; @@ -59295,6 +61081,10 @@ var TypeScript; ObjectLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.propertyAssignments, ast.propertyAssignments, includingPosition); }; + + ObjectLiteralExpression.prototype.isExpression = function () { + return true; + }; return ObjectLiteralExpression; })(AST); TypeScript.ObjectLiteralExpression = ObjectLiteralExpression; @@ -59347,6 +61137,10 @@ var TypeScript; FunctionExpression.prototype.kind = function () { return 222 /* FunctionExpression */; }; + + FunctionExpression.prototype.isExpression = function () { + return true; + }; return FunctionExpression; })(AST); TypeScript.FunctionExpression = FunctionExpression; @@ -59484,6 +61278,10 @@ var TypeScript; TypeOfExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + TypeOfExpression.prototype.isExpression = function () { + return true; + }; return TypeOfExpression; })(AST); TypeScript.TypeOfExpression = TypeOfExpression; @@ -59502,6 +61300,10 @@ var TypeScript; DeleteExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + DeleteExpression.prototype.isExpression = function () { + return true; + }; return DeleteExpression; })(AST); TypeScript.DeleteExpression = DeleteExpression; @@ -59520,6 +61322,10 @@ var TypeScript; VoidExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + VoidExpression.prototype.isExpression = function () { + return true; + }; return VoidExpression; })(AST); TypeScript.VoidExpression = VoidExpression; @@ -59571,17 +61377,6 @@ var TypeScript; return Comment; })(); TypeScript.Comment = Comment; - - function diagnosticFromDecl(decl, diagnosticKey, arguments) { - if (typeof arguments === "undefined") { arguments = null; } - var span = decl.getSpan(); - return new TypeScript.Diagnostic(decl.fileName(), decl.semanticInfoChain().lineMap(decl.fileName()), span.start(), span.length(), diagnosticKey, arguments); - } - TypeScript.diagnosticFromDecl = diagnosticFromDecl; - - function min(a, b) { - return a <= b ? a : b; - } })(TypeScript || (TypeScript = {})); var TypeScript; (function (TypeScript) { @@ -59682,6 +61477,11 @@ var TypeScript; } return { + appendFile: function (path, content) { + var txtFile = fso.OpenTextFile(path, 8, true); + txtFile.Write(content); + txtFile.Close(); + }, readFile: function (path, codepage) { return TypeScript.Environment.readFile(path, codepage); }, @@ -59802,6 +61602,9 @@ var TypeScript; var _module = require('module'); return { + appendFile: function (path, content) { + _fs.appendFileSync(path, content); + }, readFile: function (file, codepage) { return TypeScript.Environment.readFile(file, codepage); }, @@ -60245,10 +62048,38 @@ var TypeScript; return DiagnosticsLogger; })(); + var FileLogger = (function () { + function FileLogger(ioHost) { + this.ioHost = ioHost; + var file = "tsc." + Date.now() + ".log"; + + this.fileName = this.ioHost.resolvePath(file); + } + FileLogger.prototype.information = function () { + return false; + }; + FileLogger.prototype.debug = function () { + return false; + }; + FileLogger.prototype.warning = function () { + return false; + }; + FileLogger.prototype.error = function () { + return false; + }; + FileLogger.prototype.fatal = function () { + return false; + }; + FileLogger.prototype.log = function (s) { + this.ioHost.appendFile(this.fileName, s + '\r\n'); + }; + return FileLogger; + })(); + var BatchCompiler = (function () { function BatchCompiler(ioHost) { this.ioHost = ioHost; - this.compilerVersion = "0.9.5.0"; + this.compilerVersion = "0.9.7.0"; this.inputFiles = []; this.resolvedFiles = []; this.fileNameToSourceFile = new TypeScript.StringHashTable(); @@ -60266,7 +62097,13 @@ var TypeScript; } }; if (this.parseOptions()) { - this.logger = this.compilationSettings.gatherDiagnostics() ? new DiagnosticsLogger(this.ioHost) : new TypeScript.NullLogger(); + if (this.compilationSettings.createFileLog()) { + this.logger = new FileLogger(this.ioHost); + } else if (this.compilationSettings.gatherDiagnostics()) { + this.logger = new DiagnosticsLogger(this.ioHost); + } else { + this.logger = new TypeScript.NullLogger(); + } if (this.compilationSettings.watch()) { this.watchFiles(); @@ -60277,6 +62114,46 @@ var TypeScript; this.compile(); + if (this.compilationSettings.createFileLog()) { + this.logger.log("Compilation settings:"); + this.logger.log(" propagateEnumConstants " + this.compilationSettings.propagateEnumConstants()); + this.logger.log(" removeComments " + this.compilationSettings.removeComments()); + this.logger.log(" watch " + this.compilationSettings.watch()); + this.logger.log(" noResolve " + this.compilationSettings.noResolve()); + this.logger.log(" noImplicitAny " + this.compilationSettings.noImplicitAny()); + this.logger.log(" nolib " + this.compilationSettings.noLib()); + this.logger.log(" target " + this.compilationSettings.codeGenTarget()); + this.logger.log(" module " + this.compilationSettings.moduleGenTarget()); + this.logger.log(" out " + this.compilationSettings.outFileOption()); + this.logger.log(" outDir " + this.compilationSettings.outDirOption()); + this.logger.log(" sourcemap " + this.compilationSettings.mapSourceFiles()); + this.logger.log(" mapRoot " + this.compilationSettings.mapRoot()); + this.logger.log(" sourceroot " + this.compilationSettings.sourceRoot()); + this.logger.log(" declaration " + this.compilationSettings.generateDeclarationFiles()); + this.logger.log(" useCaseSensitiveFileResolution " + this.compilationSettings.useCaseSensitiveFileResolution()); + this.logger.log(" diagnostics " + this.compilationSettings.gatherDiagnostics()); + this.logger.log(" codepage " + this.compilationSettings.codepage()); + + this.logger.log(""); + + this.logger.log("Input files:"); + this.inputFiles.forEach(function (file) { + _this.logger.log(" " + file); + }); + + this.logger.log(""); + + this.logger.log("Resolved Files:"); + this.resolvedFiles.forEach(function (file) { + file.importedFiles.forEach(function (file) { + _this.logger.log(" " + file); + }); + file.referencedFiles.forEach(function (file) { + _this.logger.log(" " + file); + }); + }); + } + if (this.compilationSettings.gatherDiagnostics()) { this.logger.log(""); this.logger.log("File resolution time: " + TypeScript.fileResolutionTime); @@ -60507,6 +62384,7 @@ var TypeScript; }); opts.flag('noResolve', { + experimental: true, usage: { locCode: TypeScript.DiagnosticCode.Skip_resolution_and_preprocessing, args: null @@ -60530,6 +62408,13 @@ var TypeScript; } }); + opts.flag('logFile', { + experimental: true, + set: function () { + mutableSettings.createFileLog = true; + } + }); + opts.option('target', { usage: { locCode: TypeScript.DiagnosticCode.Specify_ECMAScript_target_version_0_default_or_1, @@ -60644,11 +62529,12 @@ var TypeScript; this.inputFiles.push.apply(this.inputFiles, opts.unnamed); - if (this.inputFiles.length === 0 || needsHelp) { + if (shouldPrintVersionOnly) { + opts.printVersion(); + return false; + } else if (this.inputFiles.length === 0 || needsHelp) { opts.printUsage(); return false; - } else if (shouldPrintVersionOnly) { - opts.printVersion(); } return !this.hasErrors; @@ -60853,11 +62739,7 @@ var TypeScript; this.hasErrors = true; } - if (diagnostic.fileName()) { - this.ioHost.stderr.Write(diagnostic.fileName() + "(" + (diagnostic.line() + 1) + "," + (diagnostic.character() + 1) + "): "); - } - - this.ioHost.stderr.WriteLine(diagnostic.message()); + this.ioHost.stderr.Write(TypeScript.TypeScriptCompiler.getFullDiagnosticText(diagnostic)); }; BatchCompiler.prototype.tryWriteOutputFiles = function (outputFiles) { diff --git a/_infrastructure/tests/typescript/0.9.5-beta/typescript.js b/_infrastructure/tests/typescript/0.9.7/typescript.js similarity index 86% rename from _infrastructure/tests/typescript/0.9.5-beta/typescript.js rename to _infrastructure/tests/typescript/0.9.7/typescript.js index 667affcf14..29ed8063a7 100644 --- a/_infrastructure/tests/typescript/0.9.5-beta/typescript.js +++ b/_infrastructure/tests/typescript/0.9.7/typescript.js @@ -57,7 +57,7 @@ var TypeScript; Implementations_are_not_allowed_in_ambient_contexts: "Implementations are not allowed in ambient contexts.", declare_modifier_not_allowed_for_code_already_in_an_ambient_context: "'declare' modifier not allowed for code already in an ambient context.", Initializers_are_not_allowed_in_ambient_contexts: "Initializers are not allowed in ambient contexts.", - Parameter_property_declarations_can_only_be_used_in_constructors: "Parameter property declarations can only be used in constructors.", + Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration: "Parameter property declarations can only be used in a non-ambient constructor declaration.", Function_implementation_expected: "Function implementation expected.", Constructor_implementation_expected: "Constructor implementation expected.", Function_overload_name_must_be_0: "Function overload name must be '{0}'.", @@ -97,13 +97,15 @@ var TypeScript; declare_modifier_not_allowed_on_import_declaration: "'declare' modifier not allowed on import declaration.", Function_overload_must_be_static: "Function overload must be static.", Function_overload_must_not_be_static: "Function overload must not be static.", - Parameter_property_declarations_cannot_be_used_in_an_ambient_context: "Parameter property declarations cannot be used in an ambient context.", Parameter_property_declarations_cannot_be_used_in_a_constructor_overload: "Parameter property declarations cannot be used in a constructor overload.", Invalid_reference_directive_syntax: "Invalid 'reference' directive syntax.", Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: "Octal literals are not available when targeting ECMAScript 5 and higher.", Accessors_are_not_allowed_in_ambient_contexts: "Accessors are not allowed in ambient contexts.", _0_modifier_cannot_appear_on_a_constructor_declaration: "'{0}' modifier cannot appear on a constructor declaration.", _0_modifier_cannot_appear_on_a_parameter: "'{0}' modifier cannot appear on a parameter.", + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: "Only a single variable declaration is allowed in a 'for...in' statement.", + Type_parameters_cannot_appear_on_a_constructor_declaration: "Type parameters cannot appear on a constructor declaration.", + Type_annotation_cannot_appear_on_a_constructor_declaration: "Type annotation cannot appear on a constructor declaration.", Duplicate_identifier_0: "Duplicate identifier '{0}'.", The_name_0_does_not_exist_in_the_current_scope: "The name '{0}' does not exist in the current scope.", The_name_0_does_not_refer_to_a_value: "The name '{0}' does not refer to a value.", @@ -199,14 +201,14 @@ var TypeScript; Could_not_find_symbol_0: "Could not find symbol '{0}'.", get_and_set_accessor_must_have_the_same_type: "'get' and 'set' accessor must have the same type.", this_cannot_be_referenced_in_current_location: "'this' cannot be referenced in current location.", - Static_methods_cannot_reference_class_type_parameters: "Static methods cannot reference class type parameters.", + Static_members_cannot_reference_class_type_parameters: "Static members cannot reference class type parameters.", Class_0_is_recursively_referenced_as_a_base_type_of_itself: "Class '{0}' is recursively referenced as a base type of itself.", Interface_0_is_recursively_referenced_as_a_base_type_of_itself: "Interface '{0}' is recursively referenced as a base type of itself.", super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.", super_cannot_be_referenced_in_non_derived_classes: "'super' cannot be referenced in non-derived classes.", A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: "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: "Constructors for derived classes must contain a 'super' call.", - Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors: "Super calls are not permitted outside constructors or in local functions inside constructors.", + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: "Super calls are not permitted outside constructors or in nested functions inside constructors.", _0_1_is_inaccessible: "'{0}.{1}' is inaccessible.", this_cannot_be_referenced_within_module_bodies: "'this' cannot be referenced within module bodies.", Invalid_expression_types_not_known_to_support_the_addition_operator: "Invalid '+' expression - types not known to support the addition operator.", @@ -219,11 +221,11 @@ var TypeScript; The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.", The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "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_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "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_a_subtype_of_the_Function_interface_type: "The right-hand side of an 'instanceof' expression must be of type 'any' or a subtype of the 'Function' interface type.", + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.", Setters_cannot_return_a_value: "Setters cannot return a value.", Tried_to_query_type_of_uninitialized_module_0: "Tried to query type of uninitialized module '{0}'.", Tried_to_set_variable_type_to_uninitialized_module_type_0: "Tried to set variable type to uninitialized module type '{0}'.", - Function_0_declared_a_non_void_return_type_but_has_no_return_expression: "Function '{0}' declared a non-void return type, but has no return expression.", + Type_0_does_not_have_type_parameters: "Type '{0}' does not have type parameters.", Getters_must_return_a_value: "Getters must return a value.", Getter_and_setter_accessors_do_not_agree_in_visibility: "Getter and setter accessors do not agree in visibility.", Invalid_left_hand_side_of_assignment_expression: "Invalid left-hand side of assignment expression.", @@ -250,7 +252,7 @@ var TypeScript; Overload_signatures_must_all_be_exported_or_not_exported: "Overload signatures must all be exported or not exported.", Overload_signatures_must_all_be_ambient_or_non_ambient: "Overload signatures must all be ambient or non-ambient.", Overload_signatures_must_all_be_optional_or_required: "Overload signatures must all be optional or required.", - Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature: "Specialized overload signature is not subtype of any non-specialized signature.", + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: "Specialized overload signature is not assignable to any non-specialized signature.", this_cannot_be_referenced_in_constructor_arguments: "'this' cannot be referenced in constructor arguments.", Instance_member_cannot_be_accessed_off_a_class: "Instance member cannot be accessed off a class.", Untyped_function_calls_may_not_accept_type_arguments: "Untyped function calls may not accept type arguments.", @@ -261,14 +263,14 @@ var TypeScript; Export_assignments_may_only_be_used_at_the_top_level_of_external_modules: "Export assignments may only be used at the top-level of external modules.", Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.", Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: "Only public methods of the base class are accessible via the 'super' keyword.", - Numeric_indexer_type_0_must_be_a_subtype_of_string_indexer_type_1: "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}'.", - Numeric_indexer_type_0_must_be_a_subtype_of_string_indexer_type_1_NL_2: "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}':{NL}{2}", - All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type_0: "All numerically named properties must be subtypes of numeric indexer type '{0}'.", - All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type_0_NL_1: "All numerically named properties must be subtypes of numeric indexer type '{0}':{NL}{1}", - All_named_properties_must_be_subtypes_of_string_indexer_type_0: "All named properties must be subtypes of string indexer type '{0}'.", - All_named_properties_must_be_subtypes_of_string_indexer_type_0_NL_1: "All named properties must be subtypes of string indexer type '{0}':{NL}{1}", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0: "All numerically named properties must be assignable to numeric indexer type '{0}'.", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1: "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}", + All_named_properties_must_be_assignable_to_string_indexer_type_0: "All named properties must be assignable to string indexer type '{0}'.", + All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1: "All named properties must be assignable to string indexer type '{0}':{NL}{1}", Generic_type_references_must_include_all_type_arguments: "Generic type references must include all type arguments.", - Default_arguments_are_not_allowed_in_an_overload_parameter: "Default arguments are not allowed in an overload parameter.", + Default_arguments_are_only_allowed_in_implementation: "Default arguments are only allowed in implementation.", Overloads_cannot_differ_only_by_return_type: "Overloads cannot differ only by return type.", Function_expression_declared_a_non_void_return_type_but_has_no_return_expression: "Function expression declared a non-void return type, but has no return expression.", Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.", @@ -280,7 +282,7 @@ var TypeScript; Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.", Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.", Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.", - Type_reference_0_in_extends_clause_does_not_reference_constructor_function_for_1: "Type reference '{0}' in extends clause does not reference constructor function for '{1}'.", + Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1: "Type name '{0}' in extends clause does not reference constructor function for '{1}'.", Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1: "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.", Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2: "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.", Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}", @@ -323,6 +325,13 @@ var TypeScript; Type_of_conditional_0_must_be_identical_to_1_or_2: "Type of conditional '{0}' must be identical to '{1}' or '{2}'.", Type_of_conditional_0_must_be_identical_to_1_2_or_3: "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.", Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.", + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.", + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.", + Parameter_0_cannot_be_referenced_in_its_initializer: "Parameter '{0}' cannot be referenced in its initializer.", + Duplicate_string_index_signature: "Duplicate string index signature.", + Duplicate_number_index_signature: "Duplicate number index signature.", + All_declarations_of_an_interface_must_have_identical_type_parameters: "All declarations of an interface must have identical type parameters.", + Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.", Type_0_is_missing_property_1_from_type_2: "Type '{0}' is missing property '{1}' from type '{2}'.", Types_of_property_0_of_types_1_and_2_are_incompatible: "Types of property '{0}' of types '{1}' and '{2}' are incompatible.", Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3: "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}", @@ -347,20 +356,23 @@ var TypeScript; Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}", Type_reference_cannot_refer_to_container_0: "Type reference cannot refer to container '{0}'.", Type_reference_must_refer_to_type: "Type reference must refer to type.", - Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element: "Enums with multiple declarations must provide an initializer for the first enum element.", + In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element: "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.", _0_overload_s: " (+ {0} overload(s))", Variable_declaration_cannot_have_the_same_name_as_an_import_declaration: "Variable declaration cannot have the same name as an import declaration.", Signature_expected_0_type_arguments_got_1_instead: "Signature expected {0} type arguments, got {1} instead.", Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2: "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.", - Types_0_and_1_originating_in_inifinitely_expanding_type_reference_do_not_refer_to_same_named_type: "Types '{0}' and '{1}' originating in inifinitely expanding type reference do not refer to same named type.", - Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments: "Types '{0}' and '{1}' originating in inifinitely expanding type reference have incompatible type arguments.", - Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: "Types '{0}' and '{1}' originating in inifinitely expanding type reference have incompatible type arguments:{NL}{2}", - Types_of_property_0_of_types_1_and_2_are_not_identical: "Types of property '{0}' of types '{1}' and '{2}' are not identical.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type: "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}", + Named_properties_0_of_types_1_and_2_are_not_identical: "Named properties '{0}' of types '{1}' and '{2}' are not identical.", Types_of_string_indexer_of_types_0_and_1_are_not_identical: "Types of string indexer of types '{0}' and '{1}' are not identical.", Types_of_number_indexer_of_types_0_and_1_are_not_identical: "Types of number indexer of types '{0}' and '{1}' are not identical.", - Type_of_number_indexer_in_type_0_is_not_a_subtype_of_string_indexer_type_in_type_1_NL_2: "Type of number indexer in type '{0}' is not a subtype of string indexer type in type '{1}'.{NL}{2}", - Type_of_property_0_in_type_1_is_not_a_subtype_of_string_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not a subtype of string indexer type in type '{2}'.{NL}{3}", - Type_of_property_0_in_type_1_is_not_a_subtype_of_number_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not a subtype of number indexer type in type '{2}'.{NL}{3}", + Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2: "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}", + Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}", + Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}", + Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_static_property_2_as_private: "Types '{0}' and '{1}' define static property '{2}' as private.", Current_host_does_not_support_0_option: "Current host does not support '{0}' option.", ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2: "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'", Module_code_generation_0_not_supported: "Module code generation '{0}' not supported.", @@ -420,6 +432,7 @@ var TypeScript; DIRECTORY: "DIRECTORY", NUMBER: "NUMBER", Specify_the_codepage_to_use_when_opening_source_files: "Specify the codepage to use when opening source files.", + Additional_locations: "Additional locations:", This_version_of_the_Javascript_runtime_does_not_support_the_0_function: "This version of the Javascript runtime does not support the '{0}' function.", Unknown_rule: "Unknown rule.", Invalid_line_number_0: "Invalid line number ({0})", @@ -435,7 +448,9 @@ var TypeScript; Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.", Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.", Array_Literal_implicitly_has_an_any_type_from_widening: "Array Literal implicitly has an 'any' type from widening.", - _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type." + _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.", + Index_signature_of_object_type_implicitly_has_an_any_type: "Index signature of object type implicitly has an 'any' type.", + Object_literal_s_property_0_implicitly_has_an_any_type_from_widening: "Object literal's property '{0}' implicitly has an 'any' type from widening." }; })(TypeScript || (TypeScript = {})); var TypeScript; @@ -959,20 +974,64 @@ var TypeScript; })(); TypeScript.Debug = Debug; })(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; var TypeScript; (function (TypeScript) { TypeScript.LocalizedDiagnosticMessages = null; - var Diagnostic = (function () { - function Diagnostic(fileName, lineMap, start, length, diagnosticKey, arguments) { - if (typeof arguments === "undefined") { arguments = null; } - this._diagnosticKey = diagnosticKey; - this._arguments = (arguments && arguments.length > 0) ? arguments : null; + var Location = (function () { + function Location(fileName, lineMap, start, length) { this._fileName = fileName; this._lineMap = lineMap; this._start = start; this._length = length; } + Location.prototype.fileName = function () { + return this._fileName; + }; + + Location.prototype.lineMap = function () { + return this._lineMap; + }; + + Location.prototype.line = function () { + return this._lineMap ? this._lineMap.getLineNumberFromPosition(this.start()) : 0; + }; + + Location.prototype.character = function () { + return this._lineMap ? this._lineMap.getLineAndCharacterFromPosition(this.start()).character() : 0; + }; + + Location.prototype.start = function () { + return this._start; + }; + + Location.prototype.length = function () { + return this._length; + }; + + Location.equals = function (location1, location2) { + return location1._fileName === location2._fileName && location1._start === location2._start && location1._length === location2._length; + }; + return Location; + })(); + TypeScript.Location = Location; + + var Diagnostic = (function (_super) { + __extends(Diagnostic, _super); + function Diagnostic(fileName, lineMap, start, length, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + _super.call(this, fileName, lineMap, start, length); + this._diagnosticKey = diagnosticKey; + this._arguments = (_arguments && _arguments.length > 0) ? _arguments : null; + this._additionalLocations = (additionalLocations && additionalLocations.length > 0) ? additionalLocations : null; + } Diagnostic.prototype.toJSON = function (key) { var result = {}; result.start = this.start(); @@ -980,34 +1039,14 @@ var TypeScript; result.diagnosticCode = this._diagnosticKey; - var arguments = this.arguments(); - if (arguments && arguments.length > 0) { - result.arguments = arguments; + var _arguments = this.arguments(); + if (_arguments && _arguments.length > 0) { + result.arguments = _arguments; } return result; }; - Diagnostic.prototype.fileName = function () { - return this._fileName; - }; - - Diagnostic.prototype.line = function () { - return this._lineMap ? this._lineMap.getLineNumberFromPosition(this.start()) : 0; - }; - - Diagnostic.prototype.character = function () { - return this._lineMap ? this._lineMap.getLineAndCharacterFromPosition(this.start()).character() : 0; - }; - - Diagnostic.prototype.start = function () { - return this._start; - }; - - Diagnostic.prototype.length = function () { - return this._length; - }; - Diagnostic.prototype.diagnosticKey = function () { return this._diagnosticKey; }; @@ -1025,11 +1064,11 @@ var TypeScript; }; Diagnostic.prototype.additionalLocations = function () { - return []; + return this._additionalLocations || []; }; Diagnostic.equals = function (diagnostic1, diagnostic2) { - return diagnostic1._fileName === diagnostic2._fileName && diagnostic1._start === diagnostic2._start && diagnostic1._length === diagnostic2._length && diagnostic1._diagnosticKey === diagnostic2._diagnosticKey && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { + return Location.equals(diagnostic1, diagnostic2) && diagnostic1._diagnosticKey === diagnostic2._diagnosticKey && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { return v1 === v2; }); }; @@ -1038,7 +1077,7 @@ var TypeScript; return getDiagnosticInfoFromKey(this.diagnosticKey()); }; return Diagnostic; - })(); + })(Location); TypeScript.Diagnostic = Diagnostic; function newLine() { @@ -1051,7 +1090,7 @@ var TypeScript; var regex = /\{(\d+)\}/g; var match; - while ((match = regex.exec(diagnostic)) != null) { + while (match = regex.exec(diagnostic)) { var val = parseInt(match[1]); if (!isNaN(val) && val > largest) { largest = val; @@ -1216,7 +1255,7 @@ var TypeScript; numberOfCharsLeft -= 2; } - if (numberOfCharsLeft == 1) { + if (numberOfCharsLeft === 1) { h ^= key.charCodeAt(index); h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); } @@ -2252,7 +2291,7 @@ var TypeScript; "code": 1039, "category": 1 /* Error */ }, - "Parameter property declarations can only be used in constructors.": { + "Parameter property declarations can only be used in a non-ambient constructor declaration.": { "code": 1040, "category": 1 /* Error */ }, @@ -2412,10 +2451,6 @@ var TypeScript; "code": 1081, "category": 1 /* Error */ }, - "Parameter property declarations cannot be used in an ambient context.": { - "code": 1082, - "category": 1 /* Error */ - }, "Parameter property declarations cannot be used in a constructor overload.": { "code": 1083, "category": 1 /* Error */ @@ -2440,6 +2475,18 @@ var TypeScript; "code": 1090, "category": 1 /* Error */ }, + "Only a single variable declaration is allowed in a 'for...in' statement.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type parameters cannot appear on a constructor declaration.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type annotation cannot appear on a constructor declaration.": { + "code": 1092, + "category": 1 /* Error */ + }, "Duplicate identifier '{0}'.": { "code": 2000, "category": 1 /* Error */ @@ -2820,7 +2867,7 @@ var TypeScript; "code": 2097, "category": 1 /* Error */ }, - "Static methods cannot reference class type parameters.": { + "Static members cannot reference class type parameters.": { "code": 2099, "category": 1 /* Error */ }, @@ -2848,7 +2895,7 @@ var TypeScript; "code": 2105, "category": 1 /* Error */ }, - "Super calls are not permitted outside constructors or in local functions inside constructors.": { + "Super calls are not permitted outside constructors or in nested functions inside constructors.": { "code": 2106, "category": 1 /* Error */ }, @@ -2900,7 +2947,7 @@ var TypeScript; "code": 2120, "category": 1 /* Error */ }, - "The right-hand side of an 'instanceof' expression must be of type 'any' or a subtype of the 'Function' interface type.": { + "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.": { "code": 2121, "category": 1 /* Error */ }, @@ -2916,7 +2963,7 @@ var TypeScript; "code": 2124, "category": 1 /* Error */ }, - "Function '{0}' declared a non-void return type, but has no return expression.": { + "Type '{0}' does not have type parameters.": { "code": 2125, "category": 1 /* Error */ }, @@ -3024,7 +3071,7 @@ var TypeScript; "code": 2153, "category": 1 /* Error */ }, - "Specialized overload signature is not subtype of any non-specialized signature.": { + "Specialized overload signature is not assignable to any non-specialized signature.": { "code": 2154, "category": 1 /* Error */ }, @@ -3068,27 +3115,27 @@ var TypeScript; "code": 2166, "category": 1 /* Error */ }, - "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}'.": { + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.": { "code": 2167, "category": 1 /* Error */ }, - "Numeric indexer type '{0}' must be a subtype of string indexer type '{1}':{NL}{2}": { + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}": { "code": 2168, "category": 1 /* Error */ }, - "All numerically named properties must be subtypes of numeric indexer type '{0}'.": { + "All numerically named properties must be assignable to numeric indexer type '{0}'.": { "code": 2169, "category": 1 /* Error */ }, - "All numerically named properties must be subtypes of numeric indexer type '{0}':{NL}{1}": { + "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}": { "code": 2170, "category": 1 /* Error */ }, - "All named properties must be subtypes of string indexer type '{0}'.": { + "All named properties must be assignable to string indexer type '{0}'.": { "code": 2171, "category": 1 /* Error */ }, - "All named properties must be subtypes of string indexer type '{0}':{NL}{1}": { + "All named properties must be assignable to string indexer type '{0}':{NL}{1}": { "code": 2172, "category": 1 /* Error */ }, @@ -3096,7 +3143,7 @@ var TypeScript; "code": 2173, "category": 1 /* Error */ }, - "Default arguments are not allowed in an overload parameter.": { + "Default arguments are only allowed in implementation.": { "code": 2174, "category": 1 /* Error */ }, @@ -3144,7 +3191,7 @@ var TypeScript; "code": 2185, "category": 1 /* Error */ }, - "Type reference '{0}' in extends clause does not reference constructor function for '{1}'.": { + "Type name '{0}' in extends clause does not reference constructor function for '{1}'.": { "code": 2186, "category": 1 /* Error */ }, @@ -3316,6 +3363,34 @@ var TypeScript; "code": 2228, "category": 1 /* Error */ }, + "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": { + "code": 2229, + "category": 1 /* Error */ + }, + "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.": { + "code": 2230, + "category": 1 /* Error */ + }, + "Parameter '{0}' cannot be referenced in its initializer.": { + "code": 2231, + "category": 1 /* Error */ + }, + "Duplicate string index signature.": { + "code": 2232, + "category": 1 /* Error */ + }, + "Duplicate number index signature.": { + "code": 2233, + "category": 1 /* Error */ + }, + "All declarations of an interface must have identical type parameters.": { + "code": 2234, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.": { + "code": 2235, + "category": 1 /* Error */ + }, "Type '{0}' is missing property '{1}' from type '{2}'.": { "code": 4000, "category": 3 /* NoPrefix */ @@ -3412,7 +3487,7 @@ var TypeScript; "code": 4023, "category": 1 /* Error */ }, - "Enums with multiple declarations must provide an initializer for the first enum element.": { + "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.": { "code": 4024, "category": 1 /* Error */ }, @@ -3432,19 +3507,19 @@ var TypeScript; "code": 4028, "category": 3 /* NoPrefix */ }, - "Types '{0}' and '{1}' originating in inifinitely expanding type reference do not refer to same named type.": { + "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.": { "code": 4029, "category": 3 /* NoPrefix */ }, - "Types '{0}' and '{1}' originating in inifinitely expanding type reference have incompatible type arguments.": { + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.": { "code": 4030, "category": 3 /* NoPrefix */ }, - "Types '{0}' and '{1}' originating in inifinitely expanding type reference have incompatible type arguments:{NL}{2}": { + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}": { "code": 4031, "category": 3 /* NoPrefix */ }, - "Types of property '{0}' of types '{1}' and '{2}' are not identical.": { + "Named properties '{0}' of types '{1}' and '{2}' are not identical.": { "code": 4032, "category": 3 /* NoPrefix */ }, @@ -3456,18 +3531,30 @@ var TypeScript; "code": 4034, "category": 3 /* NoPrefix */ }, - "Type of number indexer in type '{0}' is not a subtype of string indexer type in type '{1}'.{NL}{2}": { + "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}": { "code": 4035, "category": 3 /* NoPrefix */ }, - "Type of property '{0}' in type '{1}' is not a subtype of string indexer type in type '{2}'.{NL}{3}": { + "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}": { "code": 4036, "category": 3 /* NoPrefix */ }, - "Type of property '{0}' in type '{1}' is not a subtype of number indexer type in type '{2}'.{NL}{3}": { + "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}": { "code": 4037, "category": 3 /* NoPrefix */ }, + "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4038, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4039, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define static property '{2}' as private.": { + "code": 4040, + "category": 3 /* NoPrefix */ + }, "Current host does not support '{0}' option.": { "code": 5001, "category": 1 /* Error */ @@ -3704,6 +3791,10 @@ var TypeScript; "code": 6040, "category": 2 /* Message */ }, + "Additional locations:": { + "code": 6041, + "category": 2 /* Message */ + }, "This version of the Javascript runtime does not support the '{0}' function.": { "code": 7000, "category": 1 /* Error */ @@ -3767,6 +3858,14 @@ var TypeScript; "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.": { "code": 7016, "category": 1 /* Error */ + }, + "Index signature of object type implicitly has an 'any' type.": { + "code": 7017, + "category": 1 /* Error */ + }, + "Object literal's property '{0}' implicitly has an 'any' type from widening.": { + "code": 7018, + "category": 1 /* Error */ } }; })(TypeScript || (TypeScript = {})); @@ -3943,12 +4042,6 @@ var TypeScript; })(TypeScript.LineMap1 || (TypeScript.LineMap1 = {})); var LineMap1 = TypeScript.LineMap1; })(TypeScript || (TypeScript = {})); -var __extends = this.__extends || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; var TypeScript; (function (TypeScript) { (function (TextFactory) { @@ -6082,40 +6175,47 @@ var TypeScript; var end = this.slidingWindow.absoluteIndex(); var trailingTriviaInfo = this.scanTriviaInfo(diagnostics, true); + var fullEnd = this.slidingWindow.absoluteIndex(); var isVariableWidthKeyword = (kindAndFlags & -2147483648 /* IsVariableWidthKeyword */) !== 0; var kind = kindAndFlags & ~-2147483648 /* IsVariableWidthKeyword */; - var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, trailingTriviaInfo, isVariableWidthKeyword); + var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword); return diagnosticsLength !== diagnostics.length ? TypeScript.Syntax.realizeToken(token) : token; }; - Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, trailingTriviaInfo, isVariableWidthKeyword) { + Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword) { if (!isVariableWidthKeyword && kind >= 15 /* FirstFixedWidth */) { if (leadingTriviaInfo === 0) { if (trailingTriviaInfo === 0) { return new TypeScript.Syntax.FixedWidthTokenWithNoTrivia(kind); } else { - return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(this.text, fullStart, kind, trailingTriviaInfo); + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); } } else if (trailingTriviaInfo === 0) { - return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(this.text, fullStart, kind, leadingTriviaInfo); + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); } else { - return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(this.text, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo); + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); } } else { var width = end - start; + + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + if (leadingTriviaInfo === 0) { if (trailingTriviaInfo === 0) { - return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(this.text, fullStart, kind, width); + return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(fullText, kind); } else { - return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(this.text, fullStart, kind, width, trailingTriviaInfo); + return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); } } else if (trailingTriviaInfo === 0) { - return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(this.text, fullStart, kind, leadingTriviaInfo, width); + return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); } else { - return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(this.text, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo); + return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); } } }; @@ -8606,8 +8706,8 @@ var TypeScript; NormalModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, false); }; - NormalModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, parameterList, block, semicolonToken) { - return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, parameterList, block, semicolonToken, false); + NormalModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, false); }; NormalModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, false); @@ -8868,8 +8968,8 @@ var TypeScript; StrictModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, true); }; - StrictModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, parameterList, block, semicolonToken) { - return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, parameterList, block, semicolonToken, true); + StrictModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, true); }; StrictModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, true); @@ -9495,12 +9595,13 @@ var TypeScript; result.parsedInStrictMode = true; } + var thisAsIndexable = this; for (var i = 0, n = this.childCount(); i < n; i++) { var value = this.childAt(i); if (value) { for (var name in this) { - if (value === this[name]) { + if (value === thisAsIndexable[name]) { result[name] = value; break; } @@ -12799,12 +12900,13 @@ var TypeScript; var ArgumentListSyntax = (function (_super) { __extends(ArgumentListSyntax, _super); - function ArgumentListSyntax(typeArgumentList, openParenToken, arguments, closeParenToken, parsedInStrictMode) { + function ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, parsedInStrictMode) { _super.call(this, parsedInStrictMode); this.typeArgumentList = typeArgumentList; this.openParenToken = openParenToken; - this.arguments = arguments; this.closeParenToken = closeParenToken; + + this.arguments = _arguments; } ArgumentListSyntax.prototype.accept = function (visitor) { return visitor.visitArgumentList(this); @@ -14038,11 +14140,11 @@ var TypeScript; var ConstructorDeclarationSyntax = (function (_super) { __extends(ConstructorDeclarationSyntax, _super); - function ConstructorDeclarationSyntax(modifiers, constructorKeyword, parameterList, block, semicolonToken, parsedInStrictMode) { + function ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, parsedInStrictMode) { _super.call(this, parsedInStrictMode); this.modifiers = modifiers; this.constructorKeyword = constructorKeyword; - this.parameterList = parameterList; + this.callSignature = callSignature; this.block = block; this.semicolonToken = semicolonToken; } @@ -14065,7 +14167,7 @@ var TypeScript; case 1: return this.constructorKeyword; case 2: - return this.parameterList; + return this.callSignature; case 3: return this.block; case 4: @@ -14079,20 +14181,20 @@ var TypeScript; return true; }; - ConstructorDeclarationSyntax.prototype.update = function (modifiers, constructorKeyword, parameterList, block, semicolonToken) { - if (this.modifiers === modifiers && this.constructorKeyword === constructorKeyword && this.parameterList === parameterList && this.block === block && this.semicolonToken === semicolonToken) { + ConstructorDeclarationSyntax.prototype.update = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.constructorKeyword === constructorKeyword && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { return this; } - return new ConstructorDeclarationSyntax(modifiers, constructorKeyword, parameterList, block, semicolonToken, this.parsedInStrictMode()); + return new ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, this.parsedInStrictMode()); }; - ConstructorDeclarationSyntax.create = function (constructorKeyword, parameterList) { - return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, constructorKeyword, parameterList, null, null, false); + ConstructorDeclarationSyntax.create = function (constructorKeyword, callSignature) { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, constructorKeyword, callSignature, null, null, false); }; ConstructorDeclarationSyntax.create1 = function () { - return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(62 /* ConstructorKeyword */), ParameterListSyntax.create1(), null, null, false); + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(62 /* ConstructorKeyword */), CallSignatureSyntax.create1(), null, null, false); }; ConstructorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { @@ -14104,7 +14206,7 @@ var TypeScript; }; ConstructorDeclarationSyntax.prototype.withModifiers = function (modifiers) { - return this.update(modifiers, this.constructorKeyword, this.parameterList, this.block, this.semicolonToken); + return this.update(modifiers, this.constructorKeyword, this.callSignature, this.block, this.semicolonToken); }; ConstructorDeclarationSyntax.prototype.withModifier = function (modifier) { @@ -14112,19 +14214,19 @@ var TypeScript; }; ConstructorDeclarationSyntax.prototype.withConstructorKeyword = function (constructorKeyword) { - return this.update(this.modifiers, constructorKeyword, this.parameterList, this.block, this.semicolonToken); + return this.update(this.modifiers, constructorKeyword, this.callSignature, this.block, this.semicolonToken); }; - ConstructorDeclarationSyntax.prototype.withParameterList = function (parameterList) { - return this.update(this.modifiers, this.constructorKeyword, parameterList, this.block, this.semicolonToken); + ConstructorDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.constructorKeyword, callSignature, this.block, this.semicolonToken); }; ConstructorDeclarationSyntax.prototype.withBlock = function (block) { - return this.update(this.modifiers, this.constructorKeyword, this.parameterList, block, this.semicolonToken); + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, block, this.semicolonToken); }; ConstructorDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { - return this.update(this.modifiers, this.constructorKeyword, this.parameterList, this.block, semicolonToken); + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, this.block, semicolonToken); }; ConstructorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { @@ -17614,7 +17716,7 @@ var TypeScript; }; SyntaxRewriter.prototype.visitConstructorDeclaration = function (node) { - return node.update(this.visitList(node.modifiers), this.visitToken(node.constructorKeyword), this.visitNode(node.parameterList), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + return node.update(this.visitList(node.modifiers), this.visitToken(node.constructorKeyword), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); }; SyntaxRewriter.prototype.visitMemberFunctionDeclaration = function (node) { @@ -18036,14 +18138,12 @@ var TypeScript; (function (TypeScript) { (function (Syntax) { var VariableWidthTokenWithNoTrivia = (function () { - function VariableWidthTokenWithNoTrivia(sourceText, fullStart, kind, textOrWidth) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function VariableWidthTokenWithNoTrivia(fullText, kind) { + this._fullText = fullText; this.tokenKind = kind; - this._textOrWidth = textOrWidth; } VariableWidthTokenWithNoTrivia.prototype.clone = function () { - return new VariableWidthTokenWithNoTrivia(this._sourceText, this._fullStart, this.tokenKind, this._textOrWidth); + return new VariableWidthTokenWithNoTrivia(this._fullText, this.tokenKind); }; VariableWidthTokenWithNoTrivia.prototype.isNode = function () { @@ -18071,29 +18171,17 @@ var TypeScript; }; VariableWidthTokenWithNoTrivia.prototype.fullWidth = function () { - return this.width(); + return this.fullText().length; }; - VariableWidthTokenWithNoTrivia.prototype.start = function () { - return this._fullStart; - }; - VariableWidthTokenWithNoTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - VariableWidthTokenWithNoTrivia.prototype.width = function () { - return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); }; VariableWidthTokenWithNoTrivia.prototype.text = function () { - if (typeof this._textOrWidth === 'number') { - this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); - } - - return this._textOrWidth; + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); }; - VariableWidthTokenWithNoTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; VariableWidthTokenWithNoTrivia.prototype.value = function () { @@ -18214,15 +18302,13 @@ var TypeScript; Syntax.VariableWidthTokenWithNoTrivia = VariableWidthTokenWithNoTrivia; var VariableWidthTokenWithLeadingTrivia = (function () { - function VariableWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, textOrWidth) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._leadingTriviaInfo = leadingTriviaInfo; - this._textOrWidth = textOrWidth; } VariableWidthTokenWithLeadingTrivia.prototype.clone = function () { - return new VariableWidthTokenWithLeadingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._textOrWidth); + return new VariableWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); }; VariableWidthTokenWithLeadingTrivia.prototype.isNode = function () { @@ -18250,29 +18336,17 @@ var TypeScript; }; VariableWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { - return getTriviaWidth(this._leadingTriviaInfo) + this.width(); + return this.fullText().length; }; - VariableWidthTokenWithLeadingTrivia.prototype.start = function () { - return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); - }; - VariableWidthTokenWithLeadingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - VariableWidthTokenWithLeadingTrivia.prototype.width = function () { - return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); }; VariableWidthTokenWithLeadingTrivia.prototype.text = function () { - if (typeof this._textOrWidth === 'number') { - this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); - } - - return this._textOrWidth; + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); }; - VariableWidthTokenWithLeadingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; VariableWidthTokenWithLeadingTrivia.prototype.value = function () { @@ -18307,7 +18381,7 @@ var TypeScript; return getTriviaWidth(this._leadingTriviaInfo); }; VariableWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); }; VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { @@ -18393,15 +18467,13 @@ var TypeScript; Syntax.VariableWidthTokenWithLeadingTrivia = VariableWidthTokenWithLeadingTrivia; var VariableWidthTokenWithTrailingTrivia = (function () { - function VariableWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, textOrWidth, trailingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; - this._textOrWidth = textOrWidth; this._trailingTriviaInfo = trailingTriviaInfo; } VariableWidthTokenWithTrailingTrivia.prototype.clone = function () { - return new VariableWidthTokenWithTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._textOrWidth, this._trailingTriviaInfo); + return new VariableWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); }; VariableWidthTokenWithTrailingTrivia.prototype.isNode = function () { @@ -18429,29 +18501,17 @@ var TypeScript; }; VariableWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { - return this.width() + getTriviaWidth(this._trailingTriviaInfo); + return this.fullText().length; }; - VariableWidthTokenWithTrailingTrivia.prototype.start = function () { - return this._fullStart; - }; - VariableWidthTokenWithTrailingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - VariableWidthTokenWithTrailingTrivia.prototype.width = function () { - return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); }; VariableWidthTokenWithTrailingTrivia.prototype.text = function () { - if (typeof this._textOrWidth === 'number') { - this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); - } - - return this._textOrWidth; + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); }; - VariableWidthTokenWithTrailingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; VariableWidthTokenWithTrailingTrivia.prototype.value = function () { @@ -18505,7 +18565,7 @@ var TypeScript; return getTriviaWidth(this._trailingTriviaInfo); }; VariableWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); }; VariableWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { @@ -18572,16 +18632,14 @@ var TypeScript; Syntax.VariableWidthTokenWithTrailingTrivia = VariableWidthTokenWithTrailingTrivia; var VariableWidthTokenWithLeadingAndTrailingTrivia = (function () { - function VariableWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, textOrWidth, trailingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._leadingTriviaInfo = leadingTriviaInfo; - this._textOrWidth = textOrWidth; this._trailingTriviaInfo = trailingTriviaInfo; } VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { - return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._textOrWidth, this._trailingTriviaInfo); + return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { @@ -18609,29 +18667,17 @@ var TypeScript; }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { - return getTriviaWidth(this._leadingTriviaInfo) + this.width() + getTriviaWidth(this._trailingTriviaInfo); + return this.fullText().length; }; - VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.start = function () { - return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); - }; - VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { - return typeof this._textOrWidth === 'number' ? this._textOrWidth : this._textOrWidth.length; + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { - if (typeof this._textOrWidth === 'number') { - this._textOrWidth = this._sourceText.substr(this.start(), this._textOrWidth, this.tokenKind === 11 /* IdentifierName */); - } - - return this._textOrWidth; + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); }; - VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { @@ -18666,7 +18712,7 @@ var TypeScript; return getTriviaWidth(this._leadingTriviaInfo); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { @@ -18685,7 +18731,7 @@ var TypeScript; return getTriviaWidth(this._trailingTriviaInfo); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); }; VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { @@ -18784,11 +18830,12 @@ var TypeScript; }; FixedWidthTokenWithNoTrivia.prototype.fullWidth = function () { - return this.width(); + return this.fullText().length; }; FixedWidthTokenWithNoTrivia.prototype.width = function () { return this.text().length; }; + FixedWidthTokenWithNoTrivia.prototype.text = function () { return TypeScript.SyntaxFacts.getText(this.tokenKind); }; @@ -18904,14 +18951,13 @@ var TypeScript; Syntax.FixedWidthTokenWithNoTrivia = FixedWidthTokenWithNoTrivia; var FixedWidthTokenWithLeadingTrivia = (function () { - function FixedWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._leadingTriviaInfo = leadingTriviaInfo; } FixedWidthTokenWithLeadingTrivia.prototype.clone = function () { - return new FixedWidthTokenWithLeadingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo); + return new FixedWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); }; FixedWidthTokenWithLeadingTrivia.prototype.isNode = function () { @@ -18939,23 +18985,17 @@ var TypeScript; }; FixedWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { - return getTriviaWidth(this._leadingTriviaInfo) + this.width(); + return this.fullText().length; }; - FixedWidthTokenWithLeadingTrivia.prototype.start = function () { - return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); - }; - FixedWidthTokenWithLeadingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - FixedWidthTokenWithLeadingTrivia.prototype.width = function () { return this.text().length; }; + FixedWidthTokenWithLeadingTrivia.prototype.text = function () { return TypeScript.SyntaxFacts.getText(this.tokenKind); }; FixedWidthTokenWithLeadingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; FixedWidthTokenWithLeadingTrivia.prototype.value = function () { @@ -18980,7 +19020,7 @@ var TypeScript; return getTriviaWidth(this._leadingTriviaInfo); }; FixedWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); }; FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { @@ -19066,14 +19106,13 @@ var TypeScript; Syntax.FixedWidthTokenWithLeadingTrivia = FixedWidthTokenWithLeadingTrivia; var FixedWidthTokenWithTrailingTrivia = (function () { - function FixedWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, trailingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._trailingTriviaInfo = trailingTriviaInfo; } FixedWidthTokenWithTrailingTrivia.prototype.clone = function () { - return new FixedWidthTokenWithTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._trailingTriviaInfo); + return new FixedWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); }; FixedWidthTokenWithTrailingTrivia.prototype.isNode = function () { @@ -19101,23 +19140,17 @@ var TypeScript; }; FixedWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { - return this.width() + getTriviaWidth(this._trailingTriviaInfo); + return this.fullText().length; }; - FixedWidthTokenWithTrailingTrivia.prototype.start = function () { - return this._fullStart; - }; - FixedWidthTokenWithTrailingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - FixedWidthTokenWithTrailingTrivia.prototype.width = function () { return this.text().length; }; + FixedWidthTokenWithTrailingTrivia.prototype.text = function () { return TypeScript.SyntaxFacts.getText(this.tokenKind); }; FixedWidthTokenWithTrailingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; FixedWidthTokenWithTrailingTrivia.prototype.value = function () { @@ -19161,7 +19194,7 @@ var TypeScript; return getTriviaWidth(this._trailingTriviaInfo); }; FixedWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); }; FixedWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { @@ -19228,15 +19261,14 @@ var TypeScript; Syntax.FixedWidthTokenWithTrailingTrivia = FixedWidthTokenWithTrailingTrivia; var FixedWidthTokenWithLeadingAndTrailingTrivia = (function () { - function FixedWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo) { - this._sourceText = sourceText; - this._fullStart = fullStart; + function FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; this.tokenKind = kind; this._leadingTriviaInfo = leadingTriviaInfo; this._trailingTriviaInfo = trailingTriviaInfo; } FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { - return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._sourceText, this._fullStart, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { @@ -19264,23 +19296,17 @@ var TypeScript; }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { - return getTriviaWidth(this._leadingTriviaInfo) + this.width() + getTriviaWidth(this._trailingTriviaInfo); + return this.fullText().length; }; - FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.start = function () { - return this._fullStart + getTriviaWidth(this._leadingTriviaInfo); - }; - FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.end = function () { - return this.start() + this.width(); - }; - FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { return this.text().length; }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { return TypeScript.SyntaxFacts.getText(this.tokenKind); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { - return this._sourceText.substr(this._fullStart, this.fullWidth(), false); + return this._fullText; }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { @@ -19305,7 +19331,7 @@ var TypeScript; return getTriviaWidth(this._leadingTriviaInfo); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this._fullStart, getTriviaWidth(this._leadingTriviaInfo), false); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { @@ -19324,7 +19350,7 @@ var TypeScript; return getTriviaWidth(this._trailingTriviaInfo); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { - return TypeScript.Scanner.scanTrivia(this._sourceText, this.end(), getTriviaWidth(this._trailingTriviaInfo), true); + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); }; FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { @@ -19396,36 +19422,6 @@ var TypeScript; token.trailingTrivia().collectTextElements(elements); } - function fixedWidthToken(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo) { - if (leadingTriviaInfo === 0) { - if (trailingTriviaInfo === 0) { - return new FixedWidthTokenWithNoTrivia(kind); - } else { - return new FixedWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, trailingTriviaInfo); - } - } else if (trailingTriviaInfo === 0) { - return new FixedWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo); - } else { - return new FixedWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, trailingTriviaInfo); - } - } - Syntax.fixedWidthToken = fixedWidthToken; - - function variableWidthToken(sourceText, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo) { - if (leadingTriviaInfo === 0) { - if (trailingTriviaInfo === 0) { - return new VariableWidthTokenWithNoTrivia(sourceText, fullStart, kind, width); - } else { - return new VariableWidthTokenWithTrailingTrivia(sourceText, fullStart, kind, width, trailingTriviaInfo); - } - } else if (trailingTriviaInfo === 0) { - return new VariableWidthTokenWithLeadingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, width); - } else { - return new VariableWidthTokenWithLeadingAndTrailingTrivia(sourceText, fullStart, kind, leadingTriviaInfo, width, trailingTriviaInfo); - } - } - Syntax.variableWidthToken = variableWidthToken; - function getTriviaWidth(value) { return value >>> 2 /* TriviaFullWidthShift */; } @@ -19615,7 +19611,7 @@ var TypeScript; case 13 /* carriageReturn */: var nextIndex = i + 1; - if (nextIndex < text.length && text.charCodeAt(nextIndex) == 10 /* lineFeed */) { + if (nextIndex < text.length && text.charCodeAt(nextIndex) === 10 /* lineFeed */) { i++; } continue; @@ -21363,7 +21359,7 @@ var TypeScript; SyntaxWalker.prototype.visitConstructorDeclaration = function (node) { this.visitList(node.modifiers); this.visitToken(node.constructorKeyword); - this.visitNode(node.parameterList); + this.visitNode(node.callSignature); this.visitOptionalNode(node.block); this.visitOptionalToken(node.semicolonToken); }; @@ -21831,7 +21827,7 @@ var TypeScript; ListParsingState[ListParsingState["TypeParameterList_TypeParameters"] = 1 << 19] = "TypeParameterList_TypeParameters"; ListParsingState[ListParsingState["FirstListParsingState"] = ListParsingState.SourceUnit_ModuleElements] = "FirstListParsingState"; - ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeArgumentList_Types] = "LastListParsingState"; + ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeParameterList_TypeParameters] = "LastListParsingState"; })(ListParsingState || (ListParsingState = {})); var SyntaxCursor = (function () { @@ -23200,13 +23196,13 @@ var TypeScript; ParserImpl.prototype.isConstructorDeclaration = function () { var index = this.modifierCount(); - return this.peekToken(index).tokenKind === 62 /* ConstructorKeyword */ && this.peekToken(index + 1).tokenKind === 72 /* OpenParenToken */; + return this.peekToken(index).tokenKind === 62 /* ConstructorKeyword */; }; ParserImpl.prototype.parseConstructorDeclaration = function () { var modifiers = this.parseModifiers(); var constructorKeyword = this.eatKeyword(62 /* ConstructorKeyword */); - var parameterList = this.parseParameterList(); + var callSignature = this.parseCallSignature(false); var semicolonToken = null; var block = null; @@ -23217,7 +23213,7 @@ var TypeScript; semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); } - return this.factory.constructorDeclaration(modifiers, constructorKeyword, parameterList, block, semicolonToken); + return this.factory.constructorDeclaration(modifiers, constructorKeyword, callSignature, block, semicolonToken); }; ParserImpl.prototype.isMemberFunctionDeclaration = function (inErrorRecovery) { @@ -25091,10 +25087,6 @@ var TypeScript; var currentToken = this.currentToken(); var currentTokenKind = currentToken.tokenKind; - if (currentTokenKind === 39 /* TypeOfKeyword */) { - return this.parseTypeQuery(); - } - var type = this.parseNonArrayType(currentToken); while (this.currentToken().tokenKind === 74 /* OpenBracketToken */) { @@ -25137,6 +25129,9 @@ var TypeScript; case 31 /* NewKeyword */: return this.parseConstructorType(); + + case 39 /* TypeOfKeyword */: + return this.parseTypeQuery(); } return this.parseNameOrGenericType(); @@ -25262,7 +25257,7 @@ var TypeScript; ParserImpl.prototype.abortParsingListOrMoveToNextToken = function (currentListType, items, skippedTokens) { this.reportUnexpectedTokenDiagnostic(currentListType); - for (var state = 262144 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { + for (var state = 524288 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { if ((this.listParsingState & state) !== 0) { if (this.isExpectedListTerminator(state) || this.isExpectedListItem(state, true)) { return true; @@ -26098,14 +26093,11 @@ var TypeScript; return true; } - if (this.inAmbientDeclaration) { - this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_cannot_be_used_in_an_ambient_context); - return true; - } else if (this.currentConstructor && !this.currentConstructor.block && this.currentConstructor.parameterList === parameterList) { + if (!this.inAmbientDeclaration && this.currentConstructor && !this.currentConstructor.block && this.currentConstructor.callSignature.parameterList === parameterList) { this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_cannot_be_used_in_a_constructor_overload); return true; - } else if (this.currentConstructor === null || this.currentConstructor.parameterList !== parameterList) { - this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_can_only_be_used_in_constructors); + } else if (this.inAmbientDeclaration || this.currentConstructor === null || this.currentConstructor.callSignature.parameterList !== parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration); return true; } } @@ -26337,9 +26329,22 @@ var TypeScript; inFunctionOverloadChain = functionDeclaration.block === null; functionOverloadChainName = functionDeclaration.identifier.valueText(); - if (lastElement && inFunctionOverloadChain) { - this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); - return true; + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = moduleElements.childAt(i + 1); + if (nextElement.kind() === 129 /* FunctionDeclaration */) { + var nextFunction = nextElement; + + if (nextFunction.identifier.valueText() !== functionOverloadChainName && nextFunction.block === null) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } } } else { inFunctionOverloadChain = false; @@ -26382,9 +26387,10 @@ var TypeScript; this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); return true; } + isStaticOverload = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); if (isStaticOverload !== isInStaticOverloadChain) { - propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); var diagnostic = isInStaticOverloadChain ? TypeScript.DiagnosticCode.Function_overload_must_be_static : TypeScript.DiagnosticCode.Function_overload_must_not_be_static; this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, diagnostic, null); return true; @@ -26403,9 +26409,22 @@ var TypeScript; functionOverloadChainName = memberFunctionDeclaration.propertyName.valueText(); isInStaticOverloadChain = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); - if (lastElement && inFunctionOverloadChain) { - this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); - return true; + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = node.classElements.childAt(i + 1); + if (nextElement.kind() === 135 /* MemberFunctionDeclaration */) { + var nextMemberFunction = nextElement; + + if (nextMemberFunction.propertyName.valueText() !== functionOverloadChainName && nextMemberFunction.block === null) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } } } else if (classElement.kind() === 137 /* ConstructorDeclaration */) { var constructorDeclaration = classElement; @@ -26696,23 +26715,21 @@ var TypeScript; GrammarCheckerWalker.prototype.checkEnumElements = function (node) { var enumElementFullStart = this.childFullStart(node, node.enumElements); - var seenComputedValue = false; + var previousValueWasComputed = false; for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { var child = node.enumElements.childAt(i); if (i % 2 === 0) { var enumElement = child; - if (!enumElement.equalsValueClause && seenComputedValue) { + if (!enumElement.equalsValueClause && previousValueWasComputed) { this.pushDiagnostic1(enumElementFullStart, enumElement, TypeScript.DiagnosticCode.Enum_member_must_have_initializer, null); return true; } if (enumElement.equalsValueClause) { var value = enumElement.equalsValueClause.value; - if (!TypeScript.Syntax.isIntegerLiteral(value)) { - seenComputedValue = true; - } + previousValueWasComputed = !TypeScript.Syntax.isIntegerLiteral(value); } } @@ -26999,7 +27016,7 @@ var TypeScript; }; GrammarCheckerWalker.prototype.visitForInStatement = function (node) { - if (this.checkForStatementInAmbientContxt(node)) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForInStatementVariableDeclaration(node)) { this.skip(node); return; } @@ -27007,6 +27024,17 @@ var TypeScript; _super.prototype.visitForInStatement.call(this, node); }; + GrammarCheckerWalker.prototype.checkForInStatementVariableDeclaration = function (node) { + if (node.variableDeclaration && node.variableDeclaration.variableDeclarators.nonSeparatorCount() > 1) { + var variableDeclarationFullStart = this.childFullStart(node, node.variableDeclaration); + + this.pushDiagnostic1(variableDeclarationFullStart, node.variableDeclaration, TypeScript.DiagnosticCode.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + return true; + } + + return false; + }; + GrammarCheckerWalker.prototype.visitForStatement = function (node) { if (this.checkForStatementInAmbientContxt(node)) { this.skip(node); @@ -27183,7 +27211,7 @@ var TypeScript; }; GrammarCheckerWalker.prototype.visitConstructorDeclaration = function (node) { - if (this.checkClassElementModifiers(node.modifiers) || this.checkConstructorModifiers(node.modifiers)) { + if (this.checkClassElementModifiers(node.modifiers) || this.checkConstructorModifiers(node.modifiers) || this.checkConstructorTypeParameterList(node) || this.checkConstructorTypeAnnotation(node)) { this.skip(node); return; } @@ -27210,6 +27238,32 @@ var TypeScript; return false; }; + GrammarCheckerWalker.prototype.checkConstructorTypeParameterList = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeParameterList) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeParameterListFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(callSignatureFullStart, node.callSignature.typeParameterList, TypeScript.DiagnosticCode.Type_parameters_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeAnnotation = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeAnnotation) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeAnnotationFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(typeAnnotationFullStart, node.callSignature.typeAnnotation, TypeScript.DiagnosticCode.Type_annotation_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + GrammarCheckerWalker.prototype.visitSourceUnit = function (node) { if (this.checkFunctionOverloads(node, node.moduleElements) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { this.skip(node); @@ -27343,7 +27397,9 @@ var TypeScript; var start = (new Date()).getTime(); var result = func(); var end = (new Date()).getTime(); - logger.log(funcDescription + " completed in " + (end - start) + " msec"); + if (logger.information()) { + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + } return result; } TypeScript.timeFunction = timeFunction; @@ -27368,8 +27424,8 @@ var TypeScript; this._lineMap = null; this._declASTMap = []; this._astDeclMap = []; - this._isExternalModule = undefined; this._amdDependencies = undefined; + this._externalModuleIndicatorSpan = undefined; } Document.prototype.invalidate = function () { this._declASTMap.length = 0; @@ -27394,39 +27450,22 @@ var TypeScript; this._lineMap = syntaxTree.lineMap(); var sourceUnit = syntaxTree.sourceUnit(); - var leadingComments = this.getLeadingComments(sourceUnit); + var leadingTrivia = sourceUnit.leadingTrivia(); - this._isExternalModule = this.hasImplicitImport(leadingComments) || this.hasTopLevelImportOrExport(sourceUnit); + this._externalModuleIndicatorSpan = this.getImplicitImportSpan(leadingTrivia) || this.getTopLevelImportOrExportSpan(sourceUnit); var amdDependencies = []; - for (var i = 0, n = leadingComments.length; i < n; i++) { - var trivia = leadingComments[i]; - var amdDependency = this.getAmdDependency(trivia.fullText()); - if (amdDependency) { - amdDependencies.push(amdDependency); - } - } - - this._amdDependencies = amdDependencies; - }; - - Document.prototype.getLeadingComments = function (node) { - var firstToken = node.firstToken(); - var result = []; - - if (firstToken.hasLeadingComment()) { - var leadingTrivia = firstToken.leadingTrivia(); - - for (var i = 0, n = leadingTrivia.count(); i < n; i++) { - var trivia = leadingTrivia.syntaxTriviaAt(i); - - if (trivia.isComment()) { - result.push(trivia); + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.isComment()) { + var amdDependency = this.getAmdDependency(trivia.fullText()); + if (amdDependency) { + amdDependencies.push(amdDependency); } } } - return result; + this._amdDependencies = amdDependencies; }; Document.prototype.getAmdDependency = function (comment) { @@ -27435,49 +27474,60 @@ var TypeScript; return match ? match[2] : null; }; - Document.prototype.hasImplicitImport = function (sourceUnitLeadingComments) { - for (var i = 0, n = sourceUnitLeadingComments.length; i < n; i++) { - var trivia = sourceUnitLeadingComments[i]; + Document.prototype.getImplicitImportSpan = function (sourceUnitLeadingTrivia) { + var position = 0; - if (this.getImplicitImport(trivia.fullText())) { - return true; + for (var i = 0, n = sourceUnitLeadingTrivia.count(); i < n; i++) { + var trivia = sourceUnitLeadingTrivia.syntaxTriviaAt(i); + + if (trivia.isComment()) { + var span = this.getImplicitImportSpanWorker(trivia, position); + if (span) { + return span; + } } + + position += trivia.fullWidth(); } - return false; + return null; }; - Document.prototype.getImplicitImport = function (comment) { + Document.prototype.getImplicitImportSpanWorker = function (trivia, position) { var implicitImportRegEx = /^(\/\/\/\s*/gim; - var match = implicitImportRegEx.exec(comment); + var match = implicitImportRegEx.exec(trivia.fullText()); if (match) { - return true; + return new TypeScript.TextSpan(position, trivia.fullWidth()); } - return false; + return null; }; - Document.prototype.hasTopLevelImportOrExport = function (node) { + Document.prototype.getTopLevelImportOrExportSpan = function (node) { var firstToken; + var position = 0; for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { var moduleElement = node.moduleElements.childAt(i); firstToken = moduleElement.firstToken(); if (firstToken !== null && firstToken.tokenKind === 47 /* ExportKeyword */) { - return true; + return new TypeScript.TextSpan(position + firstToken.leadingTriviaWidth(), firstToken.width()); } if (moduleElement.kind() === 133 /* ImportDeclaration */) { var importDecl = moduleElement; if (importDecl.moduleReference.kind() === 245 /* ExternalModuleReference */) { - return true; + return new TypeScript.TextSpan(position + importDecl.leadingTriviaWidth(), importDecl.width()); } } + + position += moduleElement.fullWidth(); } - return false; + return null; + ; }; Document.prototype.sourceUnit = function () { @@ -27514,12 +27564,16 @@ var TypeScript; }; Document.prototype.isExternalModule = function () { - if (this._isExternalModule === undefined) { + return this.externalModuleIndicatorSpan() !== null; + }; + + Document.prototype.externalModuleIndicatorSpan = function () { + if (this._externalModuleIndicatorSpan === undefined) { this.syntaxTree(); - TypeScript.Debug.assert(this._isExternalModule !== undefined); + TypeScript.Debug.assert(this._externalModuleIndicatorSpan !== undefined); } - return this._isExternalModule; + return this._externalModuleIndicatorSpan; }; Document.prototype.amdDependencies = function () { @@ -27553,7 +27607,7 @@ var TypeScript; if (!this._bloomFilter) { var identifiers = TypeScript.createIntrinsicsObject(); var pre = function (cur) { - if (TypeScript.isValidAstNode(cur)) { + if (TypeScript.ASTHelpers.isValidAstNode(cur)) { if (cur.kind() === 11 /* IdentifierName */) { var nodeText = cur.valueText(); @@ -27859,246 +27913,261 @@ var TypeScript; })(StringHashTable); TypeScript.IdentiferNameHashTable = IdentiferNameHashTable; })(TypeScript || (TypeScript = {})); + var TypeScript; (function (TypeScript) { - function scriptIsElided(sourceUnit) { - return TypeScript.isDTSFile(sourceUnit.fileName()) || moduleMembersAreElided(sourceUnit.moduleElements); - } - TypeScript.scriptIsElided = scriptIsElided; + (function (ASTHelpers) { + function scriptIsElided(sourceUnit) { + return TypeScript.isDTSFile(sourceUnit.fileName()) || moduleMembersAreElided(sourceUnit.moduleElements); + } + ASTHelpers.scriptIsElided = scriptIsElided; - function moduleIsElided(declaration) { - return TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) || moduleMembersAreElided(declaration.moduleElements); - } - TypeScript.moduleIsElided = moduleIsElided; + function moduleIsElided(declaration) { + return TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) || moduleMembersAreElided(declaration.moduleElements); + } + ASTHelpers.moduleIsElided = moduleIsElided; - function moduleMembersAreElided(members) { - for (var i = 0, n = members.childCount(); i < n; i++) { - var member = members.childAt(i); + function moduleMembersAreElided(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); - if (member.kind() === 130 /* ModuleDeclaration */) { - if (!moduleIsElided(member)) { + if (member.kind() === 130 /* ModuleDeclaration */) { + if (!moduleIsElided(member)) { + return false; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */) { return false; } - } else if (member.kind() !== 128 /* InterfaceDeclaration */) { - return false; } - } - return true; - } - - function enumIsElided(declaration) { - if (TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { return true; } - return false; - } - TypeScript.enumIsElided = enumIsElided; - - function importDeclarationIsElided(importDeclAST, semanticInfoChain, compilationSettings) { - if (typeof compilationSettings === "undefined") { compilationSettings = null; } - var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; - var importDecl = semanticInfoChain.getDeclForAST(importDeclAST); - var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); - var isAmdCodeGen = compilationSettings && compilationSettings.moduleGenTarget() == 2 /* Asynchronous */; - - if (!isExternalModuleReference || isExported || !isAmdCodeGen) { - var importSymbol = importDecl.getSymbol(); - if (importDeclAST.moduleReference.kind() !== 245 /* ExternalModuleReference */) { - if (importSymbol.getExportAssignedValueSymbol()) { - return true; - } - var containerSymbol = importSymbol.getExportAssignedContainerSymbol(); - if (containerSymbol && containerSymbol.getInstanceSymbol()) { - return true; - } + function enumIsElided(declaration) { + if (TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + return true; } - return importSymbol.isUsedAsValue(); + return false; } + ASTHelpers.enumIsElided = enumIsElided; - return false; - } - TypeScript.importDeclarationIsElided = importDeclarationIsElided; + function isValidAstNode(ast) { + if (!ast) + return false; - function isValidAstNode(ast) { - if (!ast) - return false; + if (ast.start() === -1 || ast.end() === -1) + return false; - if (ast.start() === -1 || ast.end() === -1) - return false; + return true; + } + ASTHelpers.isValidAstNode = isValidAstNode; - return true; - } - TypeScript.isValidAstNode = isValidAstNode; + function getAstAtPosition(script, pos, useTrailingTriviaAsLimChar, forceInclusive) { + if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } + if (typeof forceInclusive === "undefined") { forceInclusive = false; } + var top = null; - function getAstAtPosition(script, pos, useTrailingTriviaAsLimChar, forceInclusive) { - if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } - if (typeof forceInclusive === "undefined") { forceInclusive = false; } - var top = null; + var pre = function (cur, walker) { + if (isValidAstNode(cur)) { + var isInvalid1 = cur.kind() === 149 /* ExpressionStatement */ && cur.width() === 0; - var pre = function (cur, walker) { - if (isValidAstNode(cur)) { - var isInvalid1 = cur.kind() === 149 /* ExpressionStatement */ && cur.width() === 0; + if (isInvalid1) { + walker.options.goChildren = false; + } else { + var inclusive = forceInclusive || cur.kind() === 11 /* IdentifierName */ || cur.kind() === 212 /* MemberAccessExpression */ || cur.kind() === 121 /* QualifiedName */ || cur.kind() === 224 /* VariableDeclaration */ || cur.kind() === 225 /* VariableDeclarator */ || cur.kind() === 213 /* InvocationExpression */ || pos === script.end() + script.trailingTriviaWidth(); - if (isInvalid1) { - walker.options.goChildren = false; - } else { - var inclusive = forceInclusive || cur.kind() === 11 /* IdentifierName */ || cur.kind() === 212 /* MemberAccessExpression */ || cur.kind() === 121 /* QualifiedName */ || cur.kind() === 224 /* VariableDeclaration */ || cur.kind() === 225 /* VariableDeclarator */ || cur.kind() === 213 /* InvocationExpression */ || pos === script.end() + script.trailingTriviaWidth(); - - var minChar = cur.start(); - var limChar = cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0) + (inclusive ? 1 : 0); - if (pos >= minChar && pos < limChar) { - if ((cur.kind() !== 1 /* List */ && cur.kind() !== 2 /* SeparatedList */) || cur.end() > cur.start()) { - if (top === null) { - top = cur; - } else if (cur.start() >= top.start() && (cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0)) <= (top.end() + (useTrailingTriviaAsLimChar ? top.trailingTriviaWidth() : 0))) { - if (top.width() !== 0 || cur.width() !== 0) { + var minChar = cur.start(); + var limChar = cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0) + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + if ((cur.kind() !== 1 /* List */ && cur.kind() !== 2 /* SeparatedList */) || cur.end() > cur.start()) { + if (top === null) { top = cur; + } else if (cur.start() >= top.start() && (cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0)) <= (top.end() + (useTrailingTriviaAsLimChar ? top.trailingTriviaWidth() : 0))) { + if (top.width() !== 0 || cur.width() !== 0) { + top = cur; + } } } } - } - walker.options.goChildren = (minChar <= pos && pos <= limChar); + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + }; + + TypeScript.getAstWalkerFactory().walk(script, pre); + return top; + } + ASTHelpers.getAstAtPosition = getAstAtPosition; + + function getExtendsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 230 /* ExtendsHeritageClause */; + }); + } + ASTHelpers.getExtendsHeritageClause = getExtendsHeritageClause; + + function getImplementsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 231 /* ImplementsHeritageClause */; + }); + } + ASTHelpers.getImplementsHeritageClause = getImplementsHeritageClause; + + function isCallExpression(ast) { + return (ast && ast.kind() === 213 /* InvocationExpression */) || (ast && ast.kind() === 216 /* ObjectCreationExpression */); + } + ASTHelpers.isCallExpression = isCallExpression; + + function isCallExpressionTarget(ast) { + if (!ast) { + return false; + } + + var current = ast; + + while (current && current.parent) { + if (current.parent.kind() === 212 /* MemberAccessExpression */ && current.parent.name === current) { + current = current.parent; + continue; + } + + break; + } + + if (current && current.parent) { + if (current.parent.kind() === 213 /* InvocationExpression */ || current.parent.kind() === 216 /* ObjectCreationExpression */) { + return current === current.parent.expression; } } - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - return top; - } - TypeScript.getAstAtPosition = getAstAtPosition; - - function getExtendsHeritageClause(clauses) { - if (!clauses) { - return null; + return false; } + ASTHelpers.isCallExpressionTarget = isCallExpressionTarget; - return clauses.firstOrDefault(function (c) { - return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 230 /* ExtendsHeritageClause */; - }); - } - TypeScript.getExtendsHeritageClause = getExtendsHeritageClause; + function isNameOfSomeDeclaration(ast) { + if (ast === null || ast.parent === null) { + return false; + } + if (ast.kind() !== 11 /* IdentifierName */) { + return false; + } - function getImplementsHeritageClause(clauses) { - if (!clauses) { - return null; - } + switch (ast.parent.kind()) { + case 131 /* ClassDeclaration */: + return ast.parent.identifier === ast; + case 128 /* InterfaceDeclaration */: + return ast.parent.identifier === ast; + case 132 /* EnumDeclaration */: + return ast.parent.identifier === ast; + case 130 /* ModuleDeclaration */: + return ast.parent.name === ast || ast.parent.stringLiteral === ast; + case 225 /* VariableDeclarator */: + return ast.parent.propertyName === ast; + case 129 /* FunctionDeclaration */: + return ast.parent.identifier === ast; + case 135 /* MemberFunctionDeclaration */: + return ast.parent.propertyName === ast; + case 242 /* Parameter */: + return ast.parent.identifier === ast; + case 238 /* TypeParameter */: + return ast.parent.identifier === ast; + case 240 /* SimplePropertyAssignment */: + return ast.parent.propertyName === ast; + case 241 /* FunctionPropertyAssignment */: + return ast.parent.propertyName === ast; + case 243 /* EnumElement */: + return ast.parent.propertyName === ast; + case 133 /* ImportDeclaration */: + return ast.parent.identifier === ast; + } - return clauses.firstOrDefault(function (c) { - return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 231 /* ImplementsHeritageClause */; - }); - } - TypeScript.getImplementsHeritageClause = getImplementsHeritageClause; - - function isCallExpression(ast) { - return (ast && ast.kind() === 213 /* InvocationExpression */) || (ast && ast.kind() === 216 /* ObjectCreationExpression */); - } - TypeScript.isCallExpression = isCallExpression; - - function isCallExpressionTarget(ast) { - if (!ast) { return false; } - var current = ast; + function isDeclarationASTOrDeclarationNameAST(ast) { + return isNameOfSomeDeclaration(ast) || isDeclarationAST(ast); + } + ASTHelpers.isDeclarationASTOrDeclarationNameAST = isDeclarationASTOrDeclarationNameAST; + + function getEnclosingParameterForInitializer(ast) { + var current = ast; + while (current) { + switch (current.kind()) { + case 232 /* EqualsValueClause */: + if (current.parent && current.parent.kind() === 242 /* Parameter */) { + return current.parent; + } + break; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } - while (current && current.parent) { - if (current.parent.kind() === 212 /* MemberAccessExpression */ && current.parent.name === current) { current = current.parent; - continue; + } + return null; + } + ASTHelpers.getEnclosingParameterForInitializer = getEnclosingParameterForInitializer; + + function getEnclosingMemberVariableDeclaration(ast) { + var current = ast; + + while (current) { + switch (current.kind()) { + case 136 /* MemberVariableDeclaration */: + return current; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + current = current.parent; } - break; + return null; } + ASTHelpers.getEnclosingMemberVariableDeclaration = getEnclosingMemberVariableDeclaration; - if (current && current.parent) { - if (current.parent.kind() === 213 /* InvocationExpression */ || current.parent.kind() === 216 /* ObjectCreationExpression */) { - return current === current.parent.expression; + function isNameOfFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 129 /* FunctionDeclaration */ && ast.parent.identifier === ast; + } + ASTHelpers.isNameOfFunction = isNameOfFunction; + + function isNameOfMemberFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 135 /* MemberFunctionDeclaration */ && ast.parent.propertyName === ast; + } + ASTHelpers.isNameOfMemberFunction = isNameOfMemberFunction; + + function isNameOfMemberAccessExpression(ast) { + if (ast && ast.parent && ast.parent.kind() === 212 /* MemberAccessExpression */ && ast.parent.name === ast) { + return true; } - } - return false; - } - TypeScript.isCallExpressionTarget = isCallExpressionTarget; - - function isNameOfSomeDeclaration(ast) { - if (ast === null || ast.parent === null) { return false; } - if (ast.kind() !== 11 /* IdentifierName */) { + ASTHelpers.isNameOfMemberAccessExpression = isNameOfMemberAccessExpression; + + function isRightSideOfQualifiedName(ast) { + if (ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast) { + return true; + } + return false; } + ASTHelpers.isRightSideOfQualifiedName = isRightSideOfQualifiedName; - switch (ast.parent.kind()) { - case 131 /* ClassDeclaration */: - return ast.parent.identifier === ast; - case 128 /* InterfaceDeclaration */: - return ast.parent.identifier === ast; - case 132 /* EnumDeclaration */: - return ast.parent.identifier === ast; - case 130 /* ModuleDeclaration */: - return ast.parent.name === ast || ast.parent.stringLiteral === ast; - case 225 /* VariableDeclarator */: - return ast.parent.propertyName === ast; - case 129 /* FunctionDeclaration */: - return ast.parent.identifier === ast; - case 135 /* MemberFunctionDeclaration */: - return ast.parent.propertyName === ast; - case 242 /* Parameter */: - return ast.parent.identifier === ast; - case 238 /* TypeParameter */: - return ast.parent.identifier === ast; - case 240 /* SimplePropertyAssignment */: - return ast.parent.propertyName === ast; - case 241 /* FunctionPropertyAssignment */: - return ast.parent.propertyName === ast; - case 243 /* EnumElement */: - return ast.parent.propertyName === ast; - case 133 /* ImportDeclaration */: - return ast.parent.identifier === ast; - } - - return false; - } - - function isDeclarationASTOrDeclarationNameAST(ast) { - return isNameOfSomeDeclaration(ast) || isDeclarationAST(ast); - } - TypeScript.isDeclarationASTOrDeclarationNameAST = isDeclarationASTOrDeclarationNameAST; - - function isNameOfFunction(ast) { - return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 129 /* FunctionDeclaration */ && ast.parent.identifier === ast; - } - TypeScript.isNameOfFunction = isNameOfFunction; - - function isNameOfMemberFunction(ast) { - return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 135 /* MemberFunctionDeclaration */ && ast.parent.propertyName === ast; - } - TypeScript.isNameOfMemberFunction = isNameOfMemberFunction; - - function isNameOfMemberAccessExpression(ast) { - if (ast && ast.parent && ast.parent.kind() === 212 /* MemberAccessExpression */ && ast.parent.name === ast) { - return true; - } - - return false; - } - TypeScript.isNameOfMemberAccessExpression = isNameOfMemberAccessExpression; - - function isRightSideOfQualifiedName(ast) { - if (ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast) { - return true; - } - - return false; - } - TypeScript.isRightSideOfQualifiedName = isRightSideOfQualifiedName; - - (function (Parameters) { - function fromIdentifier(id) { + function parametersFromIdentifier(id) { return { length: 1, lastParameterIsRest: function () { @@ -28122,9 +28191,9 @@ var TypeScript; } }; } - Parameters.fromIdentifier = fromIdentifier; + ASTHelpers.parametersFromIdentifier = parametersFromIdentifier; - function fromParameter(parameter) { + function parametersFromParameter(parameter) { return { length: 1, lastParameterIsRest: function () { @@ -28138,7 +28207,7 @@ var TypeScript; return parameter.identifier; }, typeAt: function (index) { - return TypeScript.getType(parameter); + return getType(parameter); }, initializerAt: function (index) { return parameter.equalsValueClause; @@ -28148,13 +28217,13 @@ var TypeScript; } }; } - Parameters.fromParameter = fromParameter; + ASTHelpers.parametersFromParameter = parametersFromParameter; function parameterIsOptional(parameter) { return parameter.questionToken !== null || parameter.equalsValueClause !== null; } - function fromParameterList(list) { + function parametersFromParameterList(list) { return { length: list.parameters.nonSeparatorCount(), lastParameterIsRest: function () { @@ -28168,7 +28237,7 @@ var TypeScript; return list.parameters.nonSeparatorAt(index).identifier; }, typeAt: function (index) { - return TypeScript.getType(list.parameters.nonSeparatorAt(index)); + return getType(list.parameters.nonSeparatorAt(index)); }, initializerAt: function (index) { return list.parameters.nonSeparatorAt(index).equalsValueClause; @@ -28178,240 +28247,251 @@ var TypeScript; } }; } - Parameters.fromParameterList = fromParameterList; - })(TypeScript.Parameters || (TypeScript.Parameters = {})); - var Parameters = TypeScript.Parameters; + ASTHelpers.parametersFromParameterList = parametersFromParameterList; - function isDeclarationAST(ast) { - switch (ast.kind()) { - case 225 /* VariableDeclarator */: - return getVariableStatement(ast) !== null; + function isDeclarationAST(ast) { + switch (ast.kind()) { + case 225 /* VariableDeclarator */: + return getVariableStatement(ast) !== null; - case 133 /* ImportDeclaration */: - case 131 /* ClassDeclaration */: - case 128 /* InterfaceDeclaration */: - case 242 /* Parameter */: - case 219 /* SimpleArrowFunctionExpression */: - case 218 /* ParenthesizedArrowFunctionExpression */: - case 144 /* IndexSignature */: - case 129 /* FunctionDeclaration */: - case 130 /* ModuleDeclaration */: - case 124 /* ArrayType */: - case 122 /* ObjectType */: - case 238 /* TypeParameter */: - case 137 /* ConstructorDeclaration */: - case 135 /* MemberFunctionDeclaration */: - case 139 /* GetAccessor */: - case 140 /* SetAccessor */: - case 136 /* MemberVariableDeclaration */: - case 138 /* IndexMemberDeclaration */: - case 132 /* EnumDeclaration */: - case 243 /* EnumElement */: - case 240 /* SimplePropertyAssignment */: - case 241 /* FunctionPropertyAssignment */: - case 222 /* FunctionExpression */: - case 142 /* CallSignature */: - case 143 /* ConstructSignature */: - case 145 /* MethodSignature */: - case 141 /* PropertySignature */: - return true; - default: - return false; + case 133 /* ImportDeclaration */: + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 242 /* Parameter */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 144 /* IndexSignature */: + case 129 /* FunctionDeclaration */: + case 130 /* ModuleDeclaration */: + case 124 /* ArrayType */: + case 122 /* ObjectType */: + case 238 /* TypeParameter */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + case 138 /* IndexMemberDeclaration */: + case 132 /* EnumDeclaration */: + case 243 /* EnumElement */: + case 240 /* SimplePropertyAssignment */: + case 241 /* FunctionPropertyAssignment */: + case 222 /* FunctionExpression */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + case 145 /* MethodSignature */: + case 141 /* PropertySignature */: + return true; + default: + return false; + } } - } - TypeScript.isDeclarationAST = isDeclarationAST; + ASTHelpers.isDeclarationAST = isDeclarationAST; - function docComments(ast) { - if (isDeclarationAST(ast)) { - var preComments = ast.kind() === 225 /* VariableDeclarator */ ? getVariableStatement(ast).preComments() : ast.preComments(); + function docComments(ast) { + if (isDeclarationAST(ast)) { + var preComments = ast.kind() === 225 /* VariableDeclarator */ ? getVariableStatement(ast).preComments() : ast.preComments(); - if (preComments && preComments.length > 0) { - var preCommentsLength = preComments.length; - var docComments = new Array(); - for (var i = preCommentsLength - 1; i >= 0; i--) { - if (isDocComment(preComments[i])) { - docComments.push(preComments[i]); - continue; + if (preComments && preComments.length > 0) { + var preCommentsLength = preComments.length; + var docComments = new Array(); + for (var i = preCommentsLength - 1; i >= 0; i--) { + if (isDocComment(preComments[i])) { + docComments.push(preComments[i]); + continue; + } + + break; } - break; + return docComments.reverse(); + } + } + + return TypeScript.sentinelEmptyArray; + } + ASTHelpers.docComments = docComments; + + function isDocComment(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + var fullText = comment.fullText(); + return fullText.charAt(2) === "*" && fullText.charAt(3) !== "/"; + } + + return false; + } + + function getParameterList(ast) { + if (ast) { + switch (ast.kind()) { + case 137 /* ConstructorDeclaration */: + return getParameterList(ast.callSignature); + case 129 /* FunctionDeclaration */: + return getParameterList(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getParameterList(ast.callSignature); + case 143 /* ConstructSignature */: + return getParameterList(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getParameterList(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getParameterList(ast.callSignature); + case 222 /* FunctionExpression */: + return getParameterList(ast.callSignature); + case 145 /* MethodSignature */: + return getParameterList(ast.callSignature); + case 125 /* ConstructorType */: + return ast.parameterList; + case 123 /* FunctionType */: + return ast.parameterList; + case 142 /* CallSignature */: + return ast.parameterList; + case 139 /* GetAccessor */: + return ast.parameterList; + case 140 /* SetAccessor */: + return ast.parameterList; + } + } + + return null; + } + ASTHelpers.getParameterList = getParameterList; + + function getType(ast) { + if (ast) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + return getType(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getType(ast.callSignature); + case 143 /* ConstructSignature */: + return getType(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getType(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getType(ast.callSignature); + case 222 /* FunctionExpression */: + return getType(ast.callSignature); + case 145 /* MethodSignature */: + return getType(ast.callSignature); + case 142 /* CallSignature */: + return getType(ast.typeAnnotation); + case 144 /* IndexSignature */: + return getType(ast.typeAnnotation); + case 141 /* PropertySignature */: + return getType(ast.typeAnnotation); + case 139 /* GetAccessor */: + return getType(ast.typeAnnotation); + case 242 /* Parameter */: + return getType(ast.typeAnnotation); + case 136 /* MemberVariableDeclaration */: + return getType(ast.variableDeclarator); + case 225 /* VariableDeclarator */: + return getType(ast.typeAnnotation); + case 236 /* CatchClause */: + return getType(ast.typeAnnotation); + case 125 /* ConstructorType */: + return ast.type; + case 123 /* FunctionType */: + return ast.type; + case 244 /* TypeAnnotation */: + return ast.type; + } + } + + return null; + } + ASTHelpers.getType = getType; + + function getVariableStatement(variableDeclarator) { + if (variableDeclarator && variableDeclarator.parent && variableDeclarator.parent.parent && variableDeclarator.parent.parent.parent && variableDeclarator.parent.kind() === 2 /* SeparatedList */ && variableDeclarator.parent.parent.kind() === 224 /* VariableDeclaration */ && variableDeclarator.parent.parent.parent.kind() === 148 /* VariableStatement */) { + return variableDeclarator.parent.parent.parent; + } + + return null; + } + + function getVariableDeclaratorModifiers(variableDeclarator) { + var variableStatement = getVariableStatement(variableDeclarator); + return variableStatement ? variableStatement.modifiers : TypeScript.sentinelEmptyArray; + } + ASTHelpers.getVariableDeclaratorModifiers = getVariableDeclaratorModifiers; + + function isIntegerLiteralAST(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.kind() === 13 /* NumericLiteral */ && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + ASTHelpers.isIntegerLiteralAST = isIntegerLiteralAST; + + function getEnclosingModuleDeclaration(ast) { + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + return ast; } - return docComments.reverse(); - } - } - - return TypeScript.sentinelEmptyArray; - } - TypeScript.docComments = docComments; - - function isDocComment(comment) { - if (comment.kind() === 6 /* MultiLineCommentTrivia */) { - var fullText = comment.fullText(); - return fullText.charAt(2) === "*" && fullText.charAt(3) !== "/"; - } - - return false; - } - - function getParameterList(ast) { - if (ast) { - switch (ast.kind()) { - case 137 /* ConstructorDeclaration */: - return ast.parameterList; - case 129 /* FunctionDeclaration */: - return getParameterList(ast.callSignature); - case 218 /* ParenthesizedArrowFunctionExpression */: - return getParameterList(ast.callSignature); - case 143 /* ConstructSignature */: - return getParameterList(ast.callSignature); - case 135 /* MemberFunctionDeclaration */: - return getParameterList(ast.callSignature); - case 241 /* FunctionPropertyAssignment */: - return getParameterList(ast.callSignature); - case 222 /* FunctionExpression */: - return getParameterList(ast.callSignature); - case 145 /* MethodSignature */: - return getParameterList(ast.callSignature); - case 125 /* ConstructorType */: - return ast.parameterList; - case 123 /* FunctionType */: - return ast.parameterList; - case 142 /* CallSignature */: - return ast.parameterList; - case 139 /* GetAccessor */: - return ast.parameterList; - case 140 /* SetAccessor */: - return ast.parameterList; - } - } - - return null; - } - TypeScript.getParameterList = getParameterList; - - function getType(ast) { - if (ast) { - switch (ast.kind()) { - case 129 /* FunctionDeclaration */: - return getType(ast.callSignature); - case 218 /* ParenthesizedArrowFunctionExpression */: - return getType(ast.callSignature); - case 143 /* ConstructSignature */: - return getType(ast.callSignature); - case 135 /* MemberFunctionDeclaration */: - return getType(ast.callSignature); - case 241 /* FunctionPropertyAssignment */: - return getType(ast.callSignature); - case 222 /* FunctionExpression */: - return getType(ast.callSignature); - case 145 /* MethodSignature */: - return getType(ast.callSignature); - case 142 /* CallSignature */: - return getType(ast.typeAnnotation); - case 144 /* IndexSignature */: - return getType(ast.typeAnnotation); - case 141 /* PropertySignature */: - return getType(ast.typeAnnotation); - case 139 /* GetAccessor */: - return getType(ast.typeAnnotation); - case 242 /* Parameter */: - return getType(ast.typeAnnotation); - case 136 /* MemberVariableDeclaration */: - return getType(ast.variableDeclarator); - case 225 /* VariableDeclarator */: - return getType(ast.typeAnnotation); - case 236 /* CatchClause */: - return getType(ast.typeAnnotation); - case 125 /* ConstructorType */: - return ast.type; - case 123 /* FunctionType */: - return ast.type; - case 244 /* TypeAnnotation */: - return ast.type; - } - } - - return null; - } - TypeScript.getType = getType; - - function getVariableStatement(variableDeclarator) { - if (variableDeclarator && variableDeclarator.parent && variableDeclarator.parent.parent && variableDeclarator.parent.parent.parent && variableDeclarator.parent.kind() === 2 /* SeparatedList */ && variableDeclarator.parent.parent.kind() === 224 /* VariableDeclaration */ && variableDeclarator.parent.parent.parent.kind() === 148 /* VariableStatement */) { - return variableDeclarator.parent.parent.parent; - } - - return null; - } - - function getVariableDeclaratorModifiers(variableDeclarator) { - var variableStatement = getVariableStatement(variableDeclarator); - return variableStatement ? variableStatement.modifiers : TypeScript.sentinelEmptyArray; - } - TypeScript.getVariableDeclaratorModifiers = getVariableDeclaratorModifiers; - - function isIntegerLiteralAST(expression) { - if (expression) { - switch (expression.kind()) { - case 164 /* PlusExpression */: - case 165 /* NegateExpression */: - expression = expression.operand; - return expression.kind() === 13 /* NumericLiteral */ && TypeScript.IntegerUtilities.isInteger(expression.text()); - - case 13 /* NumericLiteral */: - var text = expression.text(); - return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); - } - } - - return false; - } - TypeScript.isIntegerLiteralAST = isIntegerLiteralAST; - - function getEnclosingModuleDeclaration(ast) { - while (ast) { - if (ast.kind() === 130 /* ModuleDeclaration */) { - return ast; + ast = ast.parent; } - ast = ast.parent; + return null; } + ASTHelpers.getEnclosingModuleDeclaration = getEnclosingModuleDeclaration; - return null; - } - TypeScript.getEnclosingModuleDeclaration = getEnclosingModuleDeclaration; + function isLastNameOfModule(ast, astName) { + if (ast) { + if (ast.stringLiteral) { + return astName === ast.stringLiteral; + } else { + var moduleNames = TypeScript.getModuleNames(ast.name); + var nameIndex = moduleNames.indexOf(astName); - function isLastNameOfModule(ast, astName) { - if (ast) { - if (ast.stringLiteral) { - return astName === ast.stringLiteral; + return nameIndex === (moduleNames.length - 1); + } + } + + return false; + } + ASTHelpers.isLastNameOfModule = isLastNameOfModule; + + function isAnyNameOfModule(ast, astName) { + if (ast) { + if (ast.stringLiteral) { + return ast.stringLiteral === astName; + } else { + var moduleNames = TypeScript.getModuleNames(ast.name); + var nameIndex = moduleNames.indexOf(astName); + + return nameIndex >= 0; + } + } + + return false; + } + ASTHelpers.isAnyNameOfModule = isAnyNameOfModule; + + function getNameOfIdenfierOrQualifiedName(name) { + if (name.kind() === 11 /* IdentifierName */) { + return name.text(); } else { - var moduleNames = TypeScript.getModuleNames(ast.name); - var nameIndex = moduleNames.indexOf(astName); - - return nameIndex === (moduleNames.length - 1); + TypeScript.Debug.assert(name.kind() == 121 /* QualifiedName */); + var dotExpr = name; + return getNameOfIdenfierOrQualifiedName(dotExpr.left) + "." + getNameOfIdenfierOrQualifiedName(dotExpr.right); } } - - return false; - } - TypeScript.isLastNameOfModule = isLastNameOfModule; - - function isAnyNameOfModule(ast, astName) { - if (ast) { - if (ast.stringLiteral) { - return ast.stringLiteral === astName; - } else { - var moduleNames = TypeScript.getModuleNames(ast.name); - var nameIndex = moduleNames.indexOf(astName); - - return nameIndex >= 0; - } - } - - return false; - } - TypeScript.isAnyNameOfModule = isAnyNameOfModule; + ASTHelpers.getNameOfIdenfierOrQualifiedName = getNameOfIdenfierOrQualifiedName; + })(TypeScript.ASTHelpers || (TypeScript.ASTHelpers = {})); + var ASTHelpers = TypeScript.ASTHelpers; })(TypeScript || (TypeScript = {})); var TypeScript; (function (TypeScript) { @@ -28619,7 +28699,7 @@ var TypeScript; } function walkConstructorDeclarationChildren(preAst, walker) { - walker.walk(preAst.parameterList); + walker.walk(preAst.callSignature); walker.walk(preAst.block); } @@ -29412,9 +29492,17 @@ var TypeScript; var settings = compiler.compilationSettings(); this._settings = settings; - if (settings.moduleGenTarget() === 0 /* Unspecified */ && compiler._isDynamicModuleCompilation()) { - this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_compile_external_modules_unless_the_module_flag_is_provided, null); - return; + if (settings.moduleGenTarget() === 0 /* Unspecified */) { + var fileNames = compiler.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = compiler.getDocument(fileNames[i]); + if (!document.isDeclareFile() && document.isExternalModule()) { + var errorSpan = document.externalModuleIndicatorSpan(); + this._diagnostic = new TypeScript.Diagnostic(document.fileName, document.lineMap(), errorSpan.start(), errorSpan.length(), TypeScript.DiagnosticCode.Cannot_compile_external_modules_unless_the_module_flag_is_provided); + + return; + } + } } if (!settings.mapSourceFiles()) { @@ -29496,7 +29584,7 @@ var TypeScript; updatedPath = true; if (j === 0) { - if (this._outputDirectory || this._sourceRootDirectory || (this._sourceMapRootDirectory && (!this._sharedOutputFile || compiler._isDynamicModuleCompilation()))) { + if (this._outputDirectory || this._sourceMapRootDirectory) { this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_find_the_common_subdirectory_path_for_the_input_files, null); return; } @@ -29573,10 +29661,10 @@ var TypeScript; this.sourceMapper = null; this.captureThisStmtString = "var _this = this;"; this.declStack = []; - this.exportAssignmentIdentifier = null; + this.exportAssignment = null; this.inWithBlock = false; this.document = null; - this.copyrightElement = null; + this.detachedCommentsElement = null; } Emitter.prototype.pushDecl = function (decl) { if (decl) { @@ -29596,12 +29684,12 @@ var TypeScript; return enclosingDecl; }; - Emitter.prototype.setExportAssignmentIdentifier = function (id) { - this.exportAssignmentIdentifier = id; + Emitter.prototype.setExportAssignment = function (exportAssignment) { + this.exportAssignment = exportAssignment; }; - Emitter.prototype.getExportAssignmentIdentifier = function () { - return this.exportAssignmentIdentifier; + Emitter.prototype.getExportAssignment = function () { + return this.exportAssignment; }; Emitter.prototype.setDocument = function (document) { @@ -29609,14 +29697,46 @@ var TypeScript; }; Emitter.prototype.shouldEmitImportDeclaration = function (importDeclAST) { - return TypeScript.importDeclarationIsElided(importDeclAST, this.semanticInfoChain, this.emitOptions.compilationSettings()); + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + if (isExternalModuleReference && !isExported && isAmdCodeGen) { + return false; + } + + var importSymbol = importDecl.getSymbol(); + if (importSymbol.isUsedAsValue()) { + return true; + } + + if (importDeclAST.moduleReference.kind() !== 245 /* ExternalModuleReference */) { + var canBeUsedExternally = isExported || importSymbol.typeUsedExternally() || importSymbol.isUsedInExportedAlias(); + if (!canBeUsedExternally && !this.document.isExternalModule()) { + canBeUsedExternally = TypeScript.hasFlag(importDecl.getParentDecl().kind, 1 /* Script */ | 32 /* DynamicModule */); + } + + if (canBeUsedExternally) { + if (importSymbol.getExportAssignedValueSymbol()) { + return true; + } + + var containerSymbol = importSymbol.getExportAssignedContainerSymbol(); + if (containerSymbol && containerSymbol.getInstanceSymbol()) { + return true; + } + } + } + + return false; }; Emitter.prototype.emitImportDeclaration = function (importDeclAST) { var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); - var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() == 2 /* Asynchronous */; + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; this.emitComments(importDeclAST, true); @@ -29631,12 +29751,12 @@ var TypeScript; var usePropertyAssignmentInsteadOfVarDecl = false; var moduleNamePrefix; - if (isExported && (parentKind == 4 /* Container */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */)) { + if (isExported && (parentKind === 4 /* Container */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */)) { if (importSymbol.getExportAssignedTypeSymbol() || importSymbol.getExportAssignedContainerSymbol()) { needsPropertyAssignment = true; } else { var valueSymbol = importSymbol.getExportAssignedValueSymbol(); - if (valueSymbol && (valueSymbol.kind == 65536 /* Method */ || valueSymbol.kind == 16384 /* Function */)) { + if (valueSymbol && (valueSymbol.kind === 65536 /* Method */ || valueSymbol.kind === 16384 /* Function */)) { needsPropertyAssignment = true; } else { usePropertyAssignmentInsteadOfVarDecl = true; @@ -29783,14 +29903,14 @@ var TypeScript; this.writeLineToOutput(""); } - if (!trailing && emitColumn != 0) { + if (!trailing && emitColumn !== 0) { this.emitIndent(); } }; Emitter.prototype.emitComments = function (ast, pre, onlyPinnedOrTripleSlashComments) { - if (typeof onlyPinnedOrTripleSlashComments === "undefined") { onlyPinnedOrTripleSlashComments = false; } var _this = this; + if (typeof onlyPinnedOrTripleSlashComments === "undefined") { onlyPinnedOrTripleSlashComments = false; } if (ast && ast.kind() !== 146 /* Block */) { if (ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ || ast.parent.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { return; @@ -29800,12 +29920,13 @@ var TypeScript; if (pre) { var preComments = ast.preComments(); - if (preComments && ast === this.copyrightElement) { - var copyrightComments = this.getCopyrightComments(); - preComments = preComments.slice(copyrightComments.length); + if (preComments && ast === this.detachedCommentsElement) { + var detachedComments = this.getDetachedComments(ast); + preComments = preComments.slice(detachedComments.length); + this.detachedCommentsElement = null; } - if (onlyPinnedOrTripleSlashComments) { + if (preComments && onlyPinnedOrTripleSlashComments) { preComments = TypeScript.ArrayUtilities.where(preComments, function (c) { return _this.isPinnedOrTripleSlash(c); }); @@ -29946,7 +30067,7 @@ var TypeScript; Emitter.prototype.emitParameterList = function (list) { this.writeToOutput("("); this.emitCommentsArray(list.openParenTrailingComments, true); - this.emitFunctionParameters(TypeScript.Parameters.fromParameterList(list)); + this.emitFunctionParameters(TypeScript.ASTHelpers.parametersFromParameterList(list)); this.writeToOutput(")"); }; @@ -29984,15 +30105,19 @@ var TypeScript; this.indenter.increaseIndent(); - if (parameterList) { - this.emitDefaultValueAssignments(parameterList); - this.emitRestParameterInitializer(parameterList); + if (block) { + this.emitDetachedComments(block.statements); } if (this.shouldCaptureThis(funcDecl)) { this.writeCaptureThisStatement(funcDecl); } + if (parameterList) { + this.emitDefaultValueAssignments(parameterList); + this.emitRestParameterInitializer(parameterList); + } + if (block) { this.emitList(block.statements); this.emitCommentsArray(block.closeBraceLeadingComments, false); @@ -30243,12 +30368,24 @@ var TypeScript; return null; }; - Emitter.prototype.hasChildNameCollision = function (moduleName, childDecls) { + Emitter.prototype.hasChildNameCollision = function (moduleName, parentDecl) { var _this = this; + var childDecls = parentDecl.getChildDecls(); return TypeScript.ArrayUtilities.any(childDecls, function (childDecl) { - if (childDecl.name == moduleName) { - var childAST = _this.semanticInfoChain.getASTForDecl(childDecl); - if (_this.shouldEmit(childAST)) { + var childAST = _this.semanticInfoChain.getASTForDecl(childDecl); + + if (childDecl.kind != 67108864 /* EnumMember */ && _this.shouldEmit(childAST)) { + if (childDecl.name === moduleName) { + if (parentDecl.kind != 8 /* Class */) { + return true; + } + + if (!(childDecl.kind == 65536 /* Method */ || childDecl.kind == 4096 /* Property */ || childDecl.kind == 524288 /* SetAccessor */ || childDecl.kind == 262144 /* GetAccessor */)) { + return true; + } + } + + if (_this.hasChildNameCollision(moduleName, childDecl)) { return true; } } @@ -30261,10 +30398,8 @@ var TypeScript; var moduleDisplayName = moduleDecl.getDisplayName(); moduleDecl = this.getModuleDeclToVerifyChildNameCollision(moduleDecl, changeNameIfAnyDeclarationInContext); - if (moduleDecl) { - var childDecls = moduleDecl.getChildDecls(); - - while (this.hasChildNameCollision(moduleName, childDecls)) { + if (moduleDecl && moduleDecl.kind != 64 /* Enum */) { + while (this.hasChildNameCollision(moduleName, moduleDecl)) { moduleName = "_" + moduleName; moduleDisplayName = "_" + moduleDisplayName; } @@ -30283,7 +30418,7 @@ var TypeScript; }; Emitter.prototype.emitSingleModuleDeclaration = function (moduleDecl, moduleName) { - var isLastName = TypeScript.isLastNameOfModule(moduleDecl, moduleName); + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDecl, moduleName); if (isLastName) { this.emitComments(moduleDecl, true); @@ -30444,11 +30579,11 @@ var TypeScript; }; Emitter.prototype.emitSimpleArrowFunctionExpression = function (arrowFunction) { - this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.Parameters.fromIdentifier(arrowFunction.identifier), arrowFunction.block, arrowFunction.expression); + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), arrowFunction.block, arrowFunction.expression); }; Emitter.prototype.emitParenthesizedArrowFunctionExpression = function (arrowFunction) { - this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.Parameters.fromParameterList(arrowFunction.callSignature.parameterList), arrowFunction.block, arrowFunction.expression); + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), arrowFunction.block, arrowFunction.expression); }; Emitter.prototype.emitAnyArrowFunctionExpression = function (arrowFunction, funcName, parameters, block, expression) { @@ -30500,7 +30635,7 @@ var TypeScript; this.writeToOutput("function "); this.writeToOutput(this.thisClassNode.identifier.text()); this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(funcDecl.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); this.emitFunctionParameters(parameters); this.writeLineToOutput(") {"); @@ -30554,7 +30689,7 @@ var TypeScript; this.writeToOutput("("); this.writeToOutput(")"); - this.emitFunctionBodyStatements(null, accessor, TypeScript.Parameters.fromParameterList(accessor.parameterList), accessor.block, null); + this.emitFunctionBodyStatements(null, accessor, TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList), accessor.block, null); this.recordSourceMappingEnd(accessor); @@ -30586,7 +30721,7 @@ var TypeScript; this.writeToOutput(accessor.propertyName.text()); this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(accessor.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList); this.emitFunctionParameters(parameters); this.writeToOutput(")"); @@ -30625,7 +30760,7 @@ var TypeScript; this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); this.emitFunctionParameters(parameters); this.writeToOutput(")"); @@ -30680,7 +30815,7 @@ var TypeScript; this.emitParameterList(funcDecl.callSignature.parameterList); - var parameters = TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); this.emitFunctionBodyStatements(funcDecl.identifier.text(), funcDecl, parameters, funcDecl.block, null); this.recordSourceMappingEnd(funcDecl); @@ -30953,7 +31088,7 @@ var TypeScript; if (pullSymbol && pullSymbolAlias) { var symbolToCompare = TypeScript.isTypesOnlyLocation(ast) ? pullSymbolAlias.getExportAssignedTypeSymbol() : pullSymbolAlias.getExportAssignedValueSymbol(); - if (pullSymbol == symbolToCompare) { + if (pullSymbol === symbolToCompare) { pullSymbol = pullSymbolAlias; pullSymbolAlias = null; } @@ -30972,7 +31107,7 @@ var TypeScript; } var pullSymbolAlias = symbolForEmit.aliasSymbol; var pullSymbolKind = pullSymbol.kind; - var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() == this.getEnclosingDecl()); + var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() === this.getEnclosingDecl()); if (addThis && (this.emitState.container !== 6 /* Args */) && pullSymbol) { var pullSymbolContainer = pullSymbol.getContainer(); @@ -31017,19 +31152,19 @@ var TypeScript; if (name) { if (this.sourceMapper.currentNameIndex.length > 0) { var parentNameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; - if (parentNameIndex != -1) { + if (parentNameIndex !== -1) { name = this.sourceMapper.names[parentNameIndex] + "." + name; } } var nameIndex = this.sourceMapper.names.length - 1; for (nameIndex; nameIndex >= 0; nameIndex--) { - if (this.sourceMapper.names[nameIndex] == name) { + if (this.sourceMapper.names[nameIndex] === name) { break; } } - if (nameIndex == -1) { + if (nameIndex === -1) { nameIndex = this.sourceMapper.names.length; this.sourceMapper.names.push(name); } @@ -31045,7 +31180,7 @@ var TypeScript; }; Emitter.prototype.recordSourceMappingStart = function (ast) { - if (this.sourceMapper && TypeScript.isValidAstNode(ast)) { + if (this.sourceMapper && TypeScript.ASTHelpers.isValidAstNode(ast)) { var lineCol = { line: -1, character: -1 }; var sourceMapping = new TypeScript.SourceMapping(); sourceMapping.start.emittedColumn = this.emitState.column; @@ -31078,7 +31213,7 @@ var TypeScript; }; Emitter.prototype.recordSourceMappingEnd = function (ast) { - if (this.sourceMapper && TypeScript.isValidAstNode(ast)) { + if (this.sourceMapper && TypeScript.ASTHelpers.isValidAstNode(ast)) { this.sourceMapper.currentMappings.pop(); var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; @@ -31108,9 +31243,9 @@ var TypeScript; Emitter.prototype.emitParameterPropertyAndMemberVariableAssignments = function () { var constructorDecl = getLastConstructor(this.thisClassNode); - if (constructorDecl && constructorDecl.parameterList) { - for (var i = 0, n = constructorDecl.parameterList.parameters.nonSeparatorCount(); i < n; i++) { - var parameter = constructorDecl.parameterList.parameters.nonSeparatorAt(i); + if (constructorDecl) { + for (var i = 0, n = constructorDecl.callSignature.parameterList.parameters.nonSeparatorCount(); i < n; i++) { + var parameter = constructorDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { this.emitIndent(); @@ -31270,12 +31405,12 @@ var TypeScript; } }; - Emitter.prototype.getCopyrightComments = function () { - var preComments = this.copyrightElement.preComments(); + Emitter.prototype.getDetachedComments = function (element) { + var preComments = element.preComments(); if (preComments) { var lineMap = this.document.lineMap(); - var copyrightComments = []; + var detachedComments = []; var lastComment = null; for (var i = 0, n = preComments.length; i < n; i++) { @@ -31286,18 +31421,18 @@ var TypeScript; var commentLine = lineMap.getLineNumberFromPosition(comment.start()); if (commentLine >= lastCommentLine + 2) { - return copyrightComments; + return detachedComments; } } - copyrightComments.push(comment); + detachedComments.push(comment); lastComment = comment; } - var lastCommentLine = lineMap.getLineNumberFromPosition(TypeScript.ArrayUtilities.last(copyrightComments).end()); - var astLine = lineMap.getLineNumberFromPosition(this.copyrightElement.start()); + var lastCommentLine = lineMap.getLineNumberFromPosition(TypeScript.ArrayUtilities.last(detachedComments).end()); + var astLine = lineMap.getLineNumberFromPosition(element.start()); if (astLine >= lastCommentLine + 2) { - return copyrightComments; + return detachedComments; } } @@ -31305,12 +31440,15 @@ var TypeScript; }; Emitter.prototype.emitPossibleCopyrightHeaders = function (script) { - var list = script.moduleElements; + this.emitDetachedComments(script.moduleElements); + }; + + Emitter.prototype.emitDetachedComments = function (list) { if (list.childCount() > 0) { var firstElement = list.childAt(0); - this.copyrightElement = firstElement; - this.emitCommentsArray(this.getCopyrightComments(), false); + this.detachedCommentsElement = firstElement; + this.emitCommentsArray(this.getDetachedComments(this.detachedCommentsElement), false); } }; @@ -31333,7 +31471,7 @@ var TypeScript; this.emitPrologue(sourceUnit); var isExternalModule = this.document.isExternalModule(); - var isNonElidedExternalModule = isExternalModule && !TypeScript.scriptIsElided(sourceUnit); + var isNonElidedExternalModule = isExternalModule && !TypeScript.ASTHelpers.scriptIsElided(sourceUnit); if (isNonElidedExternalModule) { this.recordSourceMappingStart(sourceUnit); @@ -31358,7 +31496,7 @@ var TypeScript; this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); } - this.setExportAssignmentIdentifier(null); + this.setExportAssignment(null); if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { this.indenter.increaseIndent(); @@ -31381,20 +31519,23 @@ var TypeScript; } if (isNonElidedExternalModule) { - var exportAssignmentIdentifier = this.getExportAssignmentIdentifier(); + var exportAssignment = this.getExportAssignment(); + var exportAssignmentIdentifierText = exportAssignment ? exportAssignment.identifier.text() : null; var exportAssignmentValueSymbol = externalModule.getSymbol().getExportAssignedValueSymbol(); if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { - if (exportAssignmentIdentifier && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { this.indenter.increaseIndent(); this.emitIndent(); - this.writeLineToOutput("return " + exportAssignmentIdentifier + ";"); + this.writeToOutputWithSourceMapRecord("return " + exportAssignmentIdentifierText, exportAssignment); + this.writeLineToOutput(";"); this.indenter.decreaseIndent(); } this.writeToOutput("});"); - } else if (exportAssignmentIdentifier && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + } else if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { this.emitIndent(); - this.writeToOutput("module.exports = " + exportAssignmentIdentifier + ";"); + this.writeToOutputWithSourceMapRecord("module.exports = " + exportAssignmentIdentifierText, exportAssignment); + this.writeToOutput(";"); } this.recordSourceMappingEnd(sourceUnit); @@ -31416,7 +31557,7 @@ var TypeScript; this.emitComments(list, true); - var emitPropertyAssignmentsAfterSuperCall = TypeScript.getExtendsHeritageClause(this.thisClassNode.heritageClauses) !== null; + var emitPropertyAssignmentsAfterSuperCall = TypeScript.ASTHelpers.getExtendsHeritageClause(this.thisClassNode.heritageClauses) !== null; var propertyAssignmentIndex = emitPropertyAssignmentsAfterSuperCall ? 1 : 0; var lastEmittedNode = null; @@ -31523,7 +31664,7 @@ var TypeScript; this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(parameterList); this.emitFunctionParameters(parameters); this.writeToOutput(")"); @@ -31548,7 +31689,7 @@ var TypeScript; this.recordSourceMappingStart(classDecl); this.writeToOutput("var " + className); - var hasBaseClass = TypeScript.getExtendsHeritageClause(classDecl.heritageClauses) !== null; + var hasBaseClass = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses) !== null; var baseTypeReference = null; var varDecl = null; @@ -31562,9 +31703,10 @@ var TypeScript; this.indenter.increaseIndent(); if (hasBaseClass) { - baseTypeReference = TypeScript.getExtendsHeritageClause(classDecl.heritageClauses).typeNames.nonSeparatorAt(0); + baseTypeReference = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses).typeNames.nonSeparatorAt(0); this.emitIndent(); - this.writeLineToOutput("__extends(" + className + ", _super);"); + this.writeToOutputWithSourceMapRecord("__extends(" + className + ", _super)", baseTypeReference); + this.writeLineToOutput(";"); } this.emitIndent(); @@ -31582,7 +31724,8 @@ var TypeScript; this.recordSourceMappingNameStart("constructor"); if (hasBaseClass) { this.emitIndent(); - this.writeLineToOutput("_super.apply(this, arguments);"); + this.writeToOutputWithSourceMapRecord("_super.apply(this, arguments)", baseTypeReference); + this.writeLineToOutput(";"); } if (this.shouldCaptureThis(classDecl)) { @@ -31593,7 +31736,8 @@ var TypeScript; this.indenter.decreaseIndent(); this.emitIndent(); - this.writeLineToOutput("}"); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.writeLineToOutput(""); this.recordSourceMappingNameEnd(); this.recordSourceMappingEnd(classDecl); @@ -31715,7 +31859,7 @@ var TypeScript; this.emitParameterList(funcDecl.callSignature.parameterList); - var parameters = TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); this.emitFunctionBodyStatements(funcDecl.propertyName.text(), funcDecl, parameters, funcDecl.block, null); this.recordSourceMappingEnd(funcDecl); @@ -31741,7 +31885,7 @@ var TypeScript; } else if (moduleElement.kind() === 131 /* ClassDeclaration */) { var classDeclaration = moduleElement; - if (!TypeScript.hasModifier(classDeclaration.modifiers, 8 /* Ambient */) && TypeScript.getExtendsHeritageClause(classDeclaration.heritageClauses) !== null) { + if (!TypeScript.hasModifier(classDeclaration.modifiers, 8 /* Ambient */) && TypeScript.ASTHelpers.getExtendsHeritageClause(classDeclaration.heritageClauses) !== null) { return true; } } @@ -31921,13 +32065,13 @@ var TypeScript; Emitter.prototype.canEmitDottedNameMemberAccessExpression = function (expression) { var memberExpressionNodeType = expression.expression.kind(); - if (memberExpressionNodeType == 11 /* IdentifierName */ || memberExpressionNodeType == 212 /* MemberAccessExpression */) { + if (memberExpressionNodeType === 11 /* IdentifierName */ || memberExpressionNodeType == 212 /* MemberAccessExpression */) { var memberAccessSymbol = this.getSymbolForEmit(expression).symbol; var memberAccessExpressionSymbol = this.getSymbolForEmit(expression.expression).symbol; if (memberAccessSymbol && memberAccessExpressionSymbol && !this.semanticInfoChain.getAliasSymbolForAST(expression.expression) && (TypeScript.PullHelpers.symbolIsModule(memberAccessExpressionSymbol) || memberAccessExpressionSymbol.kind === 64 /* Enum */ || memberAccessExpressionSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */))) { var memberAccessSymbolKind = memberAccessSymbol.kind; if (memberAccessSymbolKind === 4096 /* Property */ || memberAccessSymbolKind === 67108864 /* EnumMember */ || (memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && memberAccessSymbolKind === 512 /* Variable */ && !memberAccessSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) || ((memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && !this.symbolIsUsedInItsEnclosingContainer(memberAccessSymbol)))) { - if (memberExpressionNodeType == 212 /* MemberAccessExpression */) { + if (memberExpressionNodeType === 212 /* MemberAccessExpression */) { return this.canEmitDottedNameMemberAccessExpression(expression.expression); } @@ -31941,7 +32085,7 @@ var TypeScript; Emitter.prototype.emitDottedNameMemberAccessExpressionWorker = function (expression, potentialPath, startingIndex, lastIndex) { this.recordSourceMappingStart(expression); - if (expression.expression.kind() == 212 /* MemberAccessExpression */) { + if (expression.expression.kind() === 212 /* MemberAccessExpression */) { this.emitDottedNameMemberAccessExpressionRecurse(expression.expression, potentialPath, startingIndex, lastIndex - 1); } else { this.emitComments(expression.expression, true); @@ -32058,7 +32202,7 @@ var TypeScript; this.writeToOutput("("); - var parameters = TypeScript.Parameters.fromParameterList(funcProp.callSignature.parameterList); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList); this.emitFunctionParameters(parameters); this.writeToOutput(")"); @@ -32074,8 +32218,6 @@ var TypeScript; this.setContainer(temp); this.inArrowFunction = savedInArrowFunction; - - this.recordSourceMappingEnd(funcProp); }; Emitter.prototype.emitConditionalExpression = function (expression) { @@ -32396,15 +32538,17 @@ var TypeScript; this.pushDecl(pullDecl); this.emitScriptElements(sourceUnit); this.popDecl(pullDecl); + + this.emitCommentsArray(sourceUnit.endOfFileTokenLeadingComments, false); } }; Emitter.prototype.shouldEmitEnumDeclaration = function (declaration) { - return declaration.preComments() !== null || !TypeScript.enumIsElided(declaration); + return declaration.preComments() !== null || !TypeScript.ASTHelpers.enumIsElided(declaration); }; Emitter.prototype.emitEnumDeclaration = function (declaration) { - if (!TypeScript.enumIsElided(declaration)) { + if (!TypeScript.ASTHelpers.enumIsElided(declaration)) { this.emitComments(declaration, true); this.emitEnum(declaration); this.emitComments(declaration, false); @@ -32414,11 +32558,11 @@ var TypeScript; }; Emitter.prototype.shouldEmitModuleDeclaration = function (declaration) { - return declaration.preComments() !== null || !TypeScript.moduleIsElided(declaration); + return declaration.preComments() !== null || !TypeScript.ASTHelpers.moduleIsElided(declaration); }; Emitter.prototype.emitModuleDeclaration = function (declaration) { - if (!TypeScript.moduleIsElided(declaration)) { + if (!TypeScript.ASTHelpers.moduleIsElided(declaration)) { this.emitModuleDeclarationWorker(declaration); } else { this.emitComments(declaration, true, true); @@ -32514,7 +32658,7 @@ var TypeScript; case 133 /* ImportDeclaration */: return this.emitImportDeclaration(ast); case 134 /* ExportAssignment */: - return this.setExportAssignmentIdentifier(ast.identifier.text()); + return this.setExportAssignment(ast); case 131 /* ClassDeclaration */: return this.emitClassDeclaration(ast); case 128 /* InterfaceDeclaration */: @@ -33253,10 +33397,10 @@ var TypeScript; var dtsFile = normalizedPath + ".d.ts"; var tsFile = normalizedPath + ".ts"; - if (this.host.fileExists(dtsFile)) { - normalizedPath = dtsFile; - } else { + if (this.host.fileExists(tsFile)) { normalizedPath = tsFile; + } else { + normalizedPath = dtsFile; } } @@ -33286,13 +33430,13 @@ var TypeScript; var start = new Date().getTime(); do { - var currentFilePath = this.host.resolveRelativePath(dtsFileName, parentDirectory); + currentFilePath = this.host.resolveRelativePath(tsFilePath, parentDirectory); if (this.host.fileExists(currentFilePath)) { searchFilePath = currentFilePath; break; } - currentFilePath = this.host.resolveRelativePath(tsFilePath, parentDirectory); + var currentFilePath = this.host.resolveRelativePath(dtsFileName, parentDirectory); if (this.host.fileExists(currentFilePath)) { searchFilePath = currentFilePath; break; @@ -33544,7 +33688,7 @@ var TypeScript; var declAST = this.semanticInfoChain.getASTForDecl(pullDecl); var container = this.getEnclosingContainer(declAST); - if (container.kind() === 130 /* ModuleDeclaration */ && TypeScript.isAnyNameOfModule(container, declAST)) { + if (container.kind() === 130 /* ModuleDeclaration */ && TypeScript.ASTHelpers.isAnyNameOfModule(container, declAST)) { container = this.getEnclosingContainer(container); } @@ -33555,8 +33699,8 @@ var TypeScript; emitDeclare = true; } - if (isExternalModule || container.kind() == 120 /* SourceUnit */) { - if (emitDeclare && typeString !== "interface" && typeString != "import") { + if (isExternalModule || container.kind() === 120 /* SourceUnit */) { + if (emitDeclare && typeString !== "interface" && typeString !== "import") { result += "declare "; } } @@ -33625,7 +33769,9 @@ var TypeScript; var declarationPullSymbol = declarationContainerDecl.getSymbol(); TypeScript.declarationEmitTypeSignatureTime += new Date().getTime() - start; - var typeNameMembers = type.getScopedNameEx(declarationPullSymbol); + var isNotAGenericType = ast.kind() !== 126 /* GenericType */; + + var typeNameMembers = type.getScopedNameEx(declarationPullSymbol, false, false, false, false, false, isNotAGenericType); this.emitTypeNamesMember(typeNameMembers); }; @@ -33659,7 +33805,7 @@ var TypeScript; return; } - var declComments = astOrSymbol.docComments ? astOrSymbol.docComments() : TypeScript.docComments(astOrSymbol); + var declComments = astOrSymbol.docComments ? astOrSymbol.docComments() : TypeScript.ASTHelpers.docComments(astOrSymbol); this.writeDeclarationComments(declComments, endLine); }; @@ -33718,7 +33864,7 @@ var TypeScript; this.declFile.Write(varDecl.propertyName.text()); - if (!TypeScript.hasModifier(TypeScript.getVariableDeclaratorModifiers(varDecl), 2 /* Private */)) { + if (!TypeScript.hasModifier(TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), 2 /* Private */)) { this.emitTypeOfVariableDeclaratorOrParameter(varDecl); } @@ -33770,7 +33916,7 @@ var TypeScript; DeclarationEmitter.prototype.emitDeclarationsForVariableDeclaration = function (variableDeclaration) { var varListCount = variableDeclaration.declarators.nonSeparatorCount(); for (var i = 0; i < varListCount; i++) { - this.emitVariableDeclarator(variableDeclaration.declarators.nonSeparatorAt(i), i == 0, i == varListCount - 1); + this.emitVariableDeclarator(variableDeclaration.declarators.nonSeparatorAt(i), i === 0, i === varListCount - 1); } }; @@ -33825,14 +33971,14 @@ var TypeScript; this.declFile.Write("constructor"); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); this.declFile.Write(")"); this.declFile.WriteLine(";"); }; DeclarationEmitter.prototype.emitParameterList = function (isPrivate, parameterList) { this.declFile.Write("("); - this.emitParameters(isPrivate, TypeScript.Parameters.fromParameterList(parameterList)); + this.emitParameters(isPrivate, TypeScript.ASTHelpers.parametersFromParameterList(parameterList)); this.declFile.Write(")"); }; @@ -33923,7 +34069,7 @@ var TypeScript; this.emitIndent(); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList)); this.declFile.Write(")"); var returnType = funcSignature.returnType; @@ -33954,7 +34100,7 @@ var TypeScript; this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); this.declFile.Write(")"); var returnType = funcSignature.returnType; @@ -33988,7 +34134,7 @@ var TypeScript; this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); this.declFile.Write(")"); var returnType = funcSignature.returnType; @@ -34038,7 +34184,7 @@ var TypeScript; this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); this.declFile.Write("("); - this.emitParameters(false, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); this.declFile.Write(")"); var returnType = funcSignature.returnType; @@ -34065,7 +34211,7 @@ var TypeScript; this.emitIndent(); this.declFile.Write("["); - this.emitParameters(false, TypeScript.Parameters.fromParameter(funcDecl.parameter)); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter)); this.declFile.Write("]"); var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); @@ -34104,10 +34250,10 @@ var TypeScript; var comments = []; if (accessors.getter) { - comments = comments.concat(TypeScript.docComments(accessors.getter)); + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.getter)); } if (accessors.setter) { - comments = comments.concat(TypeScript.docComments(accessors.setter)); + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.setter)); } this.writeDeclarationComments(comments); @@ -34144,27 +34290,25 @@ var TypeScript; }; DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { - if (funcDecl.parameterList) { - var argsLen = funcDecl.parameterList.parameters.nonSeparatorCount(); - if (TypeScript.lastParameterIsRest(funcDecl.parameterList)) { - argsLen--; - } + var argsLen = funcDecl.callSignature.parameterList.parameters.nonSeparatorCount(); + if (TypeScript.lastParameterIsRest(funcDecl.callSignature.parameterList)) { + argsLen--; + } - for (var i = 0; i < argsLen; i++) { - var parameter = funcDecl.parameterList.parameters.nonSeparatorAt(i); - var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); - if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { - var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); - this.emitDeclarationComments(parameter); - this.declFile.Write(this.getIndentString()); - this.emitClassElementModifiers(parameter.modifiers); - this.declFile.Write(parameter.identifier.text()); + for (var i = 0; i < argsLen; i++) { + var parameter = funcDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.emitDeclarationComments(parameter); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(parameter.modifiers); + this.declFile.Write(parameter.identifier.text()); - if (!TypeScript.hasModifier(parameter.modifiers, 2 /* Private */)) { - this.emitTypeOfVariableDeclaratorOrParameter(parameter); - } - this.declFile.WriteLine(";"); + if (!TypeScript.hasModifier(parameter.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(parameter); } + this.declFile.WriteLine(";"); } } }; @@ -34296,20 +34440,11 @@ var TypeScript; if (importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { this.declFile.WriteLine("require(" + importDeclAST.moduleReference.stringLiteral.text() + ");"); } else { - this.declFile.WriteLine(this.getFullName(importDeclAST.moduleReference.moduleName) + ";"); + this.declFile.WriteLine(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(importDeclAST.moduleReference.moduleName) + ";"); } } }; - DeclarationEmitter.prototype.getFullName = function (name) { - if (name.kind() === 11 /* IdentifierName */) { - return name.text(); - } else { - var dotExpr = name; - return this.getFullName(dotExpr.left) + "." + this.getFullName(dotExpr.right); - } - }; - DeclarationEmitter.prototype.emitDeclarationsForEnumDeclaration = function (moduleDecl) { if (!this.canEmitDeclarations(moduleDecl)) { return; @@ -34329,7 +34464,7 @@ var TypeScript; this.emitDeclarationComments(enumElement); this.emitIndent(); this.declFile.Write(enumElement.propertyName.text()); - if (enumElementDecl.constantValue != null) { + if (enumElementDecl.constantValue !== null) { this.declFile.Write(" = " + enumElementDecl.constantValue); } this.declFile.WriteLine(","); @@ -34354,7 +34489,7 @@ var TypeScript; if (moduleDecl.stringLiteral) { this.declFile.Write(moduleDecl.stringLiteral.text()); } else { - this.declFile.Write(this.getFullName(moduleDecl.name)); + this.declFile.Write(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(moduleDecl.name)); } this.declFile.WriteLine(" {"); @@ -34417,12 +34552,12 @@ var TypeScript; if (document && (document.isDeclareFile() || document.isExternalModule())) { for (var k = 0; k < documents.length; k++) { - if (documents[k] == document) { + if (documents[k] === document) { break; } } - if (k == documents.length) { + if (k === documents.length) { documents = documents.concat(document); } } @@ -34522,16 +34657,16 @@ var TypeScript; }; BloomFilter.prototype.isEquivalent = function (filter) { - return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount == filter.hashFunctionCount; + return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount === filter.hashFunctionCount; }; BloomFilter.isEquivalent = function (array1, array2) { - if (array1.length != array2.length) { + if (array1.length !== array2.length) { return false; } for (var i = 0; i < array1.length; i++) { - if (array1[i] != array2[i]) { + if (array1[i] !== array2[i]) { return false; } } @@ -34580,13 +34715,14 @@ var TypeScript; this.useCaseSensitiveFileResolution = false; this.gatherDiagnostics = false; this.codepage = null; + this.createFileLog = false; } return CompilationSettings; })(); TypeScript.CompilationSettings = CompilationSettings; var ImmutableCompilationSettings = (function () { - function ImmutableCompilationSettings(propagateEnumConstants, removeComments, watch, noResolve, allowAutomaticSemicolonInsertion, noImplicitAny, noLib, codeGenTarget, moduleGenTarget, outFileOption, outDirOption, mapSourceFiles, mapRoot, sourceRoot, generateDeclarationFiles, useCaseSensitiveFileResolution, gatherDiagnostics, codepage) { + function ImmutableCompilationSettings(propagateEnumConstants, removeComments, watch, noResolve, allowAutomaticSemicolonInsertion, noImplicitAny, noLib, codeGenTarget, moduleGenTarget, outFileOption, outDirOption, mapSourceFiles, mapRoot, sourceRoot, generateDeclarationFiles, useCaseSensitiveFileResolution, gatherDiagnostics, codepage, createFileLog) { this._propagateEnumConstants = propagateEnumConstants; this._removeComments = removeComments; this._watch = watch; @@ -34605,6 +34741,7 @@ var TypeScript; this._useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; this._gatherDiagnostics = gatherDiagnostics; this._codepage = codepage; + this._createFileLog = createFileLog; } ImmutableCompilationSettings.prototype.propagateEnumConstants = function () { return this._propagateEnumConstants; @@ -34660,6 +34797,9 @@ var TypeScript; ImmutableCompilationSettings.prototype.codepage = function () { return this._codepage; }; + ImmutableCompilationSettings.prototype.createFileLog = function () { + return this._createFileLog; + }; ImmutableCompilationSettings.defaultSettings = function () { if (!ImmutableCompilationSettings._defaultSettings) { @@ -34670,15 +34810,17 @@ var TypeScript; }; ImmutableCompilationSettings.fromCompilationSettings = function (settings) { - return new ImmutableCompilationSettings(settings.propagateEnumConstants, settings.removeComments, settings.watch, settings.noResolve, settings.allowAutomaticSemicolonInsertion, settings.noImplicitAny, settings.noLib, settings.codeGenTarget, settings.moduleGenTarget, settings.outFileOption, settings.outDirOption, settings.mapSourceFiles, settings.mapRoot, settings.sourceRoot, settings.generateDeclarationFiles, settings.useCaseSensitiveFileResolution, settings.gatherDiagnostics, settings.codepage); + return new ImmutableCompilationSettings(settings.propagateEnumConstants, settings.removeComments, settings.watch, settings.noResolve, settings.allowAutomaticSemicolonInsertion, settings.noImplicitAny, settings.noLib, settings.codeGenTarget, settings.moduleGenTarget, settings.outFileOption, settings.outDirOption, settings.mapSourceFiles, settings.mapRoot, settings.sourceRoot, settings.generateDeclarationFiles, settings.useCaseSensitiveFileResolution, settings.gatherDiagnostics, settings.codepage, settings.createFileLog); }; ImmutableCompilationSettings.prototype.toCompilationSettings = function () { var result = new CompilationSettings(); + var thisAsIndexable = this; + var resultAsIndexable = result; for (var name in this) { if (this.hasOwnProperty(name) && TypeScript.StringUtilities.startsWith(name, "_")) { - result[name.substr(1)] = this[name]; + resultAsIndexable[name.substr(1)] = thisAsIndexable[name]; } } @@ -34784,7 +34926,7 @@ var TypeScript; PullElementKind[PullElementKind["SomeValue"] = PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.EnumMember | PullElementKind.SomeFunction] = "SomeValue"; - PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter] = "SomeType"; + PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.ObjectLiteral | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter] = "SomeType"; PullElementKind[PullElementKind["AcceptableAlias"] = PullElementKind.Variable | PullElementKind.SomeFunction | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Container | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "AcceptableAlias"; @@ -34800,17 +34942,18 @@ var TypeScript; })(TypeScript || (TypeScript = {})); var TypeScript; (function (TypeScript) { - TypeScript.pullDeclID = 0; + var pullDeclID = 0; var sentinelEmptyPullDeclArray = []; var PullDecl = (function () { - function PullDecl(declName, displayName, kind, declFlags, span) { - this.declID = TypeScript.pullDeclID++; + function PullDecl(declName, displayName, kind, declFlags, semanticInfoChain) { + this.declID = pullDeclID++; this.flags = 0 /* None */; this.declGroups = null; this.childDecls = null; this.typeParameters = null; this.synthesizedValDecl = null; + this.containerDecl = null; this.childDeclTypeCache = null; this.childDeclValueCache = null; this.childDeclNamespaceCache = null; @@ -34818,7 +34961,7 @@ var TypeScript; this.name = declName; this.kind = kind; this.flags = declFlags; - this.span = span; + this.semanticInfoChain = semanticInfoChain; if (displayName !== this.name) { this.declDisplayName = displayName; @@ -34836,10 +34979,6 @@ var TypeScript; throw TypeScript.Errors.abstract(); }; - PullDecl.prototype.semanticInfoChain = function () { - throw TypeScript.Errors.abstract(); - }; - PullDecl.prototype.isExternalModule = function () { throw TypeScript.Errors.abstract(); }; @@ -34872,44 +35011,42 @@ var TypeScript; }; PullDecl.prototype.setSymbol = function (symbol) { - this.semanticInfoChain().setSymbolForDecl(this, symbol); + this.semanticInfoChain.setSymbolForDecl(this, symbol); }; - PullDecl.prototype.ensureSymbolIsBound = function (bindSignatureSymbol) { - if (typeof bindSignatureSymbol === "undefined") { bindSignatureSymbol = false; } - if (!((bindSignatureSymbol && this.hasSignatureSymbol()) || this.hasSymbol()) && this.kind != 1 /* Script */) { - var binder = this.semanticInfoChain().getBinder(); + PullDecl.prototype.ensureSymbolIsBound = function () { + if (!this.hasBeenBound() && this.kind !== 1 /* Script */) { + var binder = this.semanticInfoChain.getBinder(); binder.bindDeclToPullSymbol(this); } }; PullDecl.prototype.getSymbol = function () { - if (this.kind == 1 /* Script */) { + if (this.kind === 1 /* Script */) { return null; } this.ensureSymbolIsBound(); - return this.semanticInfoChain().getSymbolForDecl(this); + return this.semanticInfoChain.getSymbolForDecl(this); }; PullDecl.prototype.hasSymbol = function () { - var symbol = this.semanticInfoChain().getSymbolForDecl(this); + var symbol = this.semanticInfoChain.getSymbolForDecl(this); return !!symbol; }; PullDecl.prototype.setSignatureSymbol = function (signatureSymbol) { - this.semanticInfoChain().setSignatureSymbolForDecl(this, signatureSymbol); + this.semanticInfoChain.setSignatureSymbolForDecl(this, signatureSymbol); }; PullDecl.prototype.getSignatureSymbol = function () { - this.ensureSymbolIsBound(true); - - return this.semanticInfoChain().getSignatureSymbolForDecl(this); + this.ensureSymbolIsBound(); + return this.semanticInfoChain.getSignatureSymbolForDecl(this); }; PullDecl.prototype.hasSignatureSymbol = function () { - var signatureSymbol = this.semanticInfoChain().getSignatureSymbolForDecl(this); + var signatureSymbol = this.semanticInfoChain.getSignatureSymbolForDecl(this); return !!signatureSymbol; }; @@ -34921,20 +35058,17 @@ var TypeScript; this.flags |= flags; }; - PullDecl.prototype.getSpan = function () { - return this.span; - }; - PullDecl.prototype.setValueDecl = function (valDecl) { this.synthesizedValDecl = valDecl; + valDecl.containerDecl = this; }; PullDecl.prototype.getValueDecl = function () { return this.synthesizedValDecl; }; - PullDecl.prototype.isEqual = function (other) { - return (this.name === other.name) && (this.kind === other.kind) && (this.flags === other.flags) && (this.fileName() === other.fileName()) && (this.span.start() === other.span.start()) && (this.span.end() === other.span.end()); + PullDecl.prototype.getContainerDecl = function () { + return this.containerDecl; }; PullDecl.prototype.getChildDeclCache = function (declKind) { @@ -34950,7 +35084,7 @@ var TypeScript; } return this.childDeclNamespaceCache; - } else if (TypeScript.hasFlag(declKind, 58728539 /* SomeType */)) { + } else if (TypeScript.hasFlag(declKind, 58728795 /* SomeType */)) { if (!this.childDeclTypeCache) { this.childDeclTypeCache = TypeScript.createIntrinsicsObject(); } @@ -34995,7 +35129,7 @@ var TypeScript; PullDecl.prototype.searchChildDecls = function (declName, searchKind) { var cacheVal = null; - if (searchKind & 58728539 /* SomeType */) { + if (searchKind & 58728795 /* SomeType */) { cacheVal = this.childDeclTypeCache ? this.childDeclTypeCache[declName] : null; } else if (searchKind & 164 /* SomeContainer */) { cacheVal = this.childDeclNamespaceCache ? this.childDeclNamespaceCache[declName] : null; @@ -35006,7 +35140,7 @@ var TypeScript; if (cacheVal) { return cacheVal; } else { - if (searchKind & 58728539 /* SomeType */) { + if (searchKind & 58728795 /* SomeType */) { cacheVal = this.childDeclTypeParameterCache ? this.childDeclTypeParameterCache[declName] : null; if (cacheVal) { @@ -35019,11 +35153,11 @@ var TypeScript; }; PullDecl.prototype.getChildDecls = function () { - return this.childDecls ? this.childDecls : sentinelEmptyPullDeclArray; + return this.childDecls || sentinelEmptyPullDeclArray; }; PullDecl.prototype.getTypeParameters = function () { - return this.typeParameters ? this.typeParameters : sentinelEmptyPullDeclArray; + return this.typeParameters || sentinelEmptyPullDeclArray; }; PullDecl.prototype.addVariableDeclToGroup = function (decl) { @@ -35056,7 +35190,7 @@ var TypeScript; } } - return declGroups ? declGroups : sentinelEmptyPullDeclArray; + return declGroups || sentinelEmptyPullDeclArray; }; PullDecl.prototype.hasBeenBound = function () { @@ -35068,8 +35202,11 @@ var TypeScript; }; PullDecl.prototype.ast = function () { - var semanticInfoChain = this.semanticInfoChain(); - return semanticInfoChain ? semanticInfoChain.getASTForDecl(this) : null; + return this.semanticInfoChain.getASTForDecl(this); + }; + + PullDecl.prototype.isRootDecl = function () { + throw TypeScript.Errors.abstract(); }; return PullDecl; })(); @@ -35077,9 +35214,9 @@ var TypeScript; var RootPullDecl = (function (_super) { __extends(RootPullDecl, _super); - function RootPullDecl(name, fileName, kind, declFlags, span, semanticInfoChain, isExternalModule) { - _super.call(this, name, name, kind, declFlags, span); - this._semanticInfoChain = semanticInfoChain; + function RootPullDecl(name, fileName, kind, declFlags, semanticInfoChain, isExternalModule) { + _super.call(this, name, name, kind, declFlags, semanticInfoChain); + this.semanticInfoChain = semanticInfoChain; this._isExternalModule = isExternalModule; this._fileName = fileName; } @@ -35095,10 +35232,6 @@ var TypeScript; return null; }; - RootPullDecl.prototype.semanticInfoChain = function () { - return this._semanticInfoChain; - }; - RootPullDecl.prototype.isExternalModule = function () { return this._isExternalModule; }; @@ -35106,15 +35239,18 @@ var TypeScript; RootPullDecl.prototype.getEnclosingDecl = function () { return this; }; + RootPullDecl.prototype.isRootDecl = function () { + return true; + }; return RootPullDecl; })(PullDecl); TypeScript.RootPullDecl = RootPullDecl; var NormalPullDecl = (function (_super) { __extends(NormalPullDecl, _super); - function NormalPullDecl(declName, displayName, kind, declFlags, parentDecl, span, addToParent) { + function NormalPullDecl(declName, displayName, kind, declFlags, parentDecl, addToParent) { if (typeof addToParent === "undefined") { addToParent = true; } - _super.call(this, declName, displayName, kind, declFlags, span); + _super.call(this, declName, displayName, kind, declFlags, parentDecl ? parentDecl.semanticInfoChain : null); this.parentDecl = null; this.parentPath = null; @@ -35122,9 +35258,20 @@ var TypeScript; if (addToParent) { parentDecl.addChildDecl(this); } + + if (this.parentDecl) { + if (this.parentDecl.isRootDecl()) { + this._rootDecl = this.parentDecl; + } else { + this._rootDecl = this.parentDecl._rootDecl; + } + } else { + TypeScript.Debug.assert(this.isSynthesized()); + this._rootDecl = null; + } } NormalPullDecl.prototype.fileName = function () { - return this.parentDecl ? this.parentDecl.fileName() : ""; + return this._rootDecl.fileName(); }; NormalPullDecl.prototype.getParentDecl = function () { @@ -35137,7 +35284,7 @@ var TypeScript; var parentDecl = this.parentDecl; while (parentDecl) { - if (parentDecl && path[path.length - 1] != parentDecl && !(parentDecl.kind & 256 /* ObjectLiteral */)) { + if (parentDecl && path[path.length - 1] !== parentDecl && !(parentDecl.kind & (256 /* ObjectLiteral */ | 8388608 /* ObjectType */))) { path.unshift(parentDecl); } @@ -35150,11 +35297,6 @@ var TypeScript; return this.parentPath; }; - NormalPullDecl.prototype.semanticInfoChain = function () { - var parent = this.getParentDecl(); - return parent ? parent.semanticInfoChain() : null; - }; - NormalPullDecl.prototype.isExternalModule = function () { return false; }; @@ -35162,14 +35304,18 @@ var TypeScript; NormalPullDecl.prototype.getEnclosingDecl = function () { return this.parentDecl && this.parentDecl._getEnclosingDeclFromParentDecl(); }; + + NormalPullDecl.prototype.isRootDecl = function () { + return false; + }; return NormalPullDecl; })(PullDecl); TypeScript.NormalPullDecl = NormalPullDecl; var PullEnumElementDecl = (function (_super) { __extends(PullEnumElementDecl, _super); - function PullEnumElementDecl(declName, displayName, parentDecl, span) { - _super.call(this, declName, displayName, 67108864 /* EnumMember */, 4 /* Public */, parentDecl, span); + function PullEnumElementDecl(declName, displayName, parentDecl) { + _super.call(this, declName, displayName, 67108864 /* EnumMember */, 4 /* Public */, parentDecl); this.constantValue = null; } return PullEnumElementDecl; @@ -35178,9 +35324,9 @@ var TypeScript; var PullFunctionExpressionDecl = (function (_super) { __extends(PullFunctionExpressionDecl, _super); - function PullFunctionExpressionDecl(expressionName, declFlags, parentDecl, span, displayName) { + function PullFunctionExpressionDecl(expressionName, declFlags, parentDecl, displayName) { if (typeof displayName === "undefined") { displayName = ""; } - _super.call(this, "", displayName, 131072 /* FunctionExpression */, declFlags, parentDecl, span); + _super.call(this, "", displayName, 131072 /* FunctionExpression */, declFlags, parentDecl); this.functionExpressionName = expressionName; } PullFunctionExpressionDecl.prototype.getFunctionExpressionName = function () { @@ -35192,17 +35338,17 @@ var TypeScript; var PullSynthesizedDecl = (function (_super) { __extends(PullSynthesizedDecl, _super); - function PullSynthesizedDecl(declName, displayName, kind, declFlags, parentDecl, span, semanticInfoChain) { - _super.call(this, declName, displayName, kind, declFlags, parentDecl, span, false); - this._semanticInfoChain = semanticInfoChain; + function PullSynthesizedDecl(declName, displayName, kind, declFlags, parentDecl, semanticInfoChain) { + _super.call(this, declName, displayName, kind, declFlags, parentDecl, false); + this.semanticInfoChain = semanticInfoChain; } - PullSynthesizedDecl.prototype.semanticInfoChain = function () { - return this._semanticInfoChain; - }; - PullSynthesizedDecl.prototype.isSynthesized = function () { return true; }; + + PullSynthesizedDecl.prototype.fileName = function () { + return this._rootDecl ? this._rootDecl.fileName() : ""; + }; return PullSynthesizedDecl; })(NormalPullDecl); TypeScript.PullSynthesizedDecl = PullSynthesizedDecl; @@ -35228,12 +35374,11 @@ var TypeScript; var TypeScript; (function (TypeScript) { TypeScript.pullSymbolID = 0; - TypeScript.globalTyvarID = 0; TypeScript.sentinelEmptyArray = []; var PullSymbol = (function () { function PullSymbol(name, declKind) { - this.pullSymbolID = TypeScript.pullSymbolID++; + this.pullSymbolID = ++TypeScript.pullSymbolID; this._container = null; this.type = null; this._declarations = null; @@ -35254,7 +35399,7 @@ var TypeScript; }; PullSymbol.prototype.isType = function () { - return (this.kind & 58728539 /* SomeType */) != 0; + return (this.kind & 58728795 /* SomeType */) !== 0; }; PullSymbol.prototype.isTypeReference = function () { @@ -35262,7 +35407,7 @@ var TypeScript; }; PullSymbol.prototype.isSignature = function () { - return (this.kind & 7340032 /* SomeSignature */) != 0; + return (this.kind & 7340032 /* SomeSignature */) !== 0; }; PullSymbol.prototype.isArrayNamedTypeReference = function () { @@ -35323,7 +35468,7 @@ var TypeScript; return aliasSymbols; } - if (!skipScopeSymbolAliasesLookIn && this.isExternalModuleReferenceAlias(symbol) && (!symbol.assignedContainer().hasExportAssignment() || (symbol.assignedContainer().getExportAssignedContainerSymbol() && symbol.assignedContainer().getExportAssignedContainerSymbol().kind == 32 /* DynamicModule */))) { + if (!skipScopeSymbolAliasesLookIn && this.isExternalModuleReferenceAlias(symbol) && (!symbol.assignedContainer().hasExportAssignment() || (symbol.assignedContainer().getExportAssignedContainerSymbol() && symbol.assignedContainer().getExportAssignedContainerSymbol().kind === 32 /* DynamicModule */))) { scopeSymbolAliasesToLookIn.push(symbol); } } @@ -35366,11 +35511,11 @@ var TypeScript; return false; } - if (aliasSymbol.assignedType() && aliasSymbol.assignedType() != aliasSymbol.assignedContainer()) { + if (aliasSymbol.assignedType() && aliasSymbol.assignedType() !== aliasSymbol.assignedContainer()) { return false; } - if (aliasSymbol.assignedContainer() && aliasSymbol.assignedContainer().kind != 32 /* DynamicModule */) { + if (aliasSymbol.assignedContainer() && aliasSymbol.assignedContainer().kind !== 32 /* DynamicModule */) { return false; } @@ -35382,12 +35527,12 @@ var TypeScript; PullSymbol.prototype.getExportedInternalAliasSymbol = function (scopeSymbol) { if (scopeSymbol) { - if (this.kind != 128 /* TypeAlias */) { + if (this.kind !== 128 /* TypeAlias */) { var scopePath = scopeSymbol.pathToRoot(); for (var i = 0; i < scopePath.length; i++) { var internalAliases = this.findAliasedType(scopeSymbol, true, true); if (internalAliases) { - TypeScript.Debug.assert(internalAliases.length == 1); + TypeScript.Debug.assert(internalAliases.length === 1); return internalAliases[0]; } } @@ -35408,11 +35553,14 @@ var TypeScript; var externalAliases = this.getExternalAliasedSymbols(scopeSymbol); if (externalAliases && this.isExternalModuleReferenceAlias(externalAliases[externalAliases.length - 1])) { - var aliasFullName = ""; + var aliasFullName = aliasNameGetter(externalAliases[0]); + if (!aliasFullName) { + return null; + } for (var i = 1, symbolsLen = externalAliases.length; i < symbolsLen; i++) { aliasFullName = aliasFullName + "." + aliasPartsNameGetter(externalAliases[i]); } - return aliasNameGetter(externalAliases[0]) + aliasFullName; + return aliasFullName; } return null; @@ -35420,7 +35568,7 @@ var TypeScript; PullSymbol.prototype._getResolver = function () { TypeScript.Debug.assert(this._declarations && this._declarations.length > 0); - return this._declarations[0].semanticInfoChain().getResolver(); + return this._declarations[0].semanticInfoChain.getResolver(); }; PullSymbol.prototype._resolveDeclaredSymbol = function () { @@ -35433,11 +35581,7 @@ var TypeScript; }, function (symbol) { return symbol.getName(); }); - if (aliasName != null) { - return aliasName; - } - - return this.name; + return aliasName || this.name; }; PullSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { @@ -35446,7 +35590,7 @@ var TypeScript; }, function (symbol) { return symbol.getDisplayName(); }, skipInternalAliasName); - if (aliasDisplayName != null) { + if (aliasDisplayName) { return aliasDisplayName; } @@ -35472,10 +35616,14 @@ var TypeScript; PullSymbol.prototype.setIsSynthesized = function (value) { if (typeof value === "undefined") { value = true; } + TypeScript.Debug.assert(this.rootSymbol == null); this.isSynthesized = value; }; PullSymbol.prototype.getIsSynthesized = function () { + if (this.rootSymbol) { + return this.rootSymbol.getIsSynthesized(); + } return this.isSynthesized; }; @@ -35585,7 +35733,7 @@ var TypeScript; } path[path.length] = node; var nodeKind = node.kind; - if (nodeKind == 2048 /* Parameter */) { + if (nodeKind === 2048 /* Parameter */) { break; } else { node = node.getContainer(); @@ -35594,54 +35742,61 @@ var TypeScript; return path; }; - PullSymbol.prototype.findCommonAncestorPath = function (b) { - var aPath = this.pathToRoot(); - if (aPath.length === 1) { - return aPath; - } + PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope = function (symbol, scopePath, endScopePathIndex) { + var declPath = scopePath[0].getDeclarations()[0].getParentPath(); + for (var i = 0, declIndex = declPath.length - 1; i <= endScopePathIndex; i++, declIndex--) { + if (symbol.isContainer() && scopePath[i].isContainer()) { + var scopeType = scopePath[i]; - var bPath; - if (b) { - bPath = b.pathToRoot(); - } else { - return aPath; - } + var memberSymbol = scopeType.findContainedNonMemberContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } - var commonNodeIndex = -1; - for (var i = 0, aLen = aPath.length; i < aLen; i++) { - var aNode = aPath[i]; - for (var j = 0, bLen = bPath.length; j < bLen; j++) { - var bNode = bPath[j]; - if (aNode === bNode) { - var aDecl = null; - if (i > 0) { - var decls = aPath[i - 1].getDeclarations(); - if (decls.length) { - aDecl = decls[0].getParentDecl(); - } - } - var bDecl = null; - if (j > 0) { - var decls = bPath[j - 1].getDeclarations(); - if (decls.length) { - bDecl = decls[0].getParentDecl(); - } - } - if (!aDecl || !bDecl || aDecl == bDecl) { - commonNodeIndex = i; - break; - } + var memberSymbol = scopeType.findNestedContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol) { + return true; } } - if (commonNodeIndex >= 0) { - break; + } + + return false; + }; + + PullSymbol.prototype.findQualifyingSymbolPathInScopeSymbol = function (scopeSymbol) { + var thisPath = this.pathToRoot(); + if (thisPath.length === 1) { + return thisPath; + } + + var scopeSymbolPath; + if (scopeSymbol) { + scopeSymbolPath = scopeSymbol.pathToRoot(); + } else { + return thisPath; + } + + var thisCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(thisPath, function (thisNode) { + return TypeScript.ArrayUtilities.contains(scopeSymbolPath, thisNode); + }); + if (thisCommonAncestorIndex > 0) { + var thisCommonAncestor = thisPath[thisCommonAncestorIndex]; + var scopeCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(scopeSymbolPath, function (scopeNode) { + return scopeNode === thisCommonAncestor; + }); + TypeScript.Debug.assert(thisPath.length - thisCommonAncestorIndex === scopeSymbolPath.length - scopeCommonAncestorIndex); + + for (; thisCommonAncestorIndex < thisPath.length; thisCommonAncestorIndex++, scopeCommonAncestorIndex++) { + if (!PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope(thisPath[thisCommonAncestorIndex - 1], scopeSymbolPath, scopeCommonAncestorIndex)) { + break; + } } } - if (commonNodeIndex >= 0) { - return aPath.slice(0, commonNodeIndex); + if (thisCommonAncestorIndex >= 0 && thisCommonAncestorIndex < thisPath.length) { + return thisPath.slice(0, thisCommonAncestorIndex); } else { - return aPath; + return thisPath; } }; @@ -35655,6 +35810,7 @@ var TypeScript; }; PullSymbol.prototype.fullName = function (scopeSymbol) { + var _this = this; var path = this.pathToRoot(); var fullName = ""; @@ -35663,23 +35819,23 @@ var TypeScript; }, function (symbol) { return symbol.getNamePartForFullName(); }); - if (aliasFullName != null) { + if (aliasFullName) { return aliasFullName; } for (var i = 1; i < path.length; i++) { var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { - return symbol.fullName(scopeSymbol); + return symbol === _this ? null : symbol.fullName(scopeSymbol); }, function (symbol) { return symbol.getNamePartForFullName(); }); - if (aliasFullName != null) { + if (aliasFullName) { fullName = aliasFullName + "." + fullName; break; } var scopedName = path[i].getNamePartForFullName(); - if (path[i].kind == 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { + if (path[i].kind === 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { break; } @@ -35695,7 +35851,7 @@ var TypeScript; }; PullSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { - var path = this.findCommonAncestorPath(scopeSymbol); + var path = this.findQualifyingSymbolPathInScopeSymbol(scopeSymbol); var fullName = ""; var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { @@ -35703,7 +35859,7 @@ var TypeScript; }, function (symbol) { return symbol.getNamePartForFullName(); }, skipInternalAliasName); - if (aliasFullName != null) { + if (aliasFullName) { return aliasFullName; } @@ -35715,7 +35871,7 @@ var TypeScript; }, function (symbol) { return symbol.getNamePartForFullName(); }, skipInternalAliasName); - if (aliasFullName != null) { + if (aliasFullName) { fullName = aliasFullName + "." + fullName; break; } @@ -35762,9 +35918,9 @@ var TypeScript; PullSymbol.prototype.getTypeNameForFunctionSignature = function (prefix, scopeSymbol, getPrettyTypeName) { var type = this.type; - if (type && !type.isNamedTypeSymbol() && this.kind != 4096 /* Property */ && this.kind != 512 /* Variable */ && this.kind != 2048 /* Parameter */) { + if (type && !type.isNamedTypeSymbol() && this.kind !== 4096 /* Property */ && this.kind !== 512 /* Variable */ && this.kind !== 2048 /* Parameter */) { var signatures = type.getCallSignatures(); - if (signatures.length == 1 || (getPrettyTypeName && signatures.length)) { + if (signatures.length === 1 || (getPrettyTypeName && signatures.length)) { var typeName = new TypeScript.MemberNameArray(); var signatureName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, prefix, false, false, scopeSymbol, getPrettyTypeName); typeName.addAll(signatureName); @@ -35881,7 +36037,7 @@ var TypeScript; var parentDecl = decls[0].getParentDecl(); if (parentDecl) { var parentSymbol = parentDecl.getSymbol(); - if (!parentSymbol || parentDecl.kind == 1 /* Script */) { + if (!parentSymbol || parentDecl.kind === 1 /* Script */) { return true; } @@ -35892,14 +36048,14 @@ var TypeScript; return true; } - if (container.kind == 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().kind == 32 /* DynamicModule */)) { - var containerSymbol = container.kind == 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); + if (container.kind === 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().kind === 32 /* DynamicModule */)) { + var containerSymbol = container.kind === 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); if (PullContainerSymbol.usedAsSymbol(containerSymbol, this)) { return true; } } - if (!this.anyDeclHasFlag(1 /* Exported */) && kind != 4096 /* Property */ && kind != 65536 /* Method */) { + if (!this.anyDeclHasFlag(1 /* Exported */) && kind !== 4096 /* Property */ && kind !== 65536 /* Method */) { return false; } @@ -35910,13 +36066,13 @@ var TypeScript; var ast = decl.ast(); if (ast) { - var enclosingModuleDeclaration = TypeScript.getEnclosingModuleDeclaration(ast); - if (TypeScript.isLastNameOfModule(enclosingModuleDeclaration, ast)) { - return TypeScript.docComments(enclosingModuleDeclaration); + var enclosingModuleDeclaration = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(ast); + if (TypeScript.ASTHelpers.isLastNameOfModule(enclosingModuleDeclaration, ast)) { + return TypeScript.ASTHelpers.docComments(enclosingModuleDeclaration); } - if (ast.kind() != 130 /* ModuleDeclaration */ || decl.kind != 512 /* Variable */) { - return TypeScript.docComments(ast); + if (ast.kind() !== 130 /* ModuleDeclaration */ || decl.kind !== 512 /* Variable */) { + return TypeScript.ASTHelpers.docComments(ast); } } @@ -35929,10 +36085,10 @@ var TypeScript; return docComments; } - var isParameter = symbol.kind == 2048 /* Parameter */; + var isParameter = symbol.kind === 2048 /* Parameter */; var decls = symbol.getDeclarations(); for (var i = 0; i < decls.length; i++) { - if (isParameter && decls[i].kind == 4096 /* Property */) { + if (isParameter && decls[i].kind === 4096 /* Property */) { continue; } docComments = docComments.concat(this.getDocCommentsOfDecl(decls[i])); @@ -35968,14 +36124,14 @@ var TypeScript; PullSymbol.prototype.docComments = function (useConstructorAsClass) { var decls = this.getDeclarations(); - if (useConstructorAsClass && decls.length && decls[0].kind == 32768 /* ConstructorMethod */) { + if (useConstructorAsClass && decls.length && decls[0].kind === 32768 /* ConstructorMethod */) { var classDecl = decls[0].getParentDecl(); return this.getDocCommentText(this.getDocCommentsOfDecl(classDecl)); } if (this._docComments === null) { var docComments = ""; - if (!useConstructorAsClass && this.kind == 2097152 /* ConstructSignature */ && decls.length && decls[0].kind == 8 /* Class */) { + if (!useConstructorAsClass && this.kind === 2097152 /* ConstructSignature */ && decls.length && decls[0].kind === 8 /* Class */) { var classSymbol = this.returnType; var extendedTypes = classSymbol.getExtendedTypes(); if (extendedTypes.length) { @@ -35983,7 +36139,7 @@ var TypeScript; } else { docComments = ""; } - } else if (this.kind == 2048 /* Parameter */) { + } else if (this.kind === 2048 /* Parameter */) { var parameterComments = []; var funcContainer = this.getEnclosingSignature(); @@ -36000,7 +36156,7 @@ var TypeScript; docComments = parameterComments.join("\n"); } else { var getSymbolComments = true; - if (this.kind == 16777216 /* FunctionType */) { + if (this.kind === 16777216 /* FunctionType */) { var functionSymbol = this.getFunctionSymbol(); if (functionSymbol) { @@ -36016,10 +36172,10 @@ var TypeScript; } if (getSymbolComments) { docComments = this.getDocCommentText(this.getDocCommentArray(this)); - if (docComments == "") { - if (this.kind == 1048576 /* CallSignature */) { + if (docComments === "") { + if (this.kind === 1048576 /* CallSignature */) { var callTypeSymbol = this.functionType; - if (callTypeSymbol && callTypeSymbol.getCallSignatures().length == 1) { + if (callTypeSymbol && callTypeSymbol.getCallSignatures().length === 1) { docComments = callTypeSymbol.docComments(); } } @@ -36230,34 +36386,41 @@ var TypeScript; })(); TypeScript.PullSymbol = PullSymbol; + + var PullSignatureSymbol = (function (_super) { __extends(PullSignatureSymbol, _super); - function PullSignatureSymbol(kind) { + function PullSignatureSymbol(kind, _isDefinition) { + if (typeof _isDefinition === "undefined") { _isDefinition = false; } _super.call(this, "", kind); + this._isDefinition = _isDefinition; this._memberTypeParameterNameCache = null; this._stringConstantOverload = undefined; this.parameters = TypeScript.sentinelEmptyArray; - this.typeParameters = null; + this._typeParameters = null; this.returnType = null; this.functionType = null; this.hasOptionalParam = false; this.nonOptionalParamCount = 0; this.hasVarArgs = false; - this.hasAGenericParameter = false; + this._allowedToReferenceTypeParameters = null; + this._instantiationCache = null; this.hasBeenChecked = false; this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; } PullSignatureSymbol.prototype.isDefinition = function () { - return false; + return this._isDefinition; }; PullSignatureSymbol.prototype.isGeneric = function () { - return this.hasAGenericParameter || (this.typeParameters && this.typeParameters.length != 0); + var typeParameters = this.getTypeParameters(); + return !!typeParameters && typeParameters.length !== 0; }; PullSignatureSymbol.prototype.addParameter = function (parameter, isOptional) { if (typeof isOptional === "undefined") { isOptional = false; } - if (this.parameters == TypeScript.sentinelEmptyArray) { + if (this.parameters === TypeScript.sentinelEmptyArray) { this.parameters = []; } @@ -36274,25 +36437,32 @@ var TypeScript; }; PullSignatureSymbol.prototype.addTypeParameter = function (typeParameter) { - if (!this.typeParameters) { - this.typeParameters = []; + if (!this._typeParameters) { + this._typeParameters = []; } if (!this._memberTypeParameterNameCache) { this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); } - this.typeParameters[this.typeParameters.length] = typeParameter; + this._typeParameters[this._typeParameters.length] = typeParameter; this._memberTypeParameterNameCache[typeParameter.getName()] = typeParameter; }; + PullSignatureSymbol.prototype.addTypeParametersFromReturnType = function () { + var typeParameters = this.returnType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addTypeParameter(typeParameters[i]); + } + }; + PullSignatureSymbol.prototype.getTypeParameters = function () { - if (!this.typeParameters) { - this.typeParameters = []; + if (!this._typeParameters) { + this._typeParameters = []; } - return this.typeParameters; + return this._typeParameters; }; PullSignatureSymbol.prototype.findTypeParameter = function (name) { @@ -36301,10 +36471,8 @@ var TypeScript; if (!this._memberTypeParameterNameCache) { this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); - if (this.typeParameters) { - for (var i = 0; i < this.typeParameters.length; i++) { - this._memberTypeParameterNameCache[this.typeParameters[i].getName()] = this.typeParameters[i]; - } + for (var i = 0; i < this.getTypeParameters().length; i++) { + this._memberTypeParameterNameCache[this._typeParameters[i].getName()] = this._typeParameters[i]; } } @@ -36313,6 +36481,38 @@ var TypeScript; return memberSymbol; }; + PullSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullSignatureSymbol.prototype.addSpecialization = function (specializedVersionOfThisSignature, typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + this._instantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisSignature; + }; + + PullSignatureSymbol.prototype.getSpecialization = function (typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + return null; + } + + var result = this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + }; + PullSignatureSymbol.prototype.isStringConstantOverloadSignature = function () { if (this._stringConstantOverload === undefined) { var params = this.parameters; @@ -36328,6 +36528,20 @@ var TypeScript; return this._stringConstantOverload; }; + PullSignatureSymbol.prototype.getParameterTypeAtIndex = function (iParam) { + if (iParam < this.parameters.length - 1 || (iParam < this.parameters.length && !this.hasVarArgs)) { + return this.parameters[iParam].type; + } else if (this.hasVarArgs) { + var paramType = this.parameters[this.parameters.length - 1].type; + if (paramType.isArrayNamedTypeReference()) { + paramType = paramType.getElementType(); + } + return paramType; + } + + return null; + }; + PullSignatureSymbol.getSignatureTypeMemberName = function (candidateSignature, signatures, scopeSymbol) { var allMemberNames = new TypeScript.MemberNameArray(); var signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, "", false, false, scopeSymbol, true, candidateSignature); @@ -36455,75 +36669,110 @@ var TypeScript; return builder; }; + PullSignatureSymbol.prototype.forAllParameterTypes = function (length, predicate) { + if (this.parameters.length < length && !this.hasVarArgs) { + length = this.parameters.length; + } + + for (var i = 0; i < length; i++) { + var paramType = this.getParameterTypeAtIndex(i); + if (!predicate(paramType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.forAllCorrespondingParameterTypesInThisAndOtherSignature = function (otherSignature, predicate) { + var length; + if (this.hasVarArgs) { + length = otherSignature.hasVarArgs ? Math.max(this.parameters.length, otherSignature.parameters.length) : otherSignature.parameters.length; + } else { + length = otherSignature.hasVarArgs ? this.parameters.length : Math.min(this.parameters.length, otherSignature.parameters.length); + } + + for (var i = 0; i < length; i++) { + var thisParamType = this.getParameterTypeAtIndex(i); + var otherParamType = otherSignature.getParameterTypeAtIndex(i); + if (!predicate(thisParamType, otherParamType, i)) { + return false; + } + } + + return true; + }; + PullSignatureSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap) !== 0; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap) { var signature = this; if (signature.inWrapCheck) { - return false; + return 0; } + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap); + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap) { + var signature = this; signature.inWrapCheck = true; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(signature); + var wrappingTypeParameterID = signature.returnType ? signature.returnType.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; - var wrapsSomeTypeParameter = false; - - if (signature.returnType && signature.returnType.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - } - - if (!wrapsSomeTypeParameter) { - var parameters = signature.parameters; - - for (var i = 0; i < parameters.length; i++) { - if (!parameters[i].type) { - parameters[i]._resolveDeclaredSymbol(); - } - - if (parameters[i].type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } + var parameters = signature.parameters; + for (var i = 0; !wrappingTypeParameterID && i < parameters.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(parameters[i]); + wrappingTypeParameterID = parameters[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); } signature.inWrapCheck = false; - return wrapsSomeTypeParameter; + return wrappingTypeParameterID; }; - PullSignatureSymbol.prototype.wrapsSomeNestedTypeIntoInfiniteExpansion = function (typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap) { - if (this.inWrapCheck) { - return isCheckingTypeArgumentList; + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; } - if (knownWrapMap.valueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID) != undefined) { - return knownWrapMap.valueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID); + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; } - knownWrapMap.setValueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID, isCheckingTypeArgumentList); + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; - this.inWrapCheck = true; + return wrapsIntoInfinitelyExpandingTypeReference; + }; - var wrapsSomeWrappedTypeParameter = false; - - if (this.returnType && this.returnType._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - wrapsSomeWrappedTypeParameter = true; + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + if (this.returnType && this.returnType._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; } - if (!wrapsSomeWrappedTypeParameter) { - var parameters = this.parameters; + var parameters = this.parameters; - for (var i = 0; i < parameters.length; i++) { - if (parameters[i].type && parameters[i].type._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - wrapsSomeWrappedTypeParameter = true; - break; - } + for (var i = 0; i < parameters.length; i++) { + if (parameters[i].type && parameters[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; } } - knownWrapMap.setValueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID, wrapsSomeWrappedTypeParameter); - - this.inWrapCheck = false; - - return wrapsSomeWrappedTypeParameter; + return false; }; return PullSignatureSymbol; })(PullSymbol); @@ -36537,6 +36786,7 @@ var TypeScript; this._enclosedMemberTypes = null; this._enclosedMemberContainers = null; this._typeParameters = null; + this._allowedToReferenceTypeParameters = null; this._specializedVersionsOfThisType = null; this._arrayVersionOfThisType = null; this._implementedTypes = null; @@ -36548,6 +36798,7 @@ var TypeScript; this._constructSignatures = null; this._indexSignatures = null; this._allIndexSignatures = null; + this._allIndexSignaturesOfAugmentedType = null; this._memberNameCache = null; this._enclosedTypeNameCache = null; this._enclosedContainerCache = null; @@ -36568,7 +36819,9 @@ var TypeScript; this._inMemberTypeNameEx = false; this.inSymbolPrivacyCheck = false; this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; this.typeReference = null; + this._widenedType = null; this._isArrayNamedTypeReference = undefined; this.type = this; } @@ -36583,7 +36836,6 @@ var TypeScript; PullTypeSymbol.prototype.computeIsArrayNamedTypeReference = function () { var typeArgs = this.getTypeArguments(); if (typeArgs && this.getTypeArguments().length === 1 && this.name === "Array") { - var container = this.getContainer(); var declaration = this.getDeclarations()[0]; if (declaration && declaration.getParentDecl() && declaration.getParentDecl().getParentDecl() === null) { @@ -36598,13 +36850,13 @@ var TypeScript; return true; }; PullTypeSymbol.prototype.isClass = function () { - return this.kind == 8 /* Class */ || (this._constructorMethod != null); + return this.kind === 8 /* Class */ || (this._constructorMethod !== null); }; PullTypeSymbol.prototype.isFunction = function () { - return (this.kind & (33554432 /* ConstructorType */ | 16777216 /* FunctionType */)) != 0; + return (this.kind & (33554432 /* ConstructorType */ | 16777216 /* FunctionType */)) !== 0; }; PullTypeSymbol.prototype.isConstructor = function () { - return this.kind == 33554432 /* ConstructorType */; + return this.kind === 33554432 /* ConstructorType */; }; PullTypeSymbol.prototype.isTypeParameter = function () { return false; @@ -36616,7 +36868,7 @@ var TypeScript; return false; }; PullTypeSymbol.prototype.isEnum = function () { - return this.kind == 64 /* Enum */; + return this.kind === 64 /* Enum */; }; PullTypeSymbol.prototype.getTypeParameterArgumentMap = function () { @@ -36624,7 +36876,11 @@ var TypeScript; }; PullTypeSymbol.prototype.isObject = function () { - return TypeScript.hasFlag(this.kind, 8 /* Class */ | 33554432 /* ConstructorType */ | 64 /* Enum */ | 16777216 /* FunctionType */ | 16 /* Interface */ | 8388608 /* ObjectType */); + return TypeScript.hasFlag(this.kind, 8 /* Class */ | 33554432 /* ConstructorType */ | 64 /* Enum */ | 16777216 /* FunctionType */ | 16 /* Interface */ | 8388608 /* ObjectType */ | 256 /* ObjectLiteral */); + }; + + PullTypeSymbol.prototype.isFunctionType = function () { + return this.getCallSignatures().length > 0 || this.getConstructSignatures().length > 0; }; PullTypeSymbol.prototype.getKnownBaseTypeCount = function () { @@ -36645,7 +36901,7 @@ var TypeScript; }; PullTypeSymbol.prototype.hasMembers = function () { - if (this._members != TypeScript.sentinelEmptyArray) { + if (this._members !== TypeScript.sentinelEmptyArray) { return true; } @@ -36720,8 +36976,8 @@ var TypeScript; var nonMemberSymbol = this._containedNonMemberTypeNameCache[typeName]; - if (nonMemberSymbol && kind != 0 /* None */) { - nonMemberSymbol = ((nonMemberSymbol.kind & kind) != 0) ? nonMemberSymbol : null; + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; } return nonMemberSymbol; @@ -36735,8 +36991,8 @@ var TypeScript; var nonMemberSymbol = this._containedNonMemberContainerCache[containerName]; - if (nonMemberSymbol && kind != 0 /* None */) { - nonMemberSymbol = ((nonMemberSymbol.kind & kind) != 0) ? nonMemberSymbol : null; + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; } return nonMemberSymbol; @@ -36862,16 +37118,6 @@ var TypeScript; this._typeParameterNameCache[typeParameter.getName()] = typeParameter; }; - PullTypeSymbol.prototype.addConstructorTypeParameter = function (typeParameter) { - this.addTypeParameter(typeParameter); - - var constructSignatures = this.getConstructSignatures(); - - for (var i = 0; i < constructSignatures.length; i++) { - constructSignatures[i].addTypeParameter(typeParameter); - } - }; - PullTypeSymbol.prototype.getMembers = function () { return this._members; }; @@ -36901,31 +37147,52 @@ var TypeScript; return this._typeParameters; }; + PullTypeSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + if (!!(this.kind && 8216 /* SomeInstantiatableType */) && this.isNamedTypeSymbol() && !this.isTypeParameter()) { + return this.getTypeParameters(); + } + + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + PullTypeSymbol.prototype.isGeneric = function () { return (this._typeParameters && this._typeParameters.length > 0) || this._hasGenericSignature || this._hasGenericMember || this.isArrayNamedTypeReference(); }; - PullTypeSymbol.prototype.canUseSimpleInstantiationCache = function (substitutingTypes) { - return substitutingTypes.length === 1 && substitutingTypes[0].kind !== 8388608 /* ObjectType */; - }; - - PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, substitutingTypes) { - if (!substitutingTypes || !substitutingTypes.length) { - return; + PullTypeSymbol.prototype.canUseSimpleInstantiationCache = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return true; } - if (this.canUseSimpleInstantiationCache(substitutingTypes)) { + var typeParameters = this.getTypeParameters(); + return typeArgumentMap && this.isNamedTypeSymbol() && typeParameters.length === 1 && typeArgumentMap[typeParameters[0].pullSymbolID].kind !== 8388608 /* ObjectType */; + }; + + PullTypeSymbol.prototype.getSimpleInstantiationCacheId = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return typeArgumentMap[0].pullSymbolID; + } + + return typeArgumentMap[this.getTypeParameters()[0].pullSymbolID].pullSymbolID; + }; + + PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { if (!this._simpleInstantiationCache) { this._simpleInstantiationCache = []; } - this._simpleInstantiationCache[substitutingTypes[0].pullSymbolID] = specializedVersionOfThisType; + this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)] = specializedVersionOfThisType; } else { if (!this._complexInstantiationCache) { this._complexInstantiationCache = TypeScript.createIntrinsicsObject(); } - this._complexInstantiationCache[getIDForTypeSubstitutions(substitutingTypes)] = specializedVersionOfThisType; + this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisType; } if (!this._specializedVersionsOfThisType) { @@ -36935,25 +37202,25 @@ var TypeScript; this._specializedVersionsOfThisType.push(specializedVersionOfThisType); }; - PullTypeSymbol.prototype.getSpecialization = function (substitutingTypes) { - if (!substitutingTypes || !substitutingTypes.length) { - return null; - } - - if (this.canUseSimpleInstantiationCache(substitutingTypes)) { + PullTypeSymbol.prototype.getSpecialization = function (typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { if (!this._simpleInstantiationCache) { return null; } - var result = this._simpleInstantiationCache[substitutingTypes[0].pullSymbolID]; - return result ? result : null; + var result = this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)]; + return result || null; } else { if (!this._complexInstantiationCache) { return null; } - var result = this._complexInstantiationCache[getIDForTypeSubstitutions(substitutingTypes)]; - return result ? result : null; + if (this.getAllowedToReferenceTypeParameters().length == 0) { + return this; + } + + var result = this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; } }; @@ -36973,13 +37240,11 @@ var TypeScript; return this.getTypeParameters(); }; - PullTypeSymbol.prototype.addCallSignature = function (callSignature) { + PullTypeSymbol.prototype.addCallSignaturePrerequisite = function (callSignature) { if (!this._callSignatures) { this._callSignatures = []; } - this._callSignatures[this._callSignatures.length] = callSignature; - if (callSignature.isGeneric()) { this._hasGenericSignature = true; } @@ -36987,13 +37252,26 @@ var TypeScript; callSignature.functionType = this; }; - PullTypeSymbol.prototype.addConstructSignature = function (constructSignature) { + PullTypeSymbol.prototype.appendCallSignature = function (callSignature) { + this.addCallSignaturePrerequisite(callSignature); + this._callSignatures.push(callSignature); + }; + + PullTypeSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + this.addCallSignaturePrerequisite(callSignature); + TypeScript.Debug.assert(index <= this._callSignatures.length); + if (index === this._callSignatures.length) { + this._callSignatures.push(callSignature); + } else { + this._callSignatures.splice(index, 0, callSignature); + } + }; + + PullTypeSymbol.prototype.addConstructSignaturePrerequisite = function (constructSignature) { if (!this._constructSignatures) { this._constructSignatures = []; } - this._constructSignatures[this._constructSignatures.length] = constructSignature; - if (constructSignature.isGeneric()) { this._hasGenericSignature = true; } @@ -37001,6 +37279,21 @@ var TypeScript; constructSignature.functionType = this; }; + PullTypeSymbol.prototype.appendConstructSignature = function (constructSignature) { + this.addConstructSignaturePrerequisite(constructSignature); + this._constructSignatures.push(constructSignature); + }; + + PullTypeSymbol.prototype.insertConstructSignatureAtIndex = function (constructSignature, index) { + this.addConstructSignaturePrerequisite(constructSignature); + TypeScript.Debug.assert(index <= this._constructSignatures.length); + if (index === this._constructSignatures.length) { + this._constructSignatures.push(constructSignature); + } else { + this._constructSignatures.splice(index, 0, constructSignature); + } + }; + PullTypeSymbol.prototype.addIndexSignature = function (indexSignature) { if (!this._indexSignatures) { this._indexSignatures = []; @@ -37015,30 +37308,14 @@ var TypeScript; indexSignature.functionType = this; }; - PullTypeSymbol.prototype.addUnhiddenSignaturesFromBaseType = function (derivedTypeSignatures, baseTypeSignatures, signaturesBeingAggregated) { - if (!derivedTypeSignatures) { - signaturesBeingAggregated.push.apply(signaturesBeingAggregated, baseTypeSignatures); - return; - } - - var resolver = this._getResolver(); - for (var i = 0; i < baseTypeSignatures.length; i++) { - var baseSignature = baseTypeSignatures[i]; - - var signatureIsHidden = TypeScript.ArrayUtilities.any(derivedTypeSignatures, function (sig) { - return resolver.signaturesAreIdentical(baseSignature, sig, false); - }); - - if (!signatureIsHidden) { - signaturesBeingAggregated.push(baseSignature); - } - } - }; - PullTypeSymbol.prototype.hasOwnCallSignatures = function () { return this._callSignatures !== null; }; + PullTypeSymbol.prototype.getOwnCallSignatures = function () { + return this._callSignatures || TypeScript.sentinelEmptyArray; + }; + PullTypeSymbol.prototype.getCallSignatures = function () { if (this._allCallSignatures) { return this._allCallSignatures; @@ -37056,7 +37333,7 @@ var TypeScript; continue; } - this.addUnhiddenSignaturesFromBaseType(this._callSignatures, this._extendedTypes[i].getCallSignatures(), signatures); + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._callSignatures, this._extendedTypes[i].getCallSignatures(), signatures); } } @@ -37069,6 +37346,10 @@ var TypeScript; return this._constructSignatures !== null; }; + PullTypeSymbol.prototype.getOwnConstructSignatures = function () { + return this._constructSignatures || TypeScript.sentinelEmptyArray; + }; + PullTypeSymbol.prototype.getConstructSignatures = function () { var signatures = []; @@ -37082,7 +37363,7 @@ var TypeScript; continue; } - this.addUnhiddenSignaturesFromBaseType(this._constructSignatures, this._extendedTypes[i].getConstructSignatures(), signatures); + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._constructSignatures, this._extendedTypes[i].getConstructSignatures(), signatures); } } @@ -37114,7 +37395,7 @@ var TypeScript; continue; } - this.addUnhiddenSignaturesFromBaseType(this._indexSignatures, this._extendedTypes[i].getIndexSignatures(), signatures); + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._indexSignatures, this._extendedTypes[i].getIndexSignatures(), signatures); } } @@ -37123,6 +37404,45 @@ var TypeScript; return signatures; }; + PullTypeSymbol.prototype.getIndexSignaturesOfAugmentedType = function (resolver, globalFunctionInterface, globalObjectInterface) { + if (!this._allIndexSignaturesOfAugmentedType) { + var initialIndexSignatures = this.getIndexSignatures(); + var shouldAddFunctionSignatures = false; + var shouldAddObjectSignatures = false; + + if (globalFunctionInterface && this.isFunctionType() && this !== globalFunctionInterface) { + var functionIndexSignatures = globalFunctionInterface.getIndexSignatures(); + if (functionIndexSignatures.length) { + shouldAddFunctionSignatures = true; + } + } + + if (globalObjectInterface && this !== globalObjectInterface) { + var objectIndexSignatures = globalObjectInterface.getIndexSignatures(); + if (objectIndexSignatures.length) { + shouldAddObjectSignatures = true; + } + } + + if (shouldAddFunctionSignatures || shouldAddObjectSignatures) { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures.slice(0); + if (shouldAddFunctionSignatures) { + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, functionIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + if (shouldAddObjectSignatures) { + if (shouldAddFunctionSignatures) { + initialIndexSignatures = initialIndexSignatures.concat(functionIndexSignatures); + } + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, objectIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + } else { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures; + } + } + + return this._allIndexSignaturesOfAugmentedType; + }; + PullTypeSymbol.prototype.addImplementedType = function (implementedType) { if (!implementedType) { return; @@ -37293,8 +37613,8 @@ var TypeScript; memberSymbol = this._enclosedTypeNameCache[name]; - if (memberSymbol && kind != 0 /* None */) { - memberSymbol = ((memberSymbol.kind & kind) != 0) ? memberSymbol : null; + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; } return memberSymbol; @@ -37310,8 +37630,8 @@ var TypeScript; memberSymbol = this._enclosedContainerCache[name]; - if (memberSymbol && kind != 0 /* None */) { - memberSymbol = ((memberSymbol.kind & kind) != 0) ? memberSymbol : null; + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; } return memberSymbol; @@ -37320,7 +37640,7 @@ var TypeScript; PullTypeSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { var allMembers = []; - if (this._members != TypeScript.sentinelEmptyArray) { + if (this._members !== TypeScript.sentinelEmptyArray) { for (var i = 0, n = this._members.length; i < n; i++) { var member = this._members[i]; if ((member.kind & searchDeclKind) && (memberVisiblity !== 2 /* externallyVisible */ || !member.anyDeclHasFlag(2 /* Private */))) { @@ -37386,7 +37706,7 @@ var TypeScript; PullTypeSymbol.prototype.isNamedTypeSymbol = function () { var kind = this.kind; - if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 128 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.name != "")) { + if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 128 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.name !== "")) { return true; } @@ -37398,8 +37718,9 @@ var TypeScript; return s; }; - PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) { - if (this.isArrayNamedTypeReference()) { + PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName, shouldAllowArrayType) { + if (typeof shouldAllowArrayType === "undefined") { shouldAllowArrayType = true; } + if (this.isArrayNamedTypeReference() && shouldAllowArrayType) { var elementType = this.getElementType(); var elementMemberName = elementType ? (elementType.isArrayNamedTypeReference() || elementType.isNamedTypeSymbol() ? elementType.getScopedNameEx(scopeSymbol, false, false, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) : elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName)) : TypeScript.MemberName.create("any"); return TypeScript.MemberName.create(elementMemberName, "", "[]"); @@ -37436,8 +37757,8 @@ var TypeScript; } var functionSymbol = this.getFunctionSymbol(); - if (functionSymbol && functionSymbol.kind == 16384 /* Function */ && !TypeScript.PullHelpers.isSymbolLocal(functionSymbol)) { - return functionSymbol; + if (functionSymbol && functionSymbol.kind === 16384 /* Function */ && !TypeScript.PullHelpers.isSymbolLocal(functionSymbol)) { + return TypeScript.PullHelpers.isExportedSymbolInClodule(functionSymbol) ? null : functionSymbol; } return null; @@ -37463,10 +37784,10 @@ var TypeScript; this._inMemberTypeNameEx = true; var allMemberNames = new TypeScript.MemberNameArray(); - var curlies = !topLevel || indexSignatures.length != 0; + var curlies = !topLevel || indexSignatures.length !== 0; var delim = "; "; for (var i = 0; i < members.length; i++) { - if (members[i].kind == 65536 /* Method */ && members[i].type.hasOnlyOverloadCallSignatures()) { + if (members[i].kind === 65536 /* Method */ && members[i].type.hasOnlyOverloadCallSignatures()) { var methodCallSignatures = members[i].type.getCallSignatures(); var nameStr = members[i].getDisplayName(scopeSymbol) + (members[i].isOptional ? "?" : ""); ; @@ -37524,32 +37845,55 @@ var TypeScript; return 2 /* Closed */; }; - PullTypeSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap) { + PullTypeSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap, skipTypeArgumentCheck) != 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap, skipTypeArgumentCheck) { var type = this; - var wrapsSomeTypeParameter = false; - if (type.isTypeParameter()) { - if (typeParameterArgumentMap[type.pullSymbolID]) { - return true; + if (typeParameterArgumentMap[type.pullSymbolID] || typeParameterArgumentMap[type.getRootSymbol().pullSymbolID]) { + return type.pullSymbolID; } var constraint = type.getConstraint(); - - if (constraint && constraint.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - return true; - } - - return false; + var wrappingTypeParameterID = constraint ? constraint.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + return wrappingTypeParameterID; } if (type.inWrapCheck) { - return wrapsSomeTypeParameter; + return 0; } - type.inWrapCheck = true; + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap, skipTypeArgumentCheck); + + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDFromSignatures = function (signatures, typeParameterArgumentMap) { + for (var i = 0; i < signatures.length; i++) { + var wrappingTypeParameterID = signatures[i].getWrappingTypeParameterID(typeParameterArgumentMap); + if (wrappingTypeParameterID !== 0) { + return wrappingTypeParameterID; + } + } + + return 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + var wrappingTypeParameterID = 0; + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = true; - if (!wrapsSomeTypeParameter) { var typeArguments = type.getTypeArguments(); if (type.isGeneric() && !typeArguments) { @@ -37557,217 +37901,131 @@ var TypeScript; } if (typeArguments) { - for (var i = 0; i < typeArguments.length; i++) { - if (typeArguments[i].wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } + for (var i = 0; !wrappingTypeParameterID && i < typeArguments.length; i++) { + wrappingTypeParameterID = typeArguments[i].getWrappingTypeParameterID(typeParameterArgumentMap); } } } - if (!(type.kind & 8216 /* SomeInstantiatableType */) || !type.name) { - if (!wrapsSomeTypeParameter) { - var members = type.getAllMembers(68147712 /* SomeValue */, 0 /* all */); - - for (var i = 0; i < members.length; i++) { - if (members[i].type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } + if (skipTypeArgumentCheck || !(type.kind & 8216 /* SomeInstantiatableType */) || !type.name) { + var members = type.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; !wrappingTypeParameterID && i < members.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(members[i]); + wrappingTypeParameterID = members[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); } - if (!wrapsSomeTypeParameter) { - var sigs = type.getCallSignatures(); - - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } - } - - if (!wrapsSomeTypeParameter) { - sigs = type.getConstructSignatures(); - - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } - } - - if (!wrapsSomeTypeParameter) { - sigs = type.getIndexSignatures(); - - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeTypeParameter(typeParameterArgumentMap)) { - wrapsSomeTypeParameter = true; - break; - } - } - } + wrappingTypeParameterID = wrappingTypeParameterID || this.getWrappingTypeParameterIDFromSignatures(type.getCallSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getConstructSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getIndexSignatures(), typeParameterArgumentMap); } - type.inWrapCheck = false; + if (!skipTypeArgumentCheck) { + type.inWrapCheck = false; + } - return wrapsSomeTypeParameter; + return wrappingTypeParameterID; }; - PullTypeSymbol.prototype.wrapsSomeNestedTypeIntoInfiniteExpansion = function (typeBeingWrapped) { - if (!this.isArrayNamedTypeReference() && this.isNamedTypeSymbol()) { - var knownWrapMap = TypeScript.BitMatrix.getBitMatrix(true); - var result = this._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, false, knownWrapMap); - knownWrapMap.release(); - - return result; - } - - return false; + PullTypeSymbol.prototype.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType) { + TypeScript.Debug.assert(this.isNamedTypeSymbol()); + TypeScript.Debug.assert(TypeScript.PullHelpers.getRootType(enclosingType) == enclosingType); + var knownWrapMap = TypeScript.BitMatrix.getBitMatrix(true); + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap); + knownWrapMap.release(); + return wrapsIntoInfinitelyExpandingTypeReference; }; - PullTypeSymbol.prototype.isTypeEquivalentToRootSymbol = function () { - if (this.isTypeReference()) { - if (this.getIsSpecialized()) { - var typeArguments = this.getTypeArguments(); - var rootTypeArguments = this.getRootSymbol().getTypeArguments(); - if (typeArguments) { - for (var i = 0; i < typeArguments.length; i++) { - if (!typeArguments[i].isTypeParameter() && !(rootTypeArguments && rootTypeArguments[i] == typeArguments[i].getRootSymbol())) { - return false; - } - } - return true; - } - - return false; - } else { - return true; - } + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; } - return false; - }; - - PullTypeSymbol.prototype.isTypeBeingWrapped = function (typeBeingWrapped) { - if (this.inWrapCheck || this == typeBeingWrapped) { - return true; - } - - if (typeBeingWrapped.isTypeEquivalentToRootSymbol()) { - return this.isTypeBeingWrapped(typeBeingWrapped.getRootSymbol()); - } - - return false; - }; - - PullTypeSymbol.prototype.anyRootTypeBeingWrapped = function (typeBeingWrapped) { - var prevRootType = this; - var rootType = this.getRootSymbol(); - while (rootType != prevRootType) { - if (rootType.isTypeBeingWrapped(typeBeingWrapped)) { - return true; - } - - prevRootType = rootType; - rootType = rootType.getRootSymbol(); - } - - return false; - }; - - PullTypeSymbol.prototype._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse = function (typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap) { - if (this.isArrayNamedTypeReference()) { - return this.getElementType()._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap); - } - - if (this.isTypeBeingWrapped(typeBeingWrapped)) { - return isCheckingTypeArgumentList; - } - - if (knownWrapMap.valueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID) != undefined) { - return knownWrapMap.valueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID); - } - - if (this.isPrimitive() || this.isTypeParameter()) { + if (this.inWrapInfiniteExpandingReferenceCheck) { return false; } - this.inWrapCheck = true; + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; - var wrapsSomeWrappedTypeParameter = false; - - knownWrapMap.setValueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID, false); - - wrapsSomeWrappedTypeParameter = this._wrapsSomeNestedTypeIntoInfiniteExpansionWorker(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap); - - knownWrapMap.setValueAt(this.pullSymbolID, typeBeingWrapped.pullSymbolID, wrapsSomeWrappedTypeParameter); - - this.inWrapCheck = false; - - return wrapsSomeWrappedTypeParameter; + return wrapsIntoInfinitelyExpandingTypeReference; }; - PullTypeSymbol.prototype._wrapsSomeNestedTypeIntoInfiniteExpansionWorker = function (typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap) { + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + var thisRootType = TypeScript.PullHelpers.getRootType(this); + + if (thisRootType != enclosingType) { + var thisIsNamedType = this.isNamedTypeSymbol(); + + if (thisIsNamedType) { + if (thisRootType.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + thisRootType.inWrapInfiniteExpandingReferenceCheck = true; + } + + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure(enclosingType, knownWrapMap); + + if (thisIsNamedType) { + thisRootType.inWrapInfiniteExpandingReferenceCheck = false; + } + + return wrapsIntoInfinitelyExpandingTypeReference; + } + + var enclosingTypeParameters = enclosingType.getTypeParameters(); var typeArguments = this.getTypeArguments(); - if (typeArguments) { - for (var i = 0; i < typeArguments.length; i++) { - if (typeArguments[i]._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, true, knownWrapMap)) { - return true; - } + for (var i = 0; i < typeArguments.length; i++) { + if (TypeScript.ArrayUtilities.contains(enclosingTypeParameters, typeArguments[i])) { + continue; } - } - if (this.anyRootTypeBeingWrapped(typeBeingWrapped)) { - if (isCheckingTypeArgumentList && this.isTypeReference() && !this.getIsSpecialized()) { + if (typeArguments[i].wrapsSomeTypeParameter(this.getTypeParameterArgumentMap())) { return true; } - - return false; - } else if (!this.isNamedTypeSymbol() || this.isGeneric()) { - var isTypeEquivalentToRootSymbol = this.isTypeEquivalentToRootSymbol(); - var rootType = TypeScript.PullHelpers.getRootType(this); - if (isTypeEquivalentToRootSymbol) { - rootType.inWrapCheck = true; - } - - var members = this.getAllMembers(68147712 /* SomeValue */, 0 /* all */); - for (var i = 0; i < members.length; i++) { - if (members[i].type && members[i].type._wrapsSomeNestedTypeIntoInfiniteExpansionRecurse(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - return true; - } - } - - var sigs = this.getCallSignatures(); - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeNestedTypeIntoInfiniteExpansion(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - return true; - } - } - - sigs = this.getConstructSignatures(); - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeNestedTypeIntoInfiniteExpansion(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - return true; - } - } - - sigs = this.getIndexSignatures(); - for (var i = 0; i < sigs.length; i++) { - if (sigs[i].wrapsSomeNestedTypeIntoInfiniteExpansion(typeBeingWrapped, isCheckingTypeArgumentList, knownWrapMap)) { - return true; - } - } - - if (isTypeEquivalentToRootSymbol) { - rootType.inWrapCheck = false; - } - - return false; } + + return false; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure = function (enclosingType, knownWrapMap) { + var members = this.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; i < members.length; i++) { + if (members[i].type && members[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + var sigs = this.getCallSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getConstructSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getIndexSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.widenedType = function (resolver, ast, context) { + if (!this._widenedType) { + this._widenedType = resolver.widenType(this, ast, context); + } + return this._widenedType; }; return PullTypeSymbol; })(PullSymbol); @@ -37781,7 +38039,15 @@ var TypeScript; this.isResolved = true; } PullPrimitiveTypeSymbol.prototype.isAny = function () { - return this.name === "any"; + return !this.isStringConstant() && this.name === "any"; + }; + + PullPrimitiveTypeSymbol.prototype.isNull = function () { + return !this.isStringConstant() && this.name === "null"; + }; + + PullPrimitiveTypeSymbol.prototype.isUndefined = function () { + return !this.isStringConstant() && this.name === "undefined"; }; PullPrimitiveTypeSymbol.prototype.isStringConstant = function () { @@ -37790,6 +38056,14 @@ var TypeScript; PullPrimitiveTypeSymbol.prototype.setUnresolved = function () { }; + + PullPrimitiveTypeSymbol.prototype.getDisplayName = function () { + if (this.isNull() || this.isUndefined()) { + return "any"; + } else { + return _super.prototype.getDisplayName.call(this); + } + }; return PullPrimitiveTypeSymbol; })(PullTypeSymbol); TypeScript.PullPrimitiveTypeSymbol = PullPrimitiveTypeSymbol; @@ -37808,26 +38082,31 @@ var TypeScript; var PullErrorTypeSymbol = (function (_super) { __extends(PullErrorTypeSymbol, _super); - function PullErrorTypeSymbol(anyType, name) { + function PullErrorTypeSymbol(_anyType, name) { _super.call(this, name); - this.anyType = anyType; + this._anyType = _anyType; + TypeScript.Debug.assert(this._anyType); this.isResolved = true; } PullErrorTypeSymbol.prototype.isError = function () { return true; }; + PullErrorTypeSymbol.prototype._getResolver = function () { + return this._anyType._getResolver(); + }; + PullErrorTypeSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { - return this.anyType.getName(scopeSymbol, useConstraintInName); + return this._anyType.getName(scopeSymbol, useConstraintInName); }; PullErrorTypeSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { - return this.anyType.getName(scopeSymbol, useConstraintInName); + return this._anyType.getName(scopeSymbol, useConstraintInName); }; PullErrorTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { - return this.anyType.getName(scopeSymbol, useConstraintInName); + return this._anyType.getName(scopeSymbol, useConstraintInName); }; return PullErrorTypeSymbol; })(PullPrimitiveTypeSymbol); @@ -37887,7 +38166,7 @@ var TypeScript; return false; } - if (!containerSymbol.isAlias() && containerSymbol.type == symbol) { + if (!containerSymbol.isAlias() && containerSymbol.type === symbol) { return true; } @@ -37896,7 +38175,7 @@ var TypeScript; var typeExportSymbol = moduleSymbol.getExportAssignedTypeSymbol(); var containerExportSymbol = moduleSymbol.getExportAssignedContainerSymbol(); if (valueExportSymbol || typeExportSymbol || containerExportSymbol) { - return valueExportSymbol == symbol || typeExportSymbol == symbol || containerExportSymbol == symbol || PullContainerSymbol.usedAsSymbol(containerExportSymbol, symbol); + return valueExportSymbol === symbol || typeExportSymbol == symbol || containerExportSymbol == symbol || PullContainerSymbol.usedAsSymbol(containerExportSymbol, symbol); } return false; @@ -37918,8 +38197,15 @@ var TypeScript; this._assignedContainer = null; this._isUsedAsValue = false; this._typeUsedExternally = false; + this._isUsedInExportAlias = false; this.retrievingExportAssignment = false; + this.linkedAliasSymbols = null; } + PullTypeAliasSymbol.prototype.isUsedInExportedAlias = function () { + this._resolveDeclaredSymbol(); + return this._isUsedInExportAlias; + }; + PullTypeAliasSymbol.prototype.typeUsedExternally = function () { this._resolveDeclaredSymbol(); return this._typeUsedExternally; @@ -37930,19 +38216,33 @@ var TypeScript; return this._isUsedAsValue; }; - PullTypeAliasSymbol.prototype.setTypeUsedExternally = function (value) { - this._typeUsedExternally = value; + PullTypeAliasSymbol.prototype.setTypeUsedExternally = function () { + this._typeUsedExternally = true; }; - PullTypeAliasSymbol.prototype.setIsUsedAsValue = function (value) { - this._isUsedAsValue = value; + PullTypeAliasSymbol.prototype.setIsUsedInExportedAlias = function () { + this._isUsedInExportAlias = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedInExportedAlias(); + }); + } + }; - this._resolveDeclaredSymbol(); - var resolver = this._getResolver(); - var importDeclStatement = resolver.semanticInfoChain.getASTForDecl(this.getDeclarations()[0]); - var aliasSymbol = resolver.semanticInfoChain.getAliasSymbolForAST(importDeclStatement.moduleReference); - if (aliasSymbol) { - aliasSymbol.setIsUsedAsValue(value); + PullTypeAliasSymbol.prototype.addLinkedAliasSymbol = function (contingentValueSymbol) { + if (!this.linkedAliasSymbols) { + this.linkedAliasSymbols = [contingentValueSymbol]; + } else { + this.linkedAliasSymbols.push(contingentValueSymbol); + } + }; + + PullTypeAliasSymbol.prototype.setIsUsedAsValue = function () { + this._isUsedAsValue = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedAsValue(); + }); } }; @@ -38005,7 +38305,7 @@ var TypeScript; this.retrievingExportAssignment = true; var sym = this._assignedType.getExportAssignedTypeSymbol(); this.retrievingExportAssignment = false; - } else if (this._assignedType != this._assignedContainer) { + } else if (this._assignedType !== this._assignedContainer) { return this._assignedType; } } @@ -38110,31 +38410,15 @@ var TypeScript; })(PullTypeSymbol); TypeScript.PullTypeAliasSymbol = PullTypeAliasSymbol; - var PullDefinitionSignatureSymbol = (function (_super) { - __extends(PullDefinitionSignatureSymbol, _super); - function PullDefinitionSignatureSymbol() { - _super.apply(this, arguments); - } - PullDefinitionSignatureSymbol.prototype.isDefinition = function () { - return true; - }; - return PullDefinitionSignatureSymbol; - })(PullSignatureSymbol); - TypeScript.PullDefinitionSignatureSymbol = PullDefinitionSignatureSymbol; - var PullTypeParameterSymbol = (function (_super) { __extends(PullTypeParameterSymbol, _super); - function PullTypeParameterSymbol(name, _isFunctionTypeParameter) { + function PullTypeParameterSymbol(name) { _super.call(this, name, 8192 /* TypeParameter */); - this._isFunctionTypeParameter = _isFunctionTypeParameter; this._constraint = null; } PullTypeParameterSymbol.prototype.isTypeParameter = function () { return true; }; - PullTypeParameterSymbol.prototype.isFunctionTypeParameter = function () { - return this._isFunctionTypeParameter; - }; PullTypeParameterSymbol.prototype.setConstraint = function (constraintType) { this._constraint = constraintType; @@ -38144,6 +38428,34 @@ var TypeScript; return this._constraint; }; + PullTypeParameterSymbol.prototype.getBaseConstraint = function (semanticInfoChain) { + var preBaseConstraint = this.getConstraintRecursively({}); + TypeScript.Debug.assert(preBaseConstraint === null || !preBaseConstraint.isTypeParameter()); + return preBaseConstraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getConstraintRecursively = function (visitedTypeParameters) { + var constraint = this.getConstraint(); + + if (constraint) { + if (constraint.isTypeParameter()) { + var constraintAsTypeParameter = constraint; + if (!visitedTypeParameters[constraintAsTypeParameter.pullSymbolID]) { + visitedTypeParameters[constraintAsTypeParameter.pullSymbolID] = constraintAsTypeParameter; + return constraintAsTypeParameter.getConstraintRecursively(visitedTypeParameters); + } + } else { + return constraint; + } + } + + return null; + }; + + PullTypeParameterSymbol.prototype.getDefaultConstraint = function (semanticInfoChain) { + return this._constraint || semanticInfoChain.emptyTypeSymbol; + }; + PullTypeParameterSymbol.prototype.getCallSignatures = function () { if (this._constraint) { return this._constraint.getCallSignatures(); @@ -38264,80 +38576,79 @@ var TypeScript; })(PullSymbol); TypeScript.PullAccessorSymbol = PullAccessorSymbol; - function getIDForTypeSubstitutions(types) { + function getIDForTypeSubstitutions(instantiatingTypeOrSignature, typeArgumentMap) { var substitution = ""; var members = null; - for (var i = 0; i < types.length; i++) { - if (types[i].kind !== 8388608 /* ObjectType */) { - substitution += types[i].pullSymbolID + "#"; - } else { - var structure = getIDForTypeSubstitutionsFromObjectType(types[i]); - - if (structure) { - substitution += structure; - } else { - substitution += types[i].pullSymbolID + "#"; - } + var allowedToReferenceTypeParameters = instantiatingTypeOrSignature.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedToReferenceTypeParameters.length; i++) { + var typeParameter = allowedToReferenceTypeParameters[i]; + var typeParameterID = typeParameter.pullSymbolID; + var typeArg = typeArgumentMap[typeParameterID]; + if (!typeArg) { + typeArg = typeParameter; } + substitution += typeParameterID + ":" + getIDForTypeSubstitutionsOfType(typeArg); } return substitution; } TypeScript.getIDForTypeSubstitutions = getIDForTypeSubstitutions; - function getIDForTypeSubstitutionsFromObjectType(type) { - var structure = ""; - - if (type.isResolved) { - var members = type.getMembers(); - if (members && members.length) { - for (var j = 0; j < members.length; j++) { - structure += members[j].name + "@" + getIDForTypeSubstitutions([members[j].type]); - } - } - - var callSignatures = type.getCallSignatures(); - if (callSignatures && callSignatures.length) { - for (var j = 0; j < callSignatures.length; j++) { - structure += getIDForTypeSubstitutionFromSignature(callSignatures[j]); - } - } - - var constructSignatures = type.getConstructSignatures(); - if (constructSignatures && constructSignatures.length) { - for (var j = 0; j < constructSignatures.length; j++) { - structure += "new" + getIDForTypeSubstitutionFromSignature(constructSignatures[j]); - } - } - - var indexSignatures = type.getIndexSignatures(); - if (indexSignatures && indexSignatures.length) { - for (var j = 0; j < indexSignatures.length; j++) { - structure += "[]" + getIDForTypeSubstitutionFromSignature(indexSignatures[j]); - } - } + function getIDForTypeSubstitutionsOfType(type) { + var structure; + if (type.isError()) { + structure = "E" + getIDForTypeSubstitutionsOfType(type._anyType); + } else if (!type.isNamedTypeSymbol()) { + structure = getIDForTypeSubstitutionsFromObjectType(type); } - if (structure !== "") { - return "{" + structure + "}"; + if (!structure) { + structure = type.pullSymbolID + "#"; + } + + return structure; + } + + function getIDForTypeSubstitutionsFromObjectType(type) { + if (type.isResolved) { + var getIDForTypeSubStitutionWalker = new GetIDForTypeSubStitutionWalker(); + TypeScript.PullHelpers.walkPullTypeSymbolStructure(type, getIDForTypeSubStitutionWalker); } return null; } - function getIDForTypeSubstitutionFromSignature(signature) { - var structure = "("; - var parameters = signature.parameters; - if (parameters && parameters.length) { - for (var k = 0; k < parameters.length; k++) { - structure += parameters[k].name + "@" + getIDForTypeSubstitutions([parameters[k].type]); - } + var GetIDForTypeSubStitutionWalker = (function () { + function GetIDForTypeSubStitutionWalker() { + this.structure = ""; } - - structure += ")" + getIDForTypeSubstitutions([signature.returnType]); - return structure; - } + GetIDForTypeSubStitutionWalker.prototype.memberSymbolWalk = function (memberSymbol) { + this.structure += memberSymbol.name + "@" + getIDForTypeSubstitutionsOfType(memberSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.callSignatureWalk = function (signatureSymbol) { + this.structure += "("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.constructSignatureWalk = function (signatureSymbol) { + this.structure += "new("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.indexSignatureWalk = function (signatureSymbol) { + this.structure += "[]("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureParameterWalk = function (parameterSymbol) { + this.structure += parameterSymbol.name + "@" + getIDForTypeSubstitutionsOfType(parameterSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureReturnTypeWalk = function (returnType) { + this.structure += ")" + getIDForTypeSubstitutionsOfType(returnType); + return true; + }; + return GetIDForTypeSubStitutionWalker; + })(); (function (GetAllMembersVisiblity) { GetAllMembersVisiblity[GetAllMembersVisiblity["all"] = 0] = "all"; @@ -38349,38 +38660,311 @@ var TypeScript; var GetAllMembersVisiblity = TypeScript.GetAllMembersVisiblity; })(TypeScript || (TypeScript = {})); var TypeScript; +(function (TypeScript) { + var PullTypeEnclosingTypeWalker = (function () { + function PullTypeEnclosingTypeWalker() { + this.currentSymbols = null; + } + PullTypeEnclosingTypeWalker.prototype.getEnclosingType = function () { + if (this.currentSymbols && this.currentSymbols.length > 0) { + return this.currentSymbols[0]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype._canWalkStructure = function () { + var enclosingType = this.getEnclosingType(); + return !!enclosingType && enclosingType.isGeneric(); + }; + + PullTypeEnclosingTypeWalker.prototype._getCurrentSymbol = function () { + if (this.currentSymbols && this.currentSymbols.length) { + return this.currentSymbols[this.currentSymbols.length - 1]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.getGenerativeClassification = function () { + if (this._canWalkStructure()) { + var currentType = this.currentSymbols[this.currentSymbols.length - 1]; + if (!currentType) { + return 0 /* Unknown */; + } + + var variableNeededToFixNodeJitterBug = this.getEnclosingType(); + + return currentType.getGenerativeTypeClassification(variableNeededToFixNodeJitterBug); + } + + return 2 /* Closed */; + }; + + PullTypeEnclosingTypeWalker.prototype._pushSymbol = function (symbol) { + return this.currentSymbols.push(symbol); + }; + + PullTypeEnclosingTypeWalker.prototype._popSymbol = function () { + return this.currentSymbols.pop(); + }; + + PullTypeEnclosingTypeWalker.prototype._setEnclosingTypeOfParentDecl = function (decl, setSignature) { + var parentDecl = decl.getParentDecl(); + if (parentDecl) { + if (parentDecl.kind & 8216 /* SomeInstantiatableType */) { + this._setEnclosingTypeWorker(parentDecl.getSymbol(), true); + } else { + this._setEnclosingTypeOfParentDecl(parentDecl, true); + } + + if (this._canWalkStructure()) { + var symbol = decl.getSymbol(); + if (symbol) { + if (symbol.kind == 2048 /* Parameter */ || symbol.kind == 4096 /* Property */ || symbol.kind == 65536 /* Method */ || symbol.kind == 32768 /* ConstructorMethod */ || symbol.kind == 131072 /* FunctionExpression */) { + symbol = symbol.type; + } + + this._pushSymbol(symbol); + } + + if (setSignature) { + var signature = decl.getSignatureSymbol(); + if (signature) { + this._pushSymbol(signature); + } + } + } + } + }; + + PullTypeEnclosingTypeWalker.prototype._setEnclosingTypeWorker = function (symbol, setSignature) { + if (symbol.isType() && symbol.isNamedTypeSymbol()) { + this.currentSymbols = [TypeScript.PullHelpers.getRootType(symbol)]; + return; + } + + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + this._setEnclosingTypeOfParentDecl(decl, setSignature); + if (this._canWalkStructure()) { + return; + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.setCurrentSymbol = function (symbol) { + TypeScript.Debug.assert(this._canWalkStructure()); + this.currentSymbols[this.currentSymbols.length - 1] = symbol; + }; + + PullTypeEnclosingTypeWalker.prototype.startWalkingType = function (symbol) { + var currentSymbols = this.currentSymbols; + + var setEnclosingType = !this.getEnclosingType() || symbol.isNamedTypeSymbol(); + if (setEnclosingType) { + this.currentSymbols = null; + this.setEnclosingType(symbol); + } + return currentSymbols; + }; + + PullTypeEnclosingTypeWalker.prototype.endWalkingType = function (currentSymbolsWhenStartedWalkingTypes) { + this.currentSymbols = currentSymbolsWhenStartedWalkingTypes; + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingType = function (symbol) { + TypeScript.Debug.assert(!this.getEnclosingType()); + this._setEnclosingTypeWorker(symbol, symbol.isSignature()); + }; + + PullTypeEnclosingTypeWalker.prototype.walkMemberType = function (memberName, resolver) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var memberSymbol = currentType ? resolver._getNamedPropertySymbolOfAugmentedType(memberName, currentType) : null; + this._pushSymbol(memberSymbol ? memberSymbol.type : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkMemberType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkSignature = function (kind, index) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var signatures; + if (currentType) { + if (kind == 1048576 /* CallSignature */) { + signatures = currentType.getCallSignatures(); + } else if (kind == 2097152 /* ConstructSignature */) { + signatures = currentType.getConstructSignatures(); + } else { + signatures = currentType.getIndexSignatures(); + } + } + + this._pushSymbol(signatures ? signatures[index] : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkSignature = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeArgument = function (index) { + if (this._canWalkStructure()) { + var typeArgument = null; + var currentType = this._getCurrentSymbol(); + if (currentType) { + var typeArguments = currentType.getTypeArguments(); + typeArgument = typeArguments ? typeArguments[index] : null; + } + this._pushSymbol(typeArgument); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeArgument = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeParameterConstraint = function (index) { + if (this._canWalkStructure()) { + var typeParameters; + var currentSymbol = this._getCurrentSymbol(); + if (currentSymbol) { + if (currentSymbol.isSignature()) { + typeParameters = currentSymbol.getTypeParameters(); + } else { + TypeScript.Debug.assert(currentSymbol.isType()); + typeParameters = currentSymbol.getTypeParameters(); + } + } + this._pushSymbol(typeParameters ? typeParameters[index].getConstraint() : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeParameterConstraint = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkReturnType = function () { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.returnType : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkReturnType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkParameterType = function (iParam) { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.getParameterTypeAtIndex(iParam) : null); + } + }; + PullTypeEnclosingTypeWalker.prototype.postWalkParameterType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.getBothKindOfIndexSignatures = function (resolver, context, includeAugmentedType) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (currentType) { + return resolver._getBothKindsOfIndexSignatures(currentType, context, includeAugmentedType); + } + } + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.walkIndexSignatureReturnType = function (indexSigInfo, useStringIndexSignature, onlySignature) { + if (this._canWalkStructure()) { + var indexSig = indexSigInfo ? (useStringIndexSignature ? indexSigInfo.stringSignature : indexSigInfo.numericSignature) : null; + this._pushSymbol(indexSig); + if (!onlySignature) { + this._pushSymbol(indexSig ? indexSig.returnType : null); + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkIndexSignatureReturnType = function (onlySignature) { + if (this._canWalkStructure()) { + if (!onlySignature) { + this._popSymbol(); + } + this._popSymbol(); + } + }; + return PullTypeEnclosingTypeWalker; + })(); + TypeScript.PullTypeEnclosingTypeWalker = PullTypeEnclosingTypeWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; (function (TypeScript) { var CandidateInferenceInfo = (function () { function CandidateInferenceInfo() { this.typeParameter = null; - this.isFixed = false; + this._inferredTypeAfterFixing = null; this.inferenceCandidates = []; } CandidateInferenceInfo.prototype.addCandidate = function (candidate) { - if (!this.isFixed) { + if (!this._inferredTypeAfterFixing) { this.inferenceCandidates[this.inferenceCandidates.length] = candidate; } }; + + CandidateInferenceInfo.prototype.isFixed = function () { + return !!this._inferredTypeAfterFixing; + }; + + CandidateInferenceInfo.prototype.fixTypeParameter = function (resolver, context) { + var _this = this; + if (!this._inferredTypeAfterFixing) { + var collection = { + getLength: function () { + return _this.inferenceCandidates.length; + }, + getTypeAtIndex: function (index) { + return _this.inferenceCandidates[index].type; + } + }; + + var bestCommonType = resolver.findBestCommonType(collection, context, new TypeScript.TypeComparisonInfo()); + this._inferredTypeAfterFixing = bestCommonType.widenedType(resolver, null, context); + } + }; return CandidateInferenceInfo; })(); TypeScript.CandidateInferenceInfo = CandidateInferenceInfo; - var ArgumentInferenceContext = (function () { - function ArgumentInferenceContext(resolver, argumentsOrParameters) { + var TypeArgumentInferenceContext = (function () { + function TypeArgumentInferenceContext(resolver, context, signatureBeingInferred) { + this.resolver = resolver; + this.context = context; + this.signatureBeingInferred = signatureBeingInferred; this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); this.candidateCache = []; - this.fixedParameterTypes = null; - this.resolver = null; - this.argumentASTs = null; - this.resolver = resolver; - - if (argumentsOrParameters.nonSeparatorAt != undefined) { - this.argumentASTs = argumentsOrParameters; - } else { - this.fixedParameterTypes = argumentsOrParameters; + var typeParameters = signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addInferenceRoot(typeParameters[i]); } } - ArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { + TypeArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { if (this.inferenceCache.valueAt(objectType.pullSymbolID, parameterType.pullSymbolID)) { return true; } else { @@ -38389,12 +38973,12 @@ var TypeScript; } }; - ArgumentInferenceContext.prototype.resetRelationshipCache = function () { + TypeArgumentInferenceContext.prototype.resetRelationshipCache = function () { this.inferenceCache.release(); this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); }; - ArgumentInferenceContext.prototype.addInferenceRoot = function (param) { + TypeArgumentInferenceContext.prototype.addInferenceRoot = function (param) { var info = this.candidateCache[param.pullSymbolID]; if (!info) { @@ -38404,116 +38988,121 @@ var TypeScript; } }; - ArgumentInferenceContext.prototype.getInferenceInfo = function (param) { + TypeArgumentInferenceContext.prototype.getInferenceInfo = function (param) { return this.candidateCache[param.pullSymbolID]; }; - ArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate, fix) { + TypeArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate) { var info = this.getInferenceInfo(param); - if (info) { - if (candidate) { - info.addCandidate(candidate); - } - - if (!info.isFixed) { - info.isFixed = fix; - } + if (info && candidate && info.inferenceCandidates.indexOf(candidate) < 0) { + info.addCandidate(candidate); } }; - ArgumentInferenceContext.prototype.getInferenceArgumentCount = function () { - if (this.fixedParameterTypes) { - return this.fixedParameterTypes.length; - } else { - return this.argumentASTs.nonSeparatorCount(); + TypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + throw TypeScript.Errors.abstract(); + }; + + TypeArgumentInferenceContext.prototype.fixTypeParameter = function (typeParameter) { + var candidateInfo = this.candidateCache[typeParameter.pullSymbolID]; + if (candidateInfo) { + candidateInfo.fixTypeParameter(this.resolver, this.context); } }; - ArgumentInferenceContext.prototype.getArgumentTypeSymbolAtIndex = function (i, context) { - TypeScript.Debug.assert(i >= 0, "invalid inference argument position"); - - if (this.fixedParameterTypes && i < this.getInferenceArgumentCount()) { - return this.fixedParameterTypes[i]; - } else if (i < this.getInferenceArgumentCount()) { - return this.resolver.resolveAST(this.argumentASTs.nonSeparatorAt(i), true, context).type; - } - - return null; - }; - - ArgumentInferenceContext.prototype.getInferenceCandidates = function () { - var inferenceCandidates = []; - - for (var infoKey in this.candidateCache) { - if (this.candidateCache.hasOwnProperty(infoKey)) { - var info = this.candidateCache[infoKey]; - - for (var i = 0; i < info.inferenceCandidates.length; i++) { - var val = []; - val[info.typeParameter.pullSymbolID] = info.inferenceCandidates[i]; - inferenceCandidates.push(val); - } - } - } - - return inferenceCandidates; - }; - - ArgumentInferenceContext.prototype.inferArgumentTypes = function (resolver, context) { - var collection; - - var bestCommonType; - + TypeArgumentInferenceContext.prototype._finalizeInferredTypeArguments = function () { var results = []; + var typeParameters = this.signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + var info = this.candidateCache[typeParameters[i].pullSymbolID]; - var unfit = false; + info.fixTypeParameter(this.resolver, this.context); - for (var infoKey in this.candidateCache) { - if (this.candidateCache.hasOwnProperty(infoKey)) { - var info = this.candidateCache[infoKey]; - - if (!info.inferenceCandidates.length) { - results[results.length] = { param: info.typeParameter, type: null }; - continue; + for (var i = 0; i < results.length; i++) { + if (results[i].type === info.typeParameter) { + results[i].type = info._inferredTypeAfterFixing; } - - collection = { - getLength: function () { - return info.inferenceCandidates.length; - }, - getTypeAtIndex: function (index) { - return info.inferenceCandidates[index].type; - } - }; - - bestCommonType = resolver.widenType(resolver.findBestCommonType(collection, context, new TypeScript.TypeComparisonInfo())); - - if (!bestCommonType) { - unfit = true; - } else { - for (var i = 0; i < results.length; i++) { - if (results[i].type == info.typeParameter) { - results[i].type = bestCommonType; - } - } - } - - results[results.length] = { param: info.typeParameter, type: bestCommonType }; } + + results.push(info._inferredTypeAfterFixing); } - return { results: results, unfit: unfit }; + return results; }; - return ArgumentInferenceContext; + + TypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + throw TypeScript.Errors.abstract(); + }; + return TypeArgumentInferenceContext; })(); - TypeScript.ArgumentInferenceContext = ArgumentInferenceContext; + TypeScript.TypeArgumentInferenceContext = TypeArgumentInferenceContext; + + var InvocationTypeArgumentInferenceContext = (function (_super) { + __extends(InvocationTypeArgumentInferenceContext, _super); + function InvocationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, argumentASTs) { + _super.call(this, resolver, context, signatureBeingInferred); + this.argumentASTs = argumentASTs; + } + InvocationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return true; + }; + + InvocationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + this.signatureBeingInferred.forAllParameterTypes(this.argumentASTs.nonSeparatorCount(), function (parameterType, argumentIndex) { + var argumentAST = _this.argumentASTs.nonSeparatorAt(argumentIndex); + + _this.context.pushInferentialType(parameterType, _this); + var argumentType = _this.resolver.resolveAST(argumentAST, true, _this.context).type; + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(argumentType, parameterType, _this, _this.context); + _this.context.popAnyContextualType(); + + return true; + }); + + return this._finalizeInferredTypeArguments(); + }; + return InvocationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.InvocationTypeArgumentInferenceContext = InvocationTypeArgumentInferenceContext; + + var ContextualSignatureInstantiationTypeArgumentInferenceContext = (function (_super) { + __extends(ContextualSignatureInstantiationTypeArgumentInferenceContext, _super); + function ContextualSignatureInstantiationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, contextualSignature, shouldFixContextualSignatureParameterTypes) { + _super.call(this, resolver, context, signatureBeingInferred); + this.contextualSignature = contextualSignature; + this.shouldFixContextualSignatureParameterTypes = shouldFixContextualSignatureParameterTypes; + } + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return false; + }; + + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + var relateTypesCallback = function (parameterTypeBeingInferred, contextualParameterType) { + if (_this.shouldFixContextualSignatureParameterTypes) { + contextualParameterType = _this.context.fixAllTypeParametersReferencedByType(contextualParameterType, _this.resolver, _this); + } + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(contextualParameterType, parameterTypeBeingInferred, _this, _this.context); + + return true; + }; + + this.signatureBeingInferred.forAllCorrespondingParameterTypesInThisAndOtherSignature(this.contextualSignature, relateTypesCallback); + + return this._finalizeInferredTypeArguments(); + }; + return ContextualSignatureInstantiationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext = ContextualSignatureInstantiationTypeArgumentInferenceContext; var PullContextualTypeContext = (function () { - function PullContextualTypeContext(contextualType, provisional, substitutions) { + function PullContextualTypeContext(contextualType, provisional, isInferentiallyTyping, typeArgumentInferenceContext) { this.contextualType = contextualType; this.provisional = provisional; - this.substitutions = substitutions; + this.isInferentiallyTyping = isInferentiallyTyping; + this.typeArgumentInferenceContext = typeArgumentInferenceContext; this.provisionallyTypedSymbols = []; this.hasProvisionalErrors = false; this.astSymbolMap = []; @@ -38548,6 +39137,8 @@ var TypeScript; this.fileName = fileName; this.contextStack = []; this.typeCheckedNodes = null; + this.enclosingTypeWalker1 = null; + this.enclosingTypeWalker2 = null; this.inBaseTypeResolution = false; if (inTypeCheck) { TypeScript.Debug.assert(fileName, "A file name must be provided if you are typechecking"); @@ -38564,11 +39155,27 @@ var TypeScript; return this.typeCheck() && !this.typeCheckedNodes.valueAt(ast.syntaxID()) && this.fileName === ast.fileName(); }; - PullTypeResolutionContext.prototype.pushContextualType = function (type, provisional, substitutions) { - this.contextStack.push(new PullContextualTypeContext(type, provisional, substitutions)); + PullTypeResolutionContext.prototype._pushAnyContextualType = function (type, provisional, isInferentiallyTyping, argContext) { + this.contextStack.push(new PullContextualTypeContext(type, provisional, isInferentiallyTyping, argContext)); }; - PullTypeResolutionContext.prototype.popContextualType = function () { + PullTypeResolutionContext.prototype.pushNewContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), false, null); + }; + + PullTypeResolutionContext.prototype.propagateContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), this.isInferentiallyTyping(), this.getCurrentTypeArgumentInferenceContext()); + }; + + PullTypeResolutionContext.prototype.pushInferentialType = function (type, typeArgumentInferenceContext) { + this._pushAnyContextualType(type, true, true, typeArgumentInferenceContext); + }; + + PullTypeResolutionContext.prototype.pushProvisionalType = function (type) { + this._pushAnyContextualType(type, true, false, null); + }; + + PullTypeResolutionContext.prototype.popAnyContextualType = function () { var tc = this.contextStack.pop(); tc.invalidateProvisionallyTypedSymbols(); @@ -38584,24 +39191,6 @@ var TypeScript; return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].hasProvisionalErrors : false; }; - PullTypeResolutionContext.prototype.findSubstitution = function (type) { - var substitution = null; - - if (this.contextStack.length) { - for (var i = this.contextStack.length - 1; i >= 0; i--) { - if (this.contextStack[i].substitutions) { - substitution = this.contextStack[i].substitutions[type.pullSymbolID]; - - if (substitution) { - break; - } - } - } - } - - return substitution; - }; - PullTypeResolutionContext.prototype.getContextualType = function () { var context = !this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]; @@ -38612,18 +39201,44 @@ var TypeScript; return null; } - if (type.isTypeParameter() && type.getConstraint()) { - type = type.getConstraint(); - } - - var substitution = this.findSubstitution(type); - - return substitution ? substitution : type; + return type; } return null; }; + PullTypeResolutionContext.prototype.fixAllTypeParametersReferencedByType = function (type, resolver, argContext) { + var argContext = this.getCurrentTypeArgumentInferenceContext(); + if (type.wrapsSomeTypeParameter(argContext.candidateCache)) { + var typeParameterArgumentMap = []; + + for (var n in argContext.candidateCache) { + var typeParameter = argContext.candidateCache[n] && argContext.candidateCache[n].typeParameter; + if (typeParameter) { + var dummyMap = []; + dummyMap[typeParameter.pullSymbolID] = typeParameter; + if (type.wrapsSomeTypeParameter(dummyMap)) { + argContext.fixTypeParameter(typeParameter); + TypeScript.Debug.assert(argContext.candidateCache[n]._inferredTypeAfterFixing); + typeParameterArgumentMap[typeParameter.pullSymbolID] = argContext.candidateCache[n]._inferredTypeAfterFixing; + } + } + } + + return resolver.instantiateType(type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolutionContext.prototype.getCurrentTypeArgumentInferenceContext = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].typeArgumentInferenceContext : null; + }; + + PullTypeResolutionContext.prototype.isInferentiallyTyping = function () { + return this.contextStack.length > 0 && this.contextStack[this.contextStack.length - 1].isInferentiallyTyping; + }; + PullTypeResolutionContext.prototype.inProvisionalResolution = function () { return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); }; @@ -38643,9 +39258,10 @@ var TypeScript; }; PullTypeResolutionContext.prototype.setTypeInContext = function (symbol, type) { - var substitution = this.findSubstitution(type); - - symbol.type = substitution ? substitution : type; + if (symbol.type && symbol.type.isError() && !type.isError()) { + return; + } + symbol.type = type; if (this.contextStack.length && this.inProvisionalResolution()) { this.contextStack[this.contextStack.length - 1].recordProvisionallyTypedSymbol(symbol); @@ -38685,6 +39301,145 @@ var TypeScript; return null; }; + + PullTypeResolutionContext.prototype.startWalkingTypes = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var symbolsWhenStartedWalkingTypes1 = this.enclosingTypeWalker1.startWalkingType(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var symbolsWhenStartedWalkingTypes2 = this.enclosingTypeWalker2.startWalkingType(symbol2); + return { symbolsWhenStartedWalkingTypes1: symbolsWhenStartedWalkingTypes1, symbolsWhenStartedWalkingTypes2: symbolsWhenStartedWalkingTypes2 }; + }; + + PullTypeResolutionContext.prototype.endWalkingTypes = function (symbolsWhenStartedWalkingTypes) { + this.enclosingTypeWalker1.endWalkingType(symbolsWhenStartedWalkingTypes.symbolsWhenStartedWalkingTypes1); + this.enclosingTypeWalker2.endWalkingType(symbolsWhenStartedWalkingTypes.symbolsWhenStartedWalkingTypes2); + }; + + PullTypeResolutionContext.prototype.setEnclosingTypes = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + this.enclosingTypeWalker1.setEnclosingType(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + this.enclosingTypeWalker2.setEnclosingType(symbol2); + }; + + PullTypeResolutionContext.prototype.walkMemberTypes = function (memberName) { + this.enclosingTypeWalker1.walkMemberType(memberName, this.resolver); + this.enclosingTypeWalker2.walkMemberType(memberName, this.resolver); + }; + + PullTypeResolutionContext.prototype.postWalkMemberTypes = function () { + this.enclosingTypeWalker1.postWalkMemberType(); + this.enclosingTypeWalker2.postWalkMemberType(); + }; + + PullTypeResolutionContext.prototype.walkSignatures = function (kind, index, index2) { + this.enclosingTypeWalker1.walkSignature(kind, index); + this.enclosingTypeWalker2.walkSignature(kind, index2 == undefined ? index : index2); + }; + + PullTypeResolutionContext.prototype.postWalkSignatures = function () { + this.enclosingTypeWalker1.postWalkSignature(); + this.enclosingTypeWalker2.postWalkSignature(); + }; + + PullTypeResolutionContext.prototype.walkTypeParameterConstraints = function (index) { + this.enclosingTypeWalker1.walkTypeParameterConstraint(index); + this.enclosingTypeWalker2.walkTypeParameterConstraint(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeParameterConstraints = function () { + this.enclosingTypeWalker1.postWalkTypeParameterConstraint(); + this.enclosingTypeWalker2.postWalkTypeParameterConstraint(); + }; + + PullTypeResolutionContext.prototype.walkTypeArgument = function (index) { + this.enclosingTypeWalker1.walkTypeArgument(index); + this.enclosingTypeWalker2.walkTypeArgument(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeArgument = function () { + this.enclosingTypeWalker1.postWalkTypeArgument(); + this.enclosingTypeWalker2.postWalkTypeArgument(); + }; + + PullTypeResolutionContext.prototype.walkReturnTypes = function () { + this.enclosingTypeWalker1.walkReturnType(); + this.enclosingTypeWalker2.walkReturnType(); + }; + + PullTypeResolutionContext.prototype.postWalkReturnTypes = function () { + this.enclosingTypeWalker1.postWalkReturnType(); + this.enclosingTypeWalker2.postWalkReturnType(); + }; + + PullTypeResolutionContext.prototype.walkParameterTypes = function (iParam) { + this.enclosingTypeWalker1.walkParameterType(iParam); + this.enclosingTypeWalker2.walkParameterType(iParam); + }; + + PullTypeResolutionContext.prototype.postWalkParameterTypes = function () { + this.enclosingTypeWalker1.postWalkParameterType(); + this.enclosingTypeWalker2.postWalkParameterType(); + }; + + PullTypeResolutionContext.prototype.getBothKindOfIndexSignatures = function (includeAugmentedType1, includeAugmentedType2) { + var indexSigs1 = this.enclosingTypeWalker1.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType1); + var indexSigs2 = this.enclosingTypeWalker2.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType2); + return { indexSigs1: indexSigs1, indexSigs2: indexSigs2 }; + }; + + PullTypeResolutionContext.prototype.walkIndexSignatureReturnTypes = function (indexSigs, useStringIndexSignature1, useStringIndexSignature2, onlySignature) { + this.enclosingTypeWalker1.walkIndexSignatureReturnType(indexSigs.indexSigs1, useStringIndexSignature1, onlySignature); + this.enclosingTypeWalker2.walkIndexSignatureReturnType(indexSigs.indexSigs2, useStringIndexSignature2, onlySignature); + }; + + PullTypeResolutionContext.prototype.postWalkIndexSignatureReturnTypes = function (onlySignature) { + this.enclosingTypeWalker1.postWalkIndexSignatureReturnType(onlySignature); + this.enclosingTypeWalker2.postWalkIndexSignatureReturnType(onlySignature); + }; + + PullTypeResolutionContext.prototype.swapEnclosingTypeWalkers = function () { + var tempEnclosingWalker1 = this.enclosingTypeWalker1; + this.enclosingTypeWalker1 = this.enclosingTypeWalker2; + this.enclosingTypeWalker2 = tempEnclosingWalker1; + }; + + PullTypeResolutionContext.prototype.oneOfClassificationsIsInfinitelyExpanding = function () { + var generativeClassification1 = this.enclosingTypeWalker1.getGenerativeClassification(); + if (generativeClassification1 === 3 /* InfinitelyExpanding */) { + return true; + } + var generativeClassification2 = this.enclosingTypeWalker2.getGenerativeClassification(); + if (generativeClassification2 === 3 /* InfinitelyExpanding */) { + return true; + } + + return false; + }; + + PullTypeResolutionContext.prototype.resetEnclosingTypeWalkers = function () { + var enclosingTypeWalker1 = this.enclosingTypeWalker1; + var enclosingTypeWalker2 = this.enclosingTypeWalker2; + this.enclosingTypeWalker1 = null; + this.enclosingTypeWalker2 = null; + return { + enclosingTypeWalker1: enclosingTypeWalker1, + enclosingTypeWalker2: enclosingTypeWalker2 + }; + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeWalkers = function (enclosingTypeWalkers) { + this.enclosingTypeWalker1 = enclosingTypeWalkers.enclosingTypeWalker1; + this.enclosingTypeWalker2 = enclosingTypeWalkers.enclosingTypeWalker2; + }; return PullTypeResolutionContext; })(); TypeScript.PullTypeResolutionContext = PullTypeResolutionContext; @@ -38741,20 +39496,19 @@ var TypeScript; return InheritedIndexSignatureInfo; })(); - var CompilerReservedNames; - (function (CompilerReservedNames) { - CompilerReservedNames[CompilerReservedNames["_this"] = 1] = "_this"; - CompilerReservedNames[CompilerReservedNames["_super"] = 2] = "_super"; - CompilerReservedNames[CompilerReservedNames["arguments"] = 3] = "arguments"; - CompilerReservedNames[CompilerReservedNames["_i"] = 4] = "_i"; - CompilerReservedNames[CompilerReservedNames["require"] = 5] = "require"; - CompilerReservedNames[CompilerReservedNames["exports"] = 6] = "exports"; - })(CompilerReservedNames || (CompilerReservedNames = {})); + var CompilerReservedName; + (function (CompilerReservedName) { + CompilerReservedName[CompilerReservedName["_this"] = 1] = "_this"; + CompilerReservedName[CompilerReservedName["_super"] = 2] = "_super"; + CompilerReservedName[CompilerReservedName["arguments"] = 3] = "arguments"; + CompilerReservedName[CompilerReservedName["_i"] = 4] = "_i"; + CompilerReservedName[CompilerReservedName["require"] = 5] = "require"; + CompilerReservedName[CompilerReservedName["exports"] = 6] = "exports"; + })(CompilerReservedName || (CompilerReservedName = {})); function getCompilerReservedName(name) { var nameText = name.valueText(); - var index = CompilerReservedNames[nameText]; - return CompilerReservedNames[index] ? index : undefined; + return CompilerReservedName[nameText]; } var PullTypeResolver = (function () { @@ -38776,14 +39530,11 @@ var TypeScript; this.assignableCache = TypeScript.BitMatrix.getBitMatrix(true); this.subtypeCache = TypeScript.BitMatrix.getBitMatrix(true); this.identicalCache = TypeScript.BitMatrix.getBitMatrix(true); + this.inResolvingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); } PullTypeResolver.prototype.cachedArrayInterfaceType = function () { if (!this._cachedArrayInterfaceType) { - this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */); - } - - if (!this._cachedArrayInterfaceType) { - this._cachedArrayInterfaceType = this.semanticInfoChain.anyTypeSymbol; + this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (!this._cachedArrayInterfaceType.isResolved) { @@ -38799,7 +39550,7 @@ var TypeScript; PullTypeResolver.prototype.cachedNumberInterfaceType = function () { if (!this._cachedNumberInterfaceType) { - this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */); + this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedNumberInterfaceType && !this._cachedNumberInterfaceType.isResolved) { @@ -38811,7 +39562,7 @@ var TypeScript; PullTypeResolver.prototype.cachedStringInterfaceType = function () { if (!this._cachedStringInterfaceType) { - this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */); + this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedStringInterfaceType && !this._cachedStringInterfaceType.isResolved) { @@ -38823,7 +39574,7 @@ var TypeScript; PullTypeResolver.prototype.cachedBooleanInterfaceType = function () { if (!this._cachedBooleanInterfaceType) { - this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */); + this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedBooleanInterfaceType && !this._cachedBooleanInterfaceType.isResolved) { @@ -38835,7 +39586,7 @@ var TypeScript; PullTypeResolver.prototype.cachedObjectInterfaceType = function () { if (!this._cachedObjectInterfaceType) { - this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */); + this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (!this._cachedObjectInterfaceType) { @@ -38851,7 +39602,7 @@ var TypeScript; PullTypeResolver.prototype.cachedFunctionInterfaceType = function () { if (!this._cachedFunctionInterfaceType) { - this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */); + this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedFunctionInterfaceType && !this._cachedFunctionInterfaceType.isResolved) { @@ -38863,7 +39614,7 @@ var TypeScript; PullTypeResolver.prototype.cachedIArgumentsInterfaceType = function () { if (!this._cachedIArgumentsInterfaceType) { - this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */); + this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedIArgumentsInterfaceType && !this._cachedIArgumentsInterfaceType.isResolved) { @@ -38875,7 +39626,7 @@ var TypeScript; PullTypeResolver.prototype.cachedRegExpInterfaceType = function () { if (!this._cachedRegExpInterfaceType) { - this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */); + this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; } if (this._cachedRegExpInterfaceType && !this._cachedRegExpInterfaceType.isResolved) { @@ -38888,10 +39639,10 @@ var TypeScript; PullTypeResolver.prototype.cachedFunctionArgumentsSymbol = function () { if (!this._cachedFunctionArgumentsSymbol) { this._cachedFunctionArgumentsSymbol = new TypeScript.PullSymbol("arguments", 512 /* Variable */); - this._cachedFunctionArgumentsSymbol.type = this.cachedIArgumentsInterfaceType() ? this.cachedIArgumentsInterfaceType() : this.semanticInfoChain.anyTypeSymbol; + this._cachedFunctionArgumentsSymbol.type = this.cachedIArgumentsInterfaceType() || this.semanticInfoChain.anyTypeSymbol; this._cachedFunctionArgumentsSymbol.setResolved(); - var functionArgumentsDecl = new TypeScript.PullSynthesizedDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, null, new TypeScript.TextSpan(0, 0), this.semanticInfoChain); + var functionArgumentsDecl = new TypeScript.PullSynthesizedDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, null, this.semanticInfoChain); functionArgumentsDecl.setSymbol(this._cachedFunctionArgumentsSymbol); this._cachedFunctionArgumentsSymbol.addDeclaration(functionArgumentsDecl); } @@ -38899,6 +39650,33 @@ var TypeScript; return this._cachedFunctionArgumentsSymbol; }; + PullTypeResolver.prototype.getApparentType = function (type) { + if (type.isTypeParameter()) { + var baseConstraint = type.getBaseConstraint(this.semanticInfoChain); + if (baseConstraint === this.semanticInfoChain.anyTypeSymbol) { + return this.semanticInfoChain.emptyTypeSymbol; + } else { + type = baseConstraint; + } + } + if (type.isPrimitive()) { + if (type === this.semanticInfoChain.numberTypeSymbol) { + return this.cachedNumberInterfaceType(); + } + if (type === this.semanticInfoChain.booleanTypeSymbol) { + return this.cachedBooleanInterfaceType(); + } + if (type === this.semanticInfoChain.stringTypeSymbol) { + return this.cachedStringInterfaceType(); + } + return type; + } + if (type.isEnum()) { + return this.cachedNumberInterfaceType(); + } + return type; + }; + PullTypeResolver.prototype.setTypeChecked = function (ast, context) { context.setTypeChecked(ast); }; @@ -38948,7 +39726,7 @@ var TypeScript; PullTypeResolver.prototype.getExportedMemberSymbol = function (symbol, parent) { if (!(symbol.kind & (65536 /* Method */ | 4096 /* Property */))) { - var isContainer = (parent.kind & (4 /* Container */ | 32 /* DynamicModule */)) != 0; + var isContainer = (parent.kind & (4 /* Container */ | 32 /* DynamicModule */)) !== 0; var containerType = !isContainer ? parent.getAssociatedContainerType() : parent; if (isContainer && containerType) { @@ -38963,12 +39741,32 @@ var TypeScript; return symbol; }; - PullTypeResolver.prototype.getMemberSymbol = function (symbolName, declSearchKind, parent) { + PullTypeResolver.prototype._getNamedPropertySymbolOfAugmentedType = function (symbolName, parent) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, 68147712 /* SomeValue */, parent); + if (memberSymbol) { + return memberSymbol; + } + + if (this.cachedFunctionInterfaceType() && parent.isFunctionType()) { + memberSymbol = this.cachedFunctionInterfaceType().findMember(symbolName, true); + if (memberSymbol) { + return memberSymbol; + } + } + + if (this.cachedObjectInterfaceType()) { + return this.cachedObjectInterfaceType().findMember(symbolName, true); + } + + return null; + }; + + PullTypeResolver.prototype.getNamedPropertySymbol = function (symbolName, declSearchKind, parent) { var member = null; if (declSearchKind & 68147712 /* SomeValue */) { member = parent.findMember(symbolName, true); - } else if (declSearchKind & 58728539 /* SomeType */) { + } else if (declSearchKind & 58728795 /* SomeType */) { member = parent.findNestedType(symbolName); } else if (declSearchKind & 164 /* SomeContainer */) { member = parent.findNestedContainer(symbolName); @@ -38989,7 +39787,7 @@ var TypeScript; if (declSearchKind & 68147712 /* SomeValue */) { member = parent.findMember(symbolName, true); - } else if (declSearchKind & 58728539 /* SomeType */) { + } else if (declSearchKind & 58728795 /* SomeType */) { member = parent.findNestedType(symbolName); } else if (declSearchKind & 164 /* SomeContainer */) { member = parent.findNestedContainer(symbolName); @@ -39016,12 +39814,12 @@ var TypeScript; return this.getExportedMemberSymbol(member, parent); } - if ((declSearchKind & 58728539 /* SomeType */) != 0 || (declSearchKind & 68147712 /* SomeValue */) != 0) { + if ((declSearchKind & 58728795 /* SomeType */) !== 0 || (declSearchKind & 68147712 /* SomeValue */) !== 0) { childDecls = typeDeclarations[j].searchChildDecls(symbolName, 128 /* TypeAlias */); - if (childDecls.length && childDecls[0].kind == 128 /* TypeAlias */) { + if (childDecls.length && childDecls[0].kind === 128 /* TypeAlias */) { var aliasSymbol = this.getExportedMemberSymbol(childDecls[0].getSymbol(), parent); if (aliasSymbol) { - if ((declSearchKind & 58728539 /* SomeType */) != 0) { + if ((declSearchKind & 58728795 /* SomeType */) !== 0) { var typeSymbol = aliasSymbol.getExportAssignedTypeSymbol(); if (typeSymbol) { return typeSymbol; @@ -39029,9 +39827,12 @@ var TypeScript; } else { var valueSymbol = aliasSymbol.getExportAssignedValueSymbol(); if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); return valueSymbol; } } + + return aliasSymbol; } } } @@ -39040,6 +39841,7 @@ var TypeScript; }; PullTypeResolver.prototype.getSymbolFromDeclPath = function (symbolName, declPath, declSearchKind) { + var _this = this; var symbol = null; var decl = null; @@ -39053,6 +39855,61 @@ var TypeScript; var instanceType = null; var childSymbol = null; + var allowedContainerDeclKind = 4 /* Container */ | 32 /* DynamicModule */; + if (TypeScript.hasFlag(declSearchKind, 67108864 /* EnumMember */)) { + allowedContainerDeclKind |= 64 /* Enum */; + } + + var isAcceptableAlias = function (symbol) { + if (symbol.isAlias()) { + _this.resolveDeclaredSymbol(symbol); + if (TypeScript.hasFlag(declSearchKind, 164 /* SomeContainer */)) { + if (symbol.assignedContainer() || symbol.getExportAssignedContainerSymbol()) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 58728795 /* SomeType */)) { + var type = symbol.getExportAssignedTypeSymbol(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + + var type = symbol.assignedType(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 68147712 /* SomeValue */ & ~67108864 /* EnumMember */)) { + if (symbol.assignedType() && symbol.assignedType().isError()) { + return true; + } else if (symbol.assignedValue() || symbol.getExportAssignedValueSymbol()) { + return true; + } else { + var assignedType = symbol.assignedType(); + if (assignedType && assignedType.isContainer() && assignedType.getInstanceType()) { + return true; + } + + var decls = symbol.getDeclarations(); + var ast = decls[0].ast(); + return ast.moduleReference.kind() === 245 /* ExternalModuleReference */; + } + } + } + + return false; + }; + + var tryFindAlias = function (decl) { + var childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + if (isAcceptableAlias(sym)) { + return sym; + } + } + return null; + }; + for (var i = declPath.length - 1; i >= 0; i--) { decl = declPath[i]; pathDeclKind = decl.kind; @@ -39061,30 +39918,25 @@ var TypeScript; return this.semanticInfoChain.anyTypeSymbol; } - if (pathDeclKind & (4 /* Container */ | 32 /* DynamicModule */)) { + if (pathDeclKind & allowedContainerDeclKind) { childDecls = decl.searchChildDecls(symbolName, declSearchKind); if (childDecls.length) { return childDecls[0].getSymbol(); } + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + if (declSearchKind & 68147712 /* SomeValue */) { instanceSymbol = decl.getSymbol().getInstanceSymbol(); - childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); - - if (childDecls.length) { - var sym = childDecls[0].getSymbol(); - - if (sym.isAlias()) { - return sym; - } - } - if (instanceSymbol) { instanceType = instanceSymbol.type; - childSymbol = this.getMemberSymbol(symbolName, declSearchKind, instanceType); + childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, instanceType); if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { return childSymbol; @@ -39100,12 +39952,12 @@ var TypeScript; declSymbol = decl.getSymbol().type; - var childSymbol = this.getMemberSymbol(symbolName, declSearchKind, declSymbol); + var childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, declSymbol); if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { return childSymbol; } - } else if ((declSearchKind & (58728539 /* SomeType */ | 164 /* SomeContainer */)) || !(pathDeclKind & 8 /* Class */)) { + } else if ((declSearchKind & (58728795 /* SomeType */ | 164 /* SomeContainer */)) || !(pathDeclKind & 8 /* Class */)) { var candidateSymbol = null; if (pathDeclKind === 131072 /* FunctionExpression */ && symbolName === decl.getFunctionExpressionName()) { @@ -39125,23 +39977,26 @@ var TypeScript; return candidateSymbol; } - if (declSearchKind & 68147712 /* SomeValue */) { - childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); - - if (childDecls.length) { - var sym = childDecls[0].getSymbol(); - - if (sym.isAlias()) { - return sym; - } - } + var alias = tryFindAlias(decl); + if (alias) { + return alias; } } } symbol = this.semanticInfoChain.findSymbol([symbolName], declSearchKind); + if (symbol) { + return symbol; + } - return symbol; + if (!TypeScript.hasFlag(declSearchKind, 128 /* TypeAlias */)) { + symbol = this.semanticInfoChain.findSymbol([symbolName], 128 /* TypeAlias */); + if (symbol && isAcceptableAlias(symbol)) { + return symbol; + } + } + + return null; }; PullTypeResolver.prototype.getVisibleDeclsFromDeclPath = function (declPath, declSearchKind) { @@ -39237,7 +40092,7 @@ var TypeScript; PullTypeResolver.prototype.getVisibleDecls = function (enclosingDecl) { var declPath = enclosingDecl.getParentPath(); - var declSearchKind = 58728539 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; return this.getVisibleDeclsFromDeclPath(declPath, declSearchKind); }; @@ -39248,7 +40103,7 @@ var TypeScript; return null; } - var declSearchKind = 58728539 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; var members = contextualTypeSymbol.getAllMembers(declSearchKind, 2 /* externallyVisible */); for (var i = 0; i < members.length; i++) { @@ -39261,7 +40116,7 @@ var TypeScript; PullTypeResolver.prototype.getVisibleMembersFromExpression = function (expression, enclosingDecl, context) { var lhs = this.resolveAST(expression, false, context); - if (isTypesOnlyLocation(expression) && (lhs.kind === 8 /* Class */ || lhs.kind === 16 /* Interface */)) { + if (isTypesOnlyLocation(expression) && (lhs.kind === 8 /* Class */ || lhs.kind === 16 /* Interface */ || lhs.kind === 64 /* Enum */)) { return null; } @@ -39276,13 +40131,6 @@ var TypeScript; lhsType = lhsType.getExportAssignedTypeSymbol(); } - while (lhsType.isTypeParameter()) { - lhsType = lhsType.getConstraint(); - if (!lhsType) { - return null; - } - } - if (this.isAnyOrEquivalent(lhsType)) { return null; } @@ -39307,7 +40155,7 @@ var TypeScript; } } - var declSearchKind = 58728539 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; var members = []; @@ -39318,66 +40166,47 @@ var TypeScript; } } - if (lhsType.isTypeParameter()) { - var constraint = lhsType.getConstraint(); + lhsType = this.getApparentType(lhsType); - if (constraint) { - lhsType = constraint; - members = lhsType.getAllMembers(declSearchKind, 2 /* externallyVisible */); - } - } else { - if (lhs.kind == 67108864 /* EnumMember */) { - lhsType = this.semanticInfoChain.numberTypeSymbol; - } + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); - if (lhsType === this.semanticInfoChain.numberTypeSymbol && this.cachedNumberInterfaceType()) { - lhsType = this.cachedNumberInterfaceType(); - } else if (lhsType === this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { - lhsType = this.cachedStringInterfaceType(); - } else if (lhsType === this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { - lhsType = this.cachedBooleanInterfaceType(); - } - - if (!lhsType.isResolved) { - var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); - - if (potentiallySpecializedType != lhsType) { - if (!lhs.isType()) { - context.setTypeInContext(lhs, potentiallySpecializedType); - } - - lhsType = potentiallySpecializedType; - } - } - - members = lhsType.getAllMembers(declSearchKind, memberVisibilty); - - if (lhsType.isContainer()) { - var associatedInstance = lhsType.getInstanceSymbol(); - if (associatedInstance) { - var instanceType = associatedInstance.type; - this.resolveDeclaredSymbol(instanceType, context); - var instanceMembers = instanceType.getAllMembers(declSearchKind, memberVisibilty); - members = members.concat(instanceMembers); + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); } - var exportedContainer = lhsType.getExportAssignedContainerSymbol(); - if (exportedContainer) { - var exportedContainerMembers = exportedContainer.getAllMembers(declSearchKind, memberVisibilty); - members = members.concat(exportedContainerMembers); - } - } else if (!lhsType.isConstructor()) { - var associatedContainerSymbol = lhsType.getAssociatedContainerType(); - if (associatedContainerSymbol) { - var containerType = associatedContainerSymbol.type; - this.resolveDeclaredSymbol(containerType, context); - var containerMembers = containerType.getAllMembers(declSearchKind, memberVisibilty); - members = members.concat(containerMembers); - } + lhsType = potentiallySpecializedType; } } - if ((lhsType.getCallSignatures().length || lhsType.getConstructSignatures().length) && this.cachedFunctionInterfaceType()) { + members = lhsType.getAllMembers(declSearchKind, memberVisibilty); + + if (lhsType.isContainer()) { + var associatedInstance = lhsType.getInstanceSymbol(); + if (associatedInstance) { + var instanceType = associatedInstance.type; + this.resolveDeclaredSymbol(instanceType, context); + var instanceMembers = instanceType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(instanceMembers); + } + + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + if (exportedContainer) { + var exportedContainerMembers = exportedContainer.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(exportedContainerMembers); + } + } else if (!lhsType.isConstructor() && !lhsType.isEnum()) { + var associatedContainerSymbol = lhsType.getAssociatedContainerType(); + if (associatedContainerSymbol) { + var containerType = associatedContainerSymbol.type; + this.resolveDeclaredSymbol(containerType, context); + var containerMembers = containerType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(containerMembers); + } + } + + if (lhsType.isFunctionType() && this.cachedFunctionInterfaceType()) { members = members.concat(this.cachedFunctionInterfaceType().getAllMembers(declSearchKind, 2 /* externallyVisible */)); } @@ -39456,22 +40285,26 @@ var TypeScript; return symbol; } - if (ast.kind() === 11 /* IdentifierName */ && ast.parent && ast.parent.kind() === 236 /* CatchClause */) { + if (ast.parent && ast.parent.kind() === 236 /* CatchClause */ && ast.parent.identifier === ast) { return symbol; } - var enclosingModule = TypeScript.getEnclosingModuleDeclaration(ast); + if (ast.parent && ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ && ast.parent.identifier === ast) { + return symbol; + } + + var enclosingModule = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(ast); var resolvedSymbol; - if (TypeScript.isAnyNameOfModule(enclosingModule, ast)) { + if (TypeScript.ASTHelpers.isAnyNameOfModule(enclosingModule, ast)) { resolvedSymbol = this.resolveSingleModuleDeclaration(enclosingModule, ast, context); } else if (ast.kind() === 120 /* SourceUnit */ && decl.kind === 32 /* DynamicModule */) { resolvedSymbol = this.resolveModuleSymbol(decl.getSymbol(), context, null, null, ast); } else { - TypeScript.Debug.assert(ast.kind() != 11 /* IdentifierName */ && ast.kind() != 212 /* MemberAccessExpression */); - var resolvedSymbol = this.resolveAST(ast, false, context); + TypeScript.Debug.assert(ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */); + resolvedSymbol = this.resolveAST(ast, false, context); } - if (decl.kind == 2048 /* Parameter */ && !symbol.isResolved && !symbol.type && resolvedSymbol && symbol.anyDeclHasFlag(8388608 /* PropertyParameter */ | 67108864 /* ConstructorParameter */)) { + if (decl.kind === 2048 /* Parameter */ && !symbol.isResolved && !symbol.type && resolvedSymbol && symbol.anyDeclHasFlag(8388608 /* PropertyParameter */ | 67108864 /* ConstructorParameter */)) { symbol.type = resolvedSymbol.type; symbol.setResolved(); } @@ -39480,23 +40313,25 @@ var TypeScript; return symbol; }; + PullTypeResolver.prototype.resolveOtherDecl = function (otherDecl, context) { + var astForOtherDecl = this.getASTForDecl(otherDecl); + var moduleDecl = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(astForOtherDecl); + if (TypeScript.ASTHelpers.isAnyNameOfModule(moduleDecl, astForOtherDecl)) { + this.resolveSingleModuleDeclaration(moduleDecl, astForOtherDecl, context); + } else { + this.resolveAST(astForOtherDecl, false, context); + } + }; + PullTypeResolver.prototype.resolveOtherDeclarations = function (astName, context) { + var _this = this; var resolvedDecl = this.semanticInfoChain.getDeclForAST(astName); var symbol = resolvedDecl.getSymbol(); var allDecls = symbol.getDeclarations(); - for (var i = 0; i < allDecls.length; i++) { - var currentDecl = allDecls[i]; - var astForCurrentDecl = this.getASTForDecl(currentDecl); - if (astForCurrentDecl != astName) { - var moduleDecl = TypeScript.getEnclosingModuleDeclaration(astForCurrentDecl); - if (TypeScript.isAnyNameOfModule(moduleDecl, astForCurrentDecl)) { - this.resolveSingleModuleDeclaration(moduleDecl, astForCurrentDecl, context); - } else { - this.resolveAST(astForCurrentDecl, false, context); - } - } - } + this.inResolvingOtherDeclsWalker.walkOtherPullDecls(resolvedDecl, symbol.getDeclarations(), function (otherDecl) { + return _this.resolveOtherDecl(otherDecl, context); + }); }; PullTypeResolver.prototype.resolveSourceUnit = function (sourceUnit, context) { @@ -39515,9 +40350,26 @@ var TypeScript; }; PullTypeResolver.prototype.typeCheckSourceUnit = function (sourceUnit, context) { + var _this = this; this.setTypeChecked(sourceUnit, context); this.resolveAST(sourceUnit.moduleElements, false, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInSourceUnit(sourceUnit); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInSourceUnit = function (sourceUnit) { + var _this = this; + var enclosingDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + + var doesImportNameExistInOtherFiles = function (name) { + var importSymbol = _this.semanticInfoChain.findTopLevelSymbol(name, 128 /* TypeAlias */, null); + return importSymbol && importSymbol.isAlias(); + }; + + this.checkUniquenessOfImportNames([enclosingDecl], doesImportNameExistInOtherFiles); }; PullTypeResolver.prototype.resolveEnumDeclaration = function (ast, context) { @@ -39552,13 +40404,18 @@ var TypeScript; }; PullTypeResolver.prototype.typeCheckEnumDeclaration = function (ast, context) { + var _this = this; this.setTypeChecked(ast, context); this.resolveAST(ast.enumElements, false, context); var containerDecl = this.semanticInfoChain.getDeclForAST(ast); this.validateVariableDeclarationGroups(containerDecl, context); - if (!TypeScript.enumIsElided(ast)) { + this.typeCheckCallBacks.push(function (context) { + return _this.checkInitializersInEnumDeclarations(containerDecl, context); + }); + + if (!TypeScript.ASTHelpers.enumIsElided(ast)) { this.checkNameForCompilerGeneratedDeclarationCollision(ast, true, ast.identifier, context); } }; @@ -39567,6 +40424,34 @@ var TypeScript; this.checkThisCaptureVariableCollides(ast, true, context); }; + PullTypeResolver.prototype.checkInitializersInEnumDeclarations = function (decl, context) { + var symbol = decl.getSymbol(); + + var declarations = symbol.getDeclarations(); + if (decl !== declarations[0]) { + return; + } + + var seenEnumDeclWithNoFirstMember = false; + for (var i = 0; i < declarations.length; ++i) { + var currentDecl = declarations[i]; + + var ast = currentDecl.ast(); + if (ast.enumElements.nonSeparatorCount() === 0) { + continue; + } + + var firstVariable = ast.enumElements.nonSeparatorAt(0); + if (!firstVariable.equalsValueClause) { + if (!seenEnumDeclWithNoFirstMember) { + seenEnumDeclWithNoFirstMember = true; + } else { + this.semanticInfoChain.addDiagnosticFromAST(firstVariable, TypeScript.DiagnosticCode.In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element); + } + } + } + }; + PullTypeResolver.prototype.resolveModuleDeclaration = function (ast, context) { var result; @@ -39614,7 +40499,7 @@ var TypeScript; this.resolveDeclaredSymbol(instanceSymbol, context); } - var isLastName = TypeScript.isLastNameOfModule(moduleDeclAST, moduleDeclNameAST); + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDeclAST, moduleDeclNameAST); if (isLastName) { this.resolveFirstExportAssignmentStatement(moduleDeclAST.moduleElements, context); } else if (sourceUnitAST) { @@ -39633,7 +40518,7 @@ var TypeScript; PullTypeResolver.prototype.resolveFirstExportAssignmentStatement = function (moduleElements, context) { for (var i = 0, n = moduleElements.childCount(); i < n; i++) { var moduleElement = moduleElements.childAt(i); - if (moduleElement.kind() == 134 /* ExportAssignment */) { + if (moduleElement.kind() === 134 /* ExportAssignment */) { this.resolveExportAssignmentStatement(moduleElement, context); return; } @@ -39659,9 +40544,10 @@ var TypeScript; }; PullTypeResolver.prototype.typeCheckSingleModuleDeclaration = function (ast, astName, context) { + var _this = this; this.setTypeChecked(ast, context); - if (TypeScript.isLastNameOfModule(ast, astName)) { + if (TypeScript.ASTHelpers.isLastNameOfModule(ast, astName)) { this.resolveAST(ast.moduleElements, false, context); } @@ -39674,9 +40560,106 @@ var TypeScript; } } - if (!TypeScript.moduleIsElided(ast) && !ast.stringLiteral) { + if (!TypeScript.ASTHelpers.moduleIsElided(ast) && !ast.stringLiteral) { this.checkNameForCompilerGeneratedDeclarationCollision(astName, true, astName, context); } + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInModule(containerDecl); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInModule = function (decl) { + var symbol = decl.getSymbol(); + if (!symbol) { + return; + } + + var decls = symbol.getDeclarations(); + + if (decls[0] !== decl) { + return; + } + + this.checkUniquenessOfImportNames(decls); + }; + + PullTypeResolver.prototype.checkUniquenessOfImportNames = function (decls, doesNameExistOutside) { + var _this = this; + var importDeclarationNames; + + for (var i = 0; i < decls.length; ++i) { + var childDecls = decls[i].getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[childDecl.name] = true; + } + } + } + + if (!importDeclarationNames && !doesNameExistOutside) { + return; + } + + for (var i = 0; i < decls.length; ++i) { + this.scanVariableDeclarationGroups(decls[i], function (firstDeclInGroup) { + var nameConflict = importDeclarationNames && importDeclarationNames[firstDeclInGroup.name]; + if (!nameConflict) { + nameConflict = doesNameExistOutside && doesNameExistOutside(firstDeclInGroup.name); + if (nameConflict) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[firstDeclInGroup.name] = true; + } + } + + if (nameConflict) { + _this.semanticInfoChain.addDiagnosticFromAST(firstDeclInGroup.ast(), TypeScript.DiagnosticCode.Variable_declaration_cannot_have_the_same_name_as_an_import_declaration); + } + }); + } + }; + + PullTypeResolver.prototype.scanVariableDeclarationGroups = function (enclosingDecl, firstDeclHandler, subsequentDeclHandler) { + var declGroups = enclosingDecl.getVariableDeclGroups(); + + for (var i = 0; i < declGroups.length; i++) { + var firstSymbol = null; + var enclosingDeclForFirstSymbol = null; + + if (enclosingDecl.kind === 1 /* Script */ && declGroups[i].length) { + var name = declGroups[i][0].name; + var candidateSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 512 /* Variable */, enclosingDecl); + if (candidateSymbol && candidateSymbol.isResolved) { + if (!candidateSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */)) { + firstSymbol = candidateSymbol; + } + } + } + + for (var j = 0; j < declGroups[i].length; j++) { + var decl = declGroups[i][j]; + + var name = decl.name; + + var symbol = decl.getSymbol(); + + if (j === 0) { + firstDeclHandler(decl); + if (!subsequentDeclHandler) { + break; + } + + if (!firstSymbol || !firstSymbol.type) { + firstSymbol = symbol; + continue; + } + } + + subsequentDeclHandler(decl, firstSymbol); + } + } }; PullTypeResolver.prototype.postTypeCheckModuleDeclaration = function (ast, context) { @@ -39684,12 +40667,12 @@ var TypeScript; }; PullTypeResolver.prototype.isTypeRefWithoutTypeArgs = function (term) { - if (term.kind() == 11 /* IdentifierName */) { + if (term.kind() === 11 /* IdentifierName */) { return true; - } else if (term.kind() == 121 /* QualifiedName */) { + } else if (term.kind() === 121 /* QualifiedName */) { var binex = term; - if (binex.right.kind() == 11 /* IdentifierName */) { + if (binex.right.kind() === 11 /* IdentifierName */) { return true; } } @@ -39719,7 +40702,7 @@ var TypeScript; var enclosingDecl = this.getEnclosingDecl(typeDecl); var typeDeclSymbol = typeDecl.getSymbol(); var typeDeclIsClass = classOrInterface.kind() === 131 /* ClassDeclaration */; - var hasVisited = this.getSymbolForAST(classOrInterface, context) != null; + var hasVisited = this.getSymbolForAST(classOrInterface, context) !== null; if ((typeDeclSymbol.isResolved && hasVisited) || (typeDeclSymbol.inResolution && !context.isInBaseTypeResolution())) { return typeDeclSymbol; @@ -39728,13 +40711,6 @@ var TypeScript; var wasResolving = typeDeclSymbol.inResolution; typeDeclSymbol.startResolving(); - if (!typeDeclSymbol.isResolved) { - var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); - for (var i = 0; i < typeDeclTypeParameters.length; i++) { - this.resolveDeclaredSymbol(typeDeclTypeParameters[i], context); - } - } - var typeRefDecls = typeDeclSymbol.getDeclarations(); for (var i = 0; i < typeRefDecls.length; i++) { @@ -39745,13 +40721,20 @@ var TypeScript; } } + if (!typeDeclSymbol.isResolved) { + var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); + for (var i = 0; i < typeDeclTypeParameters.length; i++) { + this.resolveDeclaredSymbol(typeDeclTypeParameters[i], context); + } + } + var wasInBaseTypeResolution = context.startBaseTypeResolution(); if (!typeDeclIsClass && !hasVisited) { typeDeclSymbol.resetKnownBaseTypeCount(); } - var extendsClause = TypeScript.getExtendsHeritageClause(heritageClauses); + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); if (extendsClause) { for (var i = typeDeclSymbol.getKnownBaseTypeCount(); i < extendsClause.typeNames.nonSeparatorCount(); i = typeDeclSymbol.getKnownBaseTypeCount()) { typeDeclSymbol.incrementKnownBaseCount(); @@ -39775,7 +40758,7 @@ var TypeScript; } } - var implementsClause = TypeScript.getImplementsHeritageClause(heritageClauses); + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); if (implementsClause && typeDeclIsClass) { var extendsCount = extendsClause ? extendsClause.typeNames.nonSeparatorCount() : 0; for (var i = typeDeclSymbol.getKnownBaseTypeCount(); ((i - extendsCount) >= 0) && ((i - extendsCount) < implementsClause.typeNames.nonSeparatorCount()); i = typeDeclSymbol.getKnownBaseTypeCount()) { @@ -39801,7 +40784,7 @@ var TypeScript; typeDeclSymbol.inResolution = false; this.typeCheckCallBacks.push(function (context) { - if (classOrInterface.kind() == 131 /* ClassDeclaration */) { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { _this.resolveClassDeclaration(classOrInterface, context); } else { _this.resolveInterfaceDeclaration(classOrInterface, context); @@ -39811,25 +40794,6 @@ var TypeScript; return typeDeclSymbol; } - if (!typeDeclSymbol.isResolved) { - if (!typeDeclIsClass) { - var callSignatures = typeDeclSymbol.getCallSignatures(); - for (var i = 0; i < callSignatures.length; i++) { - this.resolveDeclaredSymbol(callSignatures[i], context); - } - - var constructSignatures = typeDeclSymbol.getConstructSignatures(); - for (var i = 0; i < constructSignatures.length; i++) { - this.resolveDeclaredSymbol(constructSignatures[i], context); - } - - var indexSignatures = typeDeclSymbol.getIndexSignatures(); - for (var i = 0; i < indexSignatures.length; i++) { - this.resolveDeclaredSymbol(indexSignatures[i], context); - } - } - } - this.setSymbolForAST(name, typeDeclSymbol, context); this.setSymbolForAST(classOrInterface, typeDeclSymbol, context); @@ -39841,6 +40805,7 @@ var TypeScript; PullTypeResolver.prototype.resolveClassDeclaration = function (classDeclAST, context) { var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); var classDeclSymbol = classDecl.getSymbol(); + if (!classDeclSymbol.isResolved) { this.resolveReferenceTypeDeclaration(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, context); @@ -39869,15 +40834,9 @@ var TypeScript; if (!parentConstructSignatures.length) { parentConstructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); parentConstructSignature.returnType = parentType; - parentConstructorType.addConstructSignature(parentConstructSignature); + parentConstructSignature.addTypeParametersFromReturnType(); + parentConstructorType.appendConstructSignature(parentConstructSignature); parentConstructSignature.addDeclaration(parentType.getDeclarations()[0]); - - var parentTypeParameters = parentConstructorType.getTypeParameters(); - - for (var i = 0; i < parentTypeParameters.length; i++) { - parentConstructSignature.addTypeParameter(parentTypeParameters[i]); - } - parentConstructSignatures = [parentConstructSignature]; } @@ -39885,33 +40844,23 @@ var TypeScript; parentConstructSignature = parentConstructSignatures[i]; parentParameters = parentConstructSignature.parameters; - constructorSignature = parentConstructSignature.isDefinition() ? new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */) : new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + constructorSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */, parentConstructSignature.isDefinition()); constructorSignature.returnType = classDeclSymbol; + constructorSignature.addTypeParametersFromReturnType(); for (var j = 0; j < parentParameters.length; j++) { constructorSignature.addParameter(parentParameters[j], parentParameters[j].isOptional); } - var typeParameters = constructorTypeSymbol.getTypeParameters(); - - for (var j = 0; j < typeParameters.length; j++) { - constructorSignature.addTypeParameter(typeParameters[j]); - } - - constructorTypeSymbol.addConstructSignature(constructorSignature); + constructorTypeSymbol.appendConstructSignature(constructorSignature); constructorSignature.addDeclaration(classDecl); } } else { constructorSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); constructorSignature.returnType = classDeclSymbol; - constructorTypeSymbol.addConstructSignature(constructorSignature); + constructorSignature.addTypeParametersFromReturnType(); + constructorTypeSymbol.appendConstructSignature(constructorSignature); constructorSignature.addDeclaration(classDecl); - - var typeParameters = constructorTypeSymbol.getTypeParameters(); - - for (var i = 0; i < typeParameters.length; i++) { - constructorSignature.addTypeParameter(typeParameters[i]); - } } } @@ -39944,13 +40893,23 @@ var TypeScript; PullTypeResolver.prototype.typeCheckTypeParametersOfTypeDeclaration = function (classOrInterface, context) { var _this = this; - var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); - var typeDeclSymbol = typeDecl.getSymbol(); - var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); - for (var i = 0; i < typeDeclTypeParameters.length; i++) { - this.checkSymbolPrivacy(typeDeclSymbol, typeDeclTypeParameters[i], function (symbol) { - return _this.typeParameterOfTypeDeclarationPrivacyErrorReporter(classOrInterface, i, typeDeclTypeParameters[i], symbol, context); - }); + var typeParametersList = classOrInterface.kind() == 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + if (typeParametersList) { + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var typeDeclSymbol = typeDecl.getSymbol(); + + for (var i = 0; i < typeParametersList.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParametersList.typeParameters.nonSeparatorAt(i); + this.resolveTypeParameterDeclaration(typeParameterAST, context); + + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.checkSymbolPrivacy(typeDeclSymbol, typeParameterSymbol, function (symbol) { + return _this.typeParameterOfTypeDeclarationPrivacyErrorReporter(classOrInterface, typeParameterAST, typeParameterSymbol, symbol, context); + }); + } } }; @@ -39969,6 +40928,8 @@ var TypeScript; if (!classDeclSymbol.hasBaseTypeConflict()) { this.typeCheckMembersAgainstIndexer(classDeclSymbol, classDecl, context); } + + this.checkTypeForDuplicateIndexSignatures(classDeclSymbol); }; PullTypeResolver.prototype.postTypeCheckClassDeclaration = function (classDeclAST, context) { @@ -40025,6 +40986,88 @@ var TypeScript; if (!interfaceDeclSymbol.hasBaseTypeConflict()) { this.typeCheckMembersAgainstIndexer(interfaceDeclSymbol, interfaceDecl, context); } + + var allInterfaceDecls = interfaceDeclSymbol.getDeclarations(); + if (interfaceDecl === allInterfaceDecls[allInterfaceDecls.length - 1]) { + this.checkTypeForDuplicateIndexSignatures(interfaceDeclSymbol); + } + + if (!this.checkInterfaceDeclForIdenticalTypeParameters(interfaceDeclAST, context)) { + this.semanticInfoChain.addDiagnosticFromAST(interfaceDeclAST.identifier, TypeScript.DiagnosticCode.All_declarations_of_an_interface_must_have_identical_type_parameters); + } + }; + + PullTypeResolver.prototype.checkInterfaceDeclForIdenticalTypeParameters = function (interfaceDeclAST, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + if (!interfaceDeclSymbol.isGeneric()) { + return true; + } + + var firstInterfaceDecl = interfaceDeclSymbol.getDeclarations()[0]; + if (firstInterfaceDecl == interfaceDecl) { + return true; + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var firstInterfaceDeclTypeParameters = firstInterfaceDecl.getTypeParameters(); + + if (typeParameters.length != firstInterfaceDeclTypeParameters.length) { + return false; + } + + for (var i = 0; i < typeParameters.length; i++) { + var typeParameter = typeParameters[i]; + var firstInterfaceDeclTypeParameter = firstInterfaceDeclTypeParameters[i]; + + if (typeParameter.name != firstInterfaceDeclTypeParameter.name) { + return false; + } + + var typeParameterSymbol = typeParameter.getSymbol(); + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter); + var firstInterfaceDeclTypeParameterAST = this.semanticInfoChain.getASTForDecl(firstInterfaceDeclTypeParameter); + + if (!!typeParameterAST.constraint != !!firstInterfaceDeclTypeParameterAST.constraint) { + return false; + } + + if (typeParameterAST.constraint) { + var typeParameterConstraint = this.resolveAST(typeParameterAST.constraint, false, context); + if (!this.typesAreIdenticalWithNewEnclosingTypes(typeParameterConstraint, typeParameterSymbol.getConstraint(), context)) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.checkTypeForDuplicateIndexSignatures = function (enclosingTypeSymbol) { + var indexSignatures = enclosingTypeSymbol.getOwnIndexSignatures(); + var firstStringIndexer = null; + var firstNumberIndexer = null; + for (var i = 0; i < indexSignatures.length; i++) { + var currentIndexer = indexSignatures[i]; + var currentParameterType = currentIndexer.parameters[0].type; + TypeScript.Debug.assert(currentParameterType); + if (currentParameterType === this.semanticInfoChain.stringTypeSymbol) { + if (firstStringIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_string_index_signature, null, [this.semanticInfoChain.locationFromAST(firstStringIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstStringIndexer = currentIndexer; + } + } else if (currentParameterType === this.semanticInfoChain.numberTypeSymbol) { + if (firstNumberIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_number_index_signature, null, [this.semanticInfoChain.locationFromAST(firstNumberIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstNumberIndexer = currentIndexer; + } + } + } }; PullTypeResolver.prototype.filterSymbol = function (symbol, kind, enclosingDecl, context) { @@ -40039,7 +41082,7 @@ var TypeScript; var alias = symbol; if (kind & 164 /* SomeContainer */) { return alias.getExportAssignedContainerSymbol(); - } else if (kind & 58728539 /* SomeType */) { + } else if (kind & 58728795 /* SomeType */) { return alias.getExportAssignedTypeSymbol(); } else if (kind & 68147712 /* SomeValue */) { return alias.getExportAssignedValueSymbol(); @@ -40050,7 +41093,7 @@ var TypeScript; }; PullTypeResolver.prototype.getMemberSymbolOfKind = function (symbolName, kind, pullTypeSymbol, enclosingDecl, context) { - var memberSymbol = this.getMemberSymbol(symbolName, kind, pullTypeSymbol); + var memberSymbol = this.getNamedPropertySymbol(symbolName, kind, pullTypeSymbol); return { symbol: this.filterSymbol(memberSymbol, kind, enclosingDecl, context), @@ -40074,11 +41117,11 @@ var TypeScript; var acceptableAlias = true; if (containerSymbol) { - acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) != 0; + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; aliasSymbol = memberSymbol.aliasSymbol; } - if (!acceptableAlias && containerSymbol && containerSymbol.kind == 128 /* TypeAlias */) { + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { this.resolveDeclaredSymbol(containerSymbol, context); var aliasedAssignedValue = containerSymbol.getExportAssignedValueSymbol(); var aliasedAssignedType = containerSymbol.getExportAssignedTypeSymbol(); @@ -40109,7 +41152,7 @@ var TypeScript; } if (!typeSymbol) { - memberSymbol = this.getMemberSymbolOfKind(rhsName, 58728539 /* SomeType */, moduleTypeSymbol, enclosingDecl, context); + memberSymbol = this.getMemberSymbolOfKind(rhsName, 58728795 /* SomeType */, moduleTypeSymbol, enclosingDecl, context); typeSymbol = memberSymbol.symbol; if (typeSymbol && memberSymbol.aliasSymbol) { aliasSymbol = memberSymbol.aliasSymbol; @@ -40134,12 +41177,12 @@ var TypeScript; }; PullTypeResolver.prototype.resolveModuleReference = function (importDecl, moduleNameExpr, enclosingDecl, context, declPath) { - TypeScript.Debug.assert(moduleNameExpr.kind() == 121 /* QualifiedName */ || moduleNameExpr.kind() == 11 /* IdentifierName */ || moduleNameExpr.kind() === 14 /* StringLiteral */, "resolving module reference should always be either name or member reference"); + TypeScript.Debug.assert(moduleNameExpr.kind() === 121 /* QualifiedName */ || moduleNameExpr.kind() === 11 /* IdentifierName */ || moduleNameExpr.kind() === 14 /* StringLiteral */, "resolving module reference should always be either name or member reference"); var moduleSymbol = null; var moduleName; - if (moduleNameExpr.kind() == 121 /* QualifiedName */) { + if (moduleNameExpr.kind() === 121 /* QualifiedName */) { var dottedNameAST = moduleNameExpr; var moduleContainer = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); if (moduleContainer) { @@ -40161,6 +41204,8 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(moduleNameExpr, moduleSymbol); if (resolvedModuleNameSymbol.isAlias()) { this.semanticInfoChain.setAliasSymbolForAST(moduleNameExpr, resolvedModuleNameSymbol); + var importDeclSymbol = importDecl.getSymbol(); + importDeclSymbol.addLinkedAliasSymbol(resolvedModuleNameSymbol); } } else { this.semanticInfoChain.addDiagnosticFromAST(moduleNameExpr, TypeScript.DiagnosticCode.Unable_to_resolve_module_reference_0, [valueText]); @@ -40181,6 +41226,7 @@ var TypeScript; var declPath = enclosingDecl.getParentPath(); var aliasedType = null; + var importDeclSymbol = importDecl.getSymbol(); if (aliasExpr.kind() === 11 /* IdentifierName */ || aliasExpr.kind() === 14 /* StringLiteral */) { var moduleSymbol = this.resolveModuleReference(importDecl, aliasExpr, enclosingDecl, context, declPath); @@ -40192,19 +41238,17 @@ var TypeScript; var valueSymbol = this.getSymbolFromDeclPath(moduleName, declPath, 68147712 /* SomeValue */); var instanceSymbol = aliasedType.getInstanceSymbol(); - if (valueSymbol && (instanceSymbol != valueSymbol || valueSymbol.type == aliasedType)) { + if (valueSymbol && (instanceSymbol != valueSymbol || valueSymbol.type === aliasedType)) { var text = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.text() : aliasExpr.text(); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(aliasExpr, TypeScript.DiagnosticCode.Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1, [text, moduleSymbol.type.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); } else { - var importDeclSymbol = importDecl.getSymbol(); importDeclSymbol.setAssignedValueSymbol(valueSymbol); } } } else { - aliasedType = this.semanticInfoChain.anyTypeSymbol; + aliasedType = this.getNewErrorTypeSymbol(); } - } else if (aliasExpr.kind() == 121 /* QualifiedName */) { - var importDeclSymbol = importDecl.getSymbol(); + } else if (aliasExpr.kind() === 121 /* QualifiedName */) { var dottedNameAST = aliasExpr; var moduleSymbol = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); if (moduleSymbol) { @@ -40214,14 +41258,13 @@ var TypeScript; importDeclSymbol.setAssignedTypeSymbol(identifierResolution.typeSymbol); importDeclSymbol.setAssignedContainerSymbol(identifierResolution.containerSymbol); this.semanticInfoChain.setAliasSymbolForAST(moduleReference, identifierResolution.aliasSymbol); - if (identifierResolution.valueSymbol) { - importDeclSymbol.setIsUsedAsValue(true); - } return null; } } + } - importDeclSymbol.setAssignedTypeSymbol(this.semanticInfoChain.anyTypeSymbol); + if (!aliasedType) { + importDeclSymbol.setAssignedTypeSymbol(this.getNewErrorTypeSymbol()); } return aliasedType; @@ -40249,7 +41292,7 @@ var TypeScript; if (!aliasedType) { var path = importStatementAST.moduleReference.stringLiteral.text(); this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Unable_to_resolve_external_module_0, [path]); - aliasedType = this.semanticInfoChain.anyTypeSymbol; + aliasedType = this.getNewErrorTypeSymbol(); } } else { aliasedType = this.resolveInternalModuleReference(importStatementAST, context); @@ -40258,9 +41301,9 @@ var TypeScript; if (aliasedType) { if (!aliasedType.isContainer()) { this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Module_cannot_be_aliased_to_a_non_module_type); - aliasedType = this.semanticInfoChain.anyTypeSymbol; - } else if (aliasedType.getExportAssignedValueSymbol()) { - importDeclSymbol.setIsUsedAsValue(true); + if (!aliasedType.isError()) { + aliasedType = this.getNewErrorTypeSymbol(); + } } if (aliasedType.isContainer()) { @@ -40277,6 +41320,14 @@ var TypeScript; this.resolveDeclaredSymbol(importDeclSymbol.assignedType(), context); this.resolveDeclaredSymbol(importDeclSymbol.assignedContainer(), context); + if (aliasedType && importDeclSymbol.anyDeclHasFlag(1 /* Exported */)) { + importDeclSymbol.setIsUsedInExportedAlias(); + + if (aliasedType.isContainer() && aliasedType.getExportAssignedValueSymbol()) { + importDeclSymbol.setIsUsedAsValue(); + } + } + if (this.canTypeCheckAST(importStatementAST, context)) { this.typeCheckImportDeclaration(importStatementAST, context); } @@ -40299,7 +41350,7 @@ var TypeScript; var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); if (enclosingDecl.kind === 32 /* DynamicModule */) { - var ast = TypeScript.getEnclosingModuleDeclaration(this.getASTForDecl(enclosingDecl)); + var ast = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(this.getASTForDecl(enclosingDecl)); if (ast && ast.kind() === 130 /* ModuleDeclaration */) { if (TypeScript.isRelative(modPath)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name)); @@ -40312,7 +41363,7 @@ var TypeScript; if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); var container = containerSymbol ? containerSymbol.getContainer() : null; - if (container && container.kind == 32 /* DynamicModule */) { + if (container && container.kind === 32 /* DynamicModule */) { checkPrivacy = true; } } else { @@ -40330,7 +41381,7 @@ var TypeScript; context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); }); - if (typeSymbol != containerSymbol) { + if (typeSymbol !== containerSymbol) { this.checkSymbolPrivacy(importDeclSymbol, typeSymbol, function (symbol) { var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1; @@ -40348,14 +41399,18 @@ var TypeScript; } } - if (getCompilerReservedName(importStatementAST.identifier)) { - this.postTypeCheckWorkitems.push(importStatementAST); - } + this.checkNameForCompilerGeneratedDeclarationCollision(importStatementAST, true, importStatementAST.identifier, context); }; PullTypeResolver.prototype.postTypeCheckImportDeclaration = function (importStatementAST, context) { - if (TypeScript.importDeclarationIsElided(importStatementAST, this.semanticInfoChain)) { - this.checkNameForCompilerGeneratedDeclarationCollision(importStatementAST, true, importStatementAST.identifier, context, true); + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var importSymbol = importDecl.getSymbol(); + + var isUsedAsValue = importSymbol.isUsedAsValue(); + var hasAssignedValue = importStatementAST.moduleReference.kind() !== 245 /* ExternalModuleReference */ && importSymbol.getExportAssignedValueSymbol() !== null; + + if (isUsedAsValue || hasAssignedValue) { + this.checkThisCaptureVariableCollides(importStatementAST, true, context); } }; @@ -40384,10 +41439,10 @@ var TypeScript; var acceptableAlias = true; if (containerSymbol) { - acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) != 0; + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; } - if (!acceptableAlias && containerSymbol && containerSymbol.kind == 128 /* TypeAlias */) { + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { this.resolveDeclaredSymbol(containerSymbol, context); var aliasSymbol = containerSymbol; @@ -40399,7 +41454,10 @@ var TypeScript; valueSymbol = aliasedAssignedValue; typeSymbol = aliasedAssignedType; containerSymbol = aliasedAssignedContainer; - aliasSymbol.setTypeUsedExternally(true); + aliasSymbol.setTypeUsedExternally(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + } acceptableAlias = true; } } @@ -40413,7 +41471,7 @@ var TypeScript; valueSymbol = this.getSymbolFromDeclPath(id, declPath, 68147712 /* SomeValue */); } if (!typeSymbol) { - typeSymbol = this.getSymbolFromDeclPath(id, declPath, 58728539 /* SomeType */); + typeSymbol = this.getSymbolFromDeclPath(id, declPath, 58728795 /* SomeType */); } if (!valueSymbol && !typeSymbol && !containerSymbol) { @@ -40477,28 +41535,32 @@ var TypeScript; var paramSymbol = paramDecl.getSymbol(); if (argDeclAST.typeAnnotation) { - var typeRef = this.resolveTypeReference(TypeScript.getType(argDeclAST), context); + var typeRef = this.resolveTypeReference(TypeScript.ASTHelpers.getType(argDeclAST), context); if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { - var diagnostic = context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); typeRef = this.getNewErrorTypeSymbol(); } context.setTypeInContext(paramSymbol, typeRef); } else { - if (paramSymbol.isVarArg && paramSymbol.type) { + if (paramSymbol.isVarArg) { if (this.cachedArrayInterfaceType()) { - context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [paramSymbol.type])); + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); } else { - context.setTypeInContext(paramSymbol, paramSymbol.type); + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); } } else { context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); - - if (this.compilationSettings.noImplicitAny()) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_function_type_implicitly_has_an_any_type, [argDeclAST.identifier.text()])); - } } + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_function_type_implicitly_has_an_any_type, [argDeclAST.identifier.text()])); + } + } + + if (TypeScript.hasFlag(paramDecl.flags, 128 /* Optional */) && argDeclAST.equalsValueClause && isTypesOnlyLocation(argDeclAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); } paramSymbol.setResolved(); @@ -40521,22 +41583,29 @@ var TypeScript; contextualType = typeRef || contextualType; } if (contextualType) { + if (context.isInferentiallyTyping()) { + contextualType = context.fixAllTypeParametersReferencedByType(contextualType, this); + } context.setTypeInContext(paramSymbol, contextualType); - } else if (paramSymbol.isVarArg && this.cachedArrayInterfaceType()) { - context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } isImplicitAny = true; } var canTypeCheckAST = this.canTypeCheckAST(argDeclAST, context); if (equalsValueClause && (canTypeCheckAST || !contextualType)) { if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.propagateContextualType(contextualType); } - var initExprSymbol = this.resolveAST(equalsValueClause, contextualType != null, context); + var initExprSymbol = this.resolveAST(equalsValueClause, contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); } if (!initExprSymbol || !initExprSymbol.type) { @@ -40548,7 +41617,7 @@ var TypeScript; } else { var initTypeSymbol = this.getInstanceTypeForAssignment(argDeclAST, initExprSymbol.type, context); if (!contextualType) { - context.setTypeInContext(paramSymbol, this.widenType(initTypeSymbol, equalsValueClause, context)); + context.setTypeInContext(paramSymbol, initTypeSymbol.widenedType(this, equalsValueClause, context)); isImplicitAny = initTypeSymbol !== paramSymbol.type; } else { var comparisonInfo = new TypeComparisonInfo(); @@ -40588,42 +41657,31 @@ var TypeScript; paramSymbol.setResolved(); }; - PullTypeResolver.prototype.checkNameForCompilerGeneratedDeclarationCollision = function (astWithName, isDeclaration, name, context, immediateThisCheck) { + PullTypeResolver.prototype.checkNameForCompilerGeneratedDeclarationCollision = function (astWithName, isDeclaration, name, context) { var compilerReservedName = getCompilerReservedName(name); - if (compilerReservedName) { - switch (compilerReservedName) { - case 1 /* _this */: - if (immediateThisCheck) { - this.checkThisCaptureVariableCollides(astWithName, isDeclaration, context); - } else { - this.postTypeCheckWorkitems.push(astWithName); - } - return; + switch (compilerReservedName) { + case 1 /* _this */: + this.postTypeCheckWorkitems.push(astWithName); + return; - case 2 /* _super */: - this.checkSuperCaptureVariableCollides(astWithName, isDeclaration, context); - return; + case 2 /* _super */: + this.checkSuperCaptureVariableCollides(astWithName, isDeclaration, context); + return; - case 3 /* arguments */: - this.checkArgumentsCollides(astWithName, context); - return; + case 3 /* arguments */: + this.checkArgumentsCollides(astWithName, context); + return; - case 4 /* _i */: - if (isDeclaration) { - this.checkIndexOfRestArgumentInitializationCollides(astWithName, context); - } - return; + case 4 /* _i */: + this.checkIndexOfRestArgumentInitializationCollides(astWithName, isDeclaration, context); + return; - case 5 /* require */: - case 6 /* exports */: - if (isDeclaration) { - this.checkExternalModuleRequireExportsCollides(astWithName, name, context); - } - return; - - default: - TypeScript.Debug.fail("Unknown compiler reserved name: " + name.text()); - } + case 5 /* require */: + case 6 /* exports */: + if (isDeclaration) { + this.checkExternalModuleRequireExportsCollides(astWithName, name, context); + } + return; } }; @@ -40631,16 +41689,16 @@ var TypeScript; var enclosingAST = this.getASTForDecl(someFunctionDecl); var nodeType = enclosingAST.kind(); - if (nodeType == 129 /* FunctionDeclaration */) { + if (nodeType === 129 /* FunctionDeclaration */) { var functionDeclaration = enclosingAST; - return !TypeScript.hasFlag(someFunctionDecl.kind == 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && functionDeclaration.block && TypeScript.lastParameterIsRest(functionDeclaration.callSignature.parameterList); + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && functionDeclaration.block && TypeScript.lastParameterIsRest(functionDeclaration.callSignature.parameterList); } else if (nodeType === 135 /* MemberFunctionDeclaration */) { var memberFunction = enclosingAST; - return !TypeScript.hasFlag(someFunctionDecl.kind == 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && memberFunction.block && TypeScript.lastParameterIsRest(memberFunction.callSignature.parameterList); - } else if (nodeType == 137 /* ConstructorDeclaration */) { + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && memberFunction.block && TypeScript.lastParameterIsRest(memberFunction.callSignature.parameterList); + } else if (nodeType === 137 /* ConstructorDeclaration */) { var constructorDeclaration = enclosingAST; - return !TypeScript.hasFlag(someFunctionDecl.getParentDecl().flags, 8 /* Ambient */) && constructorDeclaration.block && TypeScript.lastParameterIsRest(constructorDeclaration.parameterList); - } else if (nodeType == 218 /* ParenthesizedArrowFunctionExpression */) { + return !TypeScript.hasFlag(someFunctionDecl.getParentDecl().flags, 8 /* Ambient */) && constructorDeclaration.block && TypeScript.lastParameterIsRest(constructorDeclaration.callSignature.parameterList); + } else if (nodeType === 218 /* ParenthesizedArrowFunctionExpression */) { var arrowFunctionExpression = enclosingAST; return TypeScript.lastParameterIsRest(arrowFunctionExpression.callSignature.parameterList); } else if (nodeType === 222 /* FunctionExpression */) { @@ -40652,7 +41710,7 @@ var TypeScript; }; PullTypeResolver.prototype.checkArgumentsCollides = function (ast, context) { - if (ast.kind() == 242 /* Parameter */) { + if (ast.kind() === 242 /* Parameter */) { var enclosingDecl = this.getEnclosingDeclForAST(ast); if (TypeScript.hasFlag(enclosingDecl.kind, 1032192 /* SomeFunction */)) { if (this.hasRestParameterCodeGen(enclosingDecl)) { @@ -40662,12 +41720,33 @@ var TypeScript; } }; - PullTypeResolver.prototype.checkIndexOfRestArgumentInitializationCollides = function (ast, context) { - if (ast.kind() == 242 /* Parameter */) { + PullTypeResolver.prototype.checkIndexOfRestArgumentInitializationCollides = function (ast, isDeclaration, context) { + if (!isDeclaration || ast.kind() === 242 /* Parameter */) { var enclosingDecl = this.getEnclosingDeclForAST(ast); - if (TypeScript.hasFlag(enclosingDecl.kind, 1032192 /* SomeFunction */)) { - if (this.hasRestParameterCodeGen(enclosingDecl)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter)); + var declPath = isDeclaration ? [enclosingDecl] : (enclosingDecl ? enclosingDecl.getParentPath() : []); + var resolvedSymbol = null; + var resolvedSymbolContainer; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (!isDeclaration) { + if (!resolvedSymbol) { + resolvedSymbol = this.resolveNameExpression(ast, context); + if (resolvedSymbol.isError()) { + return; + } + + resolvedSymbolContainer = resolvedSymbol.getContainer(); + } + + if (resolvedSymbolContainer && TypeScript.ArrayUtilities.contains(resolvedSymbolContainer.getDeclarations(), decl)) { + break; + } + } + + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter)); + } } } } @@ -40676,12 +41755,12 @@ var TypeScript; PullTypeResolver.prototype.checkExternalModuleRequireExportsCollides = function (ast, name, context) { var enclosingDecl = this.getEnclosingDeclForAST(ast); - var enclosingModule = TypeScript.getEnclosingModuleDeclaration(name); - if (TypeScript.isAnyNameOfModule(enclosingModule, name)) { + var enclosingModule = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(name); + if (TypeScript.ASTHelpers.isAnyNameOfModule(enclosingModule, name)) { enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); } - if (enclosingDecl && enclosingDecl.kind == 32 /* DynamicModule */) { + if (enclosingDecl && enclosingDecl.kind === 32 /* DynamicModule */) { var decl = this.semanticInfoChain.getDeclForAST(ast); if (!TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { @@ -40733,6 +41812,7 @@ var TypeScript; var objectTypeSymbol = objectTypeDecl.getSymbol(); this.typeCheckMembersAgainstIndexer(objectTypeSymbol, objectTypeDecl, context); + this.checkTypeForDuplicateIndexSignatures(objectTypeSymbol); }; PullTypeResolver.prototype.resolveTypeAnnotation = function (typeAnnotation, context) { @@ -40749,11 +41829,11 @@ var TypeScript; var aliasType = null; var type = this.computeTypeReferenceSymbol(typeRef, context); - if (type.kind == 4 /* Container */) { + if (type.kind === 4 /* Container */) { var container = type; var instanceSymbol = container.getInstanceSymbol(); - if (instanceSymbol && (instanceSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */) || instanceSymbol.kind == 32768 /* ConstructorMethod */)) { + if (instanceSymbol && (instanceSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */) || instanceSymbol.kind === 32768 /* ConstructorMethod */)) { type = instanceSymbol.type.getAssociatedContainerType(); } } @@ -40770,7 +41850,7 @@ var TypeScript; } if (type && !type.isError()) { - if ((type.kind & 58728539 /* SomeType */) === 0) { + if ((type.kind & 58728795 /* SomeType */) === 0) { if (type.kind & 164 /* SomeContainer */) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_cannot_refer_to_container_0, [aliasType ? aliasType.toString() : type.toString()])); } else { @@ -40786,6 +41866,22 @@ var TypeScript; return type; }; + PullTypeResolver.prototype.getArrayType = function (elementType) { + var arraySymbol = elementType.getArrayType(); + + if (!arraySymbol) { + arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + + elementType.setArrayType(arraySymbol); + } + + return arraySymbol; + }; + PullTypeResolver.prototype.computeTypeReferenceSymbol = function (term, context) { switch (term.kind()) { case 60 /* AnyKeyword */: @@ -40820,7 +41916,7 @@ var TypeScript; var stringConstantAST = term; var enclosingDecl = this.getEnclosingDeclForAST(term); typeDeclSymbol = new TypeScript.PullStringConstantTypeSymbol(stringConstantAST.text()); - var decl = new TypeScript.PullSynthesizedDecl(stringConstantAST.text(), stringConstantAST.text(), typeDeclSymbol.kind, null, enclosingDecl, new TypeScript.TextSpan(stringConstantAST.start(), stringConstantAST.width()), enclosingDecl.semanticInfoChain()); + var decl = new TypeScript.PullSynthesizedDecl(stringConstantAST.text(), stringConstantAST.text(), typeDeclSymbol.kind, null, enclosingDecl, enclosingDecl.semanticInfoChain); typeDeclSymbol.addDeclaration(decl); } else if (term.kind() === 127 /* TypeQuery */) { var typeQuery = term; @@ -40839,24 +41935,14 @@ var TypeScript; } if (valueSymbol) { - typeDeclSymbol = valueSymbol.type; + typeDeclSymbol = valueSymbol.type.widenedType(this, typeQueryTerm, context); } else { typeDeclSymbol = this.getNewErrorTypeSymbol(); } } else if (term.kind() === 124 /* ArrayType */) { var arrayType = term; - var underlying = this.computeTypeReferenceSymbol(arrayType.type, context); - var arraySymbol = underlying.getArrayType(); - - if (!arraySymbol) { - arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [underlying]); - - if (!arraySymbol) { - arraySymbol = this.semanticInfoChain.anyTypeSymbol; - } - } - - typeDeclSymbol = arraySymbol; + var underlying = this.resolveTypeReference(arrayType.type, context); + typeDeclSymbol = this.getArrayType(underlying); } else { throw TypeScript.Errors.invalidOperation("unknown type"); } @@ -40879,19 +41965,27 @@ var TypeScript; }; PullTypeResolver.prototype.genericTypeIsUsedWithoutRequiredTypeArguments = function (typeSymbol, term, context) { - return typeSymbol.isNamedTypeSymbol() && typeSymbol.isGeneric() && !typeSymbol.isTypeParameter() && (typeSymbol.isResolved || typeSymbol.inResolution) && !typeSymbol.getIsSpecialized() && typeSymbol.getTypeParameters().length && typeSymbol.getTypeArguments() == null && this.isTypeRefWithoutTypeArgs(term); + if (!typeSymbol) { + return false; + } + + if (typeSymbol.isAlias()) { + return this.genericTypeIsUsedWithoutRequiredTypeArguments(typeSymbol.getExportAssignedTypeSymbol(), term, context); + } + + return typeSymbol.isNamedTypeSymbol() && typeSymbol.isGeneric() && !typeSymbol.isTypeParameter() && (typeSymbol.isResolved || typeSymbol.inResolution) && !typeSymbol.getIsSpecialized() && typeSymbol.getTypeParameters().length && typeSymbol.getTypeArguments() === null && this.isTypeRefWithoutTypeArgs(term); }; PullTypeResolver.prototype.resolveMemberVariableDeclaration = function (varDecl, context) { - return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.getType(varDecl.variableDeclarator), varDecl.variableDeclarator.equalsValueClause, context); + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl.variableDeclarator), varDecl.variableDeclarator.equalsValueClause, context); }; PullTypeResolver.prototype.resolvePropertySignature = function (varDecl, context) { - return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.getType(varDecl), null, context); + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); }; PullTypeResolver.prototype.resolveVariableDeclarator = function (varDecl, context) { - return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.getType(varDecl), varDecl.equalsValueClause, context); + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); }; PullTypeResolver.prototype.resolveParameterList = function (list, context) { @@ -40899,7 +41993,7 @@ var TypeScript; }; PullTypeResolver.prototype.resolveParameter = function (parameter, context) { - return this.resolveVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.getType(parameter), parameter.equalsValueClause, context); + return this.resolveVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); }; PullTypeResolver.prototype.getEnumTypeSymbol = function (enumElement, context) { @@ -40932,7 +42026,7 @@ var TypeScript; var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); - if (enclosingDecl && decl.kind == 2048 /* Parameter */) { + if (enclosingDecl && decl.kind === 2048 /* Parameter */) { enclosingDecl.ensureSymbolIsBound(); } @@ -40970,7 +42064,7 @@ var TypeScript; if (!(hasTypeExpr || init)) { var defaultType = this.semanticInfoChain.anyTypeSymbol; - if (declSymbol.isVarArg) { + if (declSymbol.isVarArg && this.cachedArrayInterfaceType()) { defaultType = this.createInstantiatedType(this.cachedArrayInterfaceType(), [defaultType]); } @@ -41012,7 +42106,7 @@ var TypeScript; } var wrapperDecl = this.getEnclosingDecl(decl); - wrapperDecl = wrapperDecl ? wrapperDecl : enclosingDecl; + wrapperDecl = wrapperDecl || enclosingDecl; var typeExprSymbol = this.resolveTypeReference(typeExpr, context); @@ -41029,7 +42123,7 @@ var TypeScript; context.setTypeInContext(declParameterSymbol, typeExprSymbol); } } else { - if (typeExprSymbol == this.semanticInfoChain.anyTypeSymbol) { + if (typeExprSymbol === this.semanticInfoChain.anyTypeSymbol) { decl.setFlag(16777216 /* IsAnnotatedWithAny */); } @@ -41055,7 +42149,7 @@ var TypeScript; } } } - } else if (declSymbol.isVarArg && !(typeExprSymbol.isArrayNamedTypeReference() || typeExprSymbol == this.cachedArrayInterfaceType())) { + } else if (declSymbol.isVarArg && !(typeExprSymbol.isArrayNamedTypeReference() || typeExprSymbol === this.cachedArrayInterfaceType())) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); typeExprSymbol = this.getNewErrorTypeSymbol(); } @@ -41066,7 +42160,7 @@ var TypeScript; declParameterSymbol.type = typeExprSymbol; } - if (typeExprSymbol.kind == 16777216 /* FunctionType */ && !typeExprSymbol.getFunctionSymbol()) { + if (typeExprSymbol.kind === 16777216 /* FunctionType */ && !typeExprSymbol.getFunctionSymbol()) { typeExprSymbol.setFunctionSymbol(declSymbol); } } @@ -41081,7 +42175,7 @@ var TypeScript; var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; if (typeExprSymbol) { - context.pushContextualType(typeExprSymbol, context.inProvisionalResolution(), null); + context.pushNewContextualType(typeExprSymbol); } var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); @@ -41090,12 +42184,12 @@ var TypeScript; var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; var wrapperDecl = this.getEnclosingDecl(decl); - wrapperDecl = wrapperDecl ? wrapperDecl : enclosingDecl; + wrapperDecl = wrapperDecl || enclosingDecl; - var initExprSymbol = this.resolveAST(init, typeExprSymbol != null, context); + var initExprSymbol = this.resolveAST(init, typeExprSymbol !== null, context); if (typeExprSymbol) { - context.popContextualType(); + context.popAnyContextualType(); } if (!initExprSymbol) { @@ -41110,9 +42204,9 @@ var TypeScript; } } else { var initTypeSymbol = initExprSymbol.type; - var widenedInitTypeSymbol = this.widenType(initTypeSymbol, init.value, context); if (!hasTypeExpr) { + var widenedInitTypeSymbol = initTypeSymbol.widenedType(this, init.value, context); context.setTypeInContext(declSymbol, widenedInitTypeSymbol); if (declParameterSymbol) { @@ -41120,30 +42214,32 @@ var TypeScript; } if (this.compilationSettings.noImplicitAny()) { - if ((widenedInitTypeSymbol != initTypeSymbol) && (widenedInitTypeSymbol == this.semanticInfoChain.anyTypeSymbol)) { + if ((widenedInitTypeSymbol !== initTypeSymbol) && (widenedInitTypeSymbol === this.semanticInfoChain.anyTypeSymbol)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); } } + + return widenedInitTypeSymbol; } } - return widenedInitTypeSymbol; + return initTypeSymbol; }; PullTypeResolver.prototype.typeCheckPropertySignature = function (varDecl, context) { - this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.getType(varDecl), null, context); + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); }; PullTypeResolver.prototype.typeCheckMemberVariableDeclaration = function (varDecl, context) { - this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.getType(varDecl), varDecl.variableDeclarator.equalsValueClause, context); + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.variableDeclarator.equalsValueClause, context); }; PullTypeResolver.prototype.typeCheckVariableDeclarator = function (varDecl, context) { - this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.getType(varDecl), varDecl.equalsValueClause, context); + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); }; PullTypeResolver.prototype.typeCheckParameter = function (parameter, context) { - this.typeCheckVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.getType(parameter), parameter.equalsValueClause, context); + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); }; PullTypeResolver.prototype.typeCheckVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { @@ -41199,7 +42295,7 @@ var TypeScript; } } else if (varDeclOrParameter.kind() !== 243 /* EnumElement */ && this.compilationSettings.noImplicitAny() && !this.isForInVariableDeclarator(varDeclOrParameter)) { var wrapperDecl = this.getEnclosingDecl(decl); - wrapperDecl = wrapperDecl ? wrapperDecl : enclosingDecl; + wrapperDecl = wrapperDecl || enclosingDecl; if ((wrapperDecl.kind === 16384 /* Function */ || wrapperDecl.kind === 32768 /* ConstructorMethod */ || wrapperDecl.kind === 2097152 /* ConstructSignature */)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); @@ -41211,7 +42307,7 @@ var TypeScript; } else if (TypeScript.hasFlag(parentDecl.flags, 8 /* Ambient */) && !TypeScript.hasFlag(wrapperDecl.flags, 2 /* Private */)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); } - } else if (wrapperDecl.kind === 8388608 /* ObjectType */) { + } else if (decl.kind === 4096 /* Property */ && !declSymbol.getContainer().isNamedTypeSymbol()) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Member_0_of_object_type_implicitly_has_an_any_type, [name.text()])); } else if (wrapperDecl.kind !== 268435456 /* CatchBlock */) { if (!TypeScript.hasFlag(wrapperDecl.flags, 8 /* Ambient */)) { @@ -41225,16 +42321,16 @@ var TypeScript; if (init && varDeclOrParameter.kind() === 242 /* Parameter */) { var containerSignature = enclosingDecl.getSignatureSymbol(); if (containerSignature && !containerSignature.isDefinition()) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Default_arguments_are_not_allowed_in_an_overload_parameter)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); } } - if (declSymbol.kind != 2048 /* Parameter */ && (declSymbol.kind != 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { + if (declSymbol.kind !== 2048 /* Parameter */ && (declSymbol.kind !== 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { this.checkSymbolPrivacy(declSymbol, declSymbol.type, function (symbol) { return _this.variablePrivacyErrorReporter(varDeclOrParameter, declSymbol, symbol, context); }); } - if ((declSymbol.kind != 4096 /* Property */ && declSymbol.kind != 67108864 /* EnumMember */) || declSymbol.anyDeclHasFlag(8388608 /* PropertyParameter */)) { + if ((declSymbol.kind !== 4096 /* Property */ && declSymbol.kind !== 67108864 /* EnumMember */) || declSymbol.anyDeclHasFlag(8388608 /* PropertyParameter */)) { this.checkNameForCompilerGeneratedDeclarationCollision(varDeclOrParameter, true, name, context); } }; @@ -41245,15 +42341,14 @@ var TypeScript; PullTypeResolver.prototype.checkSuperCaptureVariableCollides = function (superAST, isDeclaration, context) { var enclosingDecl = this.getEnclosingDeclForAST(superAST); - var declPath = enclosingDecl.getParentPath(); var classSymbol = this.getContextualClassSymbolForEnclosingDecl(superAST, enclosingDecl); if (classSymbol && !classSymbol.anyDeclHasFlag(8 /* Ambient */)) { - if (superAST.kind() == 242 /* Parameter */) { + if (superAST.kind() === 242 /* Parameter */) { var enclosingAST = this.getASTForDecl(enclosingDecl); if (enclosingAST.kind() !== 218 /* ParenthesizedArrowFunctionExpression */ && enclosingAST.kind() !== 219 /* SimpleArrowFunctionExpression */) { - var block = enclosingDecl.kind == 65536 /* Method */ ? enclosingAST.block : enclosingAST.block; + var block = enclosingDecl.kind === 65536 /* Method */ ? enclosingAST.block : enclosingAST.block; if (!block) { return; } @@ -41279,8 +42374,8 @@ var TypeScript; var enclosingDecl = this.getEnclosingDeclForAST(_thisAST); - var enclosingModule = TypeScript.getEnclosingModuleDeclaration(_thisAST); - if (TypeScript.isAnyNameOfModule(enclosingModule, _thisAST)) { + var enclosingModule = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(_thisAST); + if (TypeScript.ASTHelpers.isAnyNameOfModule(enclosingModule, _thisAST)) { enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); } @@ -41310,11 +42405,21 @@ var TypeScript; var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); var typeParameterSymbol = typeParameterDecl.getSymbol(); + this.resolveFirstTypeParameterDeclaration(typeParameterSymbol, context); + + if (typeParameterSymbol.isResolved && this.canTypeCheckAST(typeParameterAST, context)) { + this.typeCheckTypeParameterDeclaration(typeParameterAST, context); + } + + return typeParameterSymbol; + }; + + PullTypeResolver.prototype.resolveFirstTypeParameterDeclaration = function (typeParameterSymbol, context) { + var typeParameterDecl = typeParameterSymbol.getDeclarations()[0]; + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecl); + if (typeParameterSymbol.isResolved || typeParameterSymbol.inResolution) { - if (typeParameterSymbol.isResolved && this.canTypeCheckAST(typeParameterAST, context)) { - this.typeCheckTypeParameterDeclaration(typeParameterAST, context); - } - return typeParameterSymbol; + return; } typeParameterSymbol.startResolving(); @@ -41328,18 +42433,27 @@ var TypeScript; } typeParameterSymbol.setResolved(); - - if (this.canTypeCheckAST(typeParameterAST, context)) { - this.setTypeChecked(typeParameterAST, context); - } - - return typeParameterSymbol; }; PullTypeResolver.prototype.typeCheckTypeParameterDeclaration = function (typeParameterAST, context) { this.setTypeChecked(typeParameterAST, context); - this.resolveAST(typeParameterAST.constraint, false, context); + var constraint = this.resolveAST(typeParameterAST.constraint, false, context); + + if (constraint) { + var typeParametersAST = typeParameterAST.parent; + var typeParameters = []; + for (var i = 0; i < typeParametersAST.nonSeparatorCount(); i++) { + var currentTypeParameterAST = typeParametersAST.nonSeparatorAt(i); + var currentTypeParameterDecl = this.semanticInfoChain.getDeclForAST(currentTypeParameterAST); + var currentTypeParameter = this.semanticInfoChain.getSymbolForDecl(currentTypeParameterDecl); + typeParameters[currentTypeParameter.pullSymbolID] = currentTypeParameter; + } + + if (constraint.wrapsSomeTypeParameter(typeParameters)) { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); + } + } }; PullTypeResolver.prototype.resolveConstraint = function (constraint, context) { @@ -41364,6 +42478,7 @@ var TypeScript; case 219 /* SimpleArrowFunctionExpression */: case 218 /* ParenthesizedArrowFunctionExpression */: case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: go = false; break; @@ -41451,20 +42566,12 @@ var TypeScript; var returnType = bestCommonReturnType; var returnExpression = returnExpressions[returnExpressionSymbols.indexOf(returnType)]; - if (useContextualType && returnType == this.semanticInfoChain.anyTypeSymbol) { - var contextualType = context.getContextualType(); - - if (contextualType) { - returnType = contextualType; - } - } - var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); var functionSymbol = functionDecl.getSymbol(); if (returnType) { var previousReturnType = returnType; - var newReturnType = this.widenType(returnType, returnExpression, context); + var newReturnType = returnType.widenedType(this, returnExpression, context); signature.returnType = newReturnType; if (!TypeScript.ArrayUtilities.contains(returnExpressionSymbols, bestCommonReturnType)) { @@ -41474,7 +42581,7 @@ var TypeScript; if (this.compilationSettings.noImplicitAny()) { if (previousReturnType !== newReturnType && newReturnType === this.semanticInfoChain.anyTypeSymbol) { var functionName = enclosingDecl.name; - if (functionName == "") { + if (functionName === "") { functionName = enclosingDecl.getFunctionExpressionName(); } @@ -41500,28 +42607,26 @@ var TypeScript; var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); - if (funcDeclAST.parameterList) { - for (var i = 0; i < funcDeclAST.parameterList.parameters.nonSeparatorCount(); i++) { - this.resolveAST(funcDeclAST.parameterList.parameters.nonSeparatorAt(i), false, context); - } + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveAST(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), false, context); } this.resolveAST(funcDeclAST.block, false, context); if (funcDecl.getSignatureSymbol() && funcDecl.getSignatureSymbol().isDefinition() && this.enclosingClassIsDerived(funcDecl.getParentDecl())) { if (!this.constructorHasSuperCall(funcDeclAST)) { - context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), 11, TypeScript.DiagnosticCode.Constructors_for_derived_classes_must_contain_a_super_call)); + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.Constructors_for_derived_classes_must_contain_a_super_call)); } else if (this.superCallMustBeFirstStatementInConstructor(funcDecl)) { var firstStatement = this.getFirstStatementOfBlockOrNull(funcDeclAST.block); if (!firstStatement || !this.isSuperInvocationExpressionStatement(firstStatement)) { - context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), 11, TypeScript.DiagnosticCode.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties)); + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties)); } } } this.validateVariableDeclarationGroups(funcDecl, context); - this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.callSignature.parameterList), null, funcDeclAST.block, context); this.typeCheckCallBacks.push(function (context) { _this.typeCheckFunctionOverloads(funcDeclAST, context); @@ -41533,9 +42638,18 @@ var TypeScript; if (constructorDecl.block) { var foundSuperCall = false; var pre = function (ast, walker) { - if (_this.isSuperInvocationExpression(ast)) { - foundSuperCall = true; - walker.options.stopWalking = true; + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + walker.options.goChildren = false; + default: + if (_this.isSuperInvocationExpression(ast)) { + foundSuperCall = true; + walker.options.stopWalking = true; + } } }; @@ -41546,19 +42660,31 @@ var TypeScript; return false; }; - PullTypeResolver.prototype.typeCheckFunctionExpression = function (funcDecl, context) { - this.typeCheckAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.getType(funcDecl), funcDecl.block, null, context); + PullTypeResolver.prototype.typeCheckFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), funcDecl.callSignature.typeAnnotation, funcDecl.block, null, isContextuallyTyped, context); }; PullTypeResolver.prototype.typeCheckCallSignature = function (funcDecl, context) { - this.typeCheckFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.getType(funcDecl), null, context); + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; PullTypeResolver.prototype.typeCheckConstructSignature = function (funcDecl, context) { - this.typeCheckFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), null, context); + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; - PullTypeResolver.prototype.typeCheckFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameters, returnTypeAnnotation, block, context) { + PullTypeResolver.prototype.typeCheckMethodSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberFunctionDeclaration = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.containsSingleThrowStatement = function (block) { + return block !== null && block.statements.childCount() === 1 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */; + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameters, returnTypeAnnotation, block, context) { var _this = this; this.setTypeChecked(funcDeclAST, context); @@ -41578,22 +42704,9 @@ var TypeScript; this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); this.validateVariableDeclarationGroups(funcDecl, context); - this.checkFunctionTypePrivacy(funcDeclAST, isStatic, typeParameters, TypeScript.Parameters.fromParameterList(parameters), returnTypeAnnotation, block, context); + this.checkFunctionTypePrivacy(funcDeclAST, isStatic, typeParameters, TypeScript.ASTHelpers.parametersFromParameterList(parameters), returnTypeAnnotation, block, context); - var signature = funcDecl.getSignatureSymbol(); - - var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) != 0; - - if (funcDeclAST.kind() !== 143 /* ConstructSignature */ && block && returnTypeAnnotation != null && !hasReturn) { - var isVoidOrAny = this.isAnyOrEquivalent(signature.returnType) || signature.returnType === this.semanticInfoChain.voidTypeSymbol; - - if (!isVoidOrAny && !(block.statements.childCount() > 0 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */)) { - var funcName = funcDecl.getDisplayName(); - funcName = funcName ? funcName : "expression"; - - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_0_declared_a_non_void_return_type_but_has_no_return_expression, [funcName])); - } - } + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(funcDecl, returnTypeAnnotation, funcDecl.getSignatureSymbol().returnType, block, context); if (funcDecl.kind === 16384 /* Function */) { this.checkNameForCompilerGeneratedDeclarationCollision(funcDeclAST, true, name, context); @@ -41604,6 +42717,20 @@ var TypeScript; }); }; + PullTypeResolver.prototype.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement = function (functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context) { + var hasReturn = TypeScript.hasFlag(functionDecl.flags, 4194304 /* HasReturnStatement */); + + if (block !== null && returnTypeAnnotation !== null && !hasReturn) { + var isVoidOrAny = this.isAnyOrEquivalent(returnTypeSymbol) || returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol; + + if (!isVoidOrAny && !this.containsSingleThrowStatement(block)) { + var funcName = functionDecl.getDisplayName() || TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_declared_a_non_void_return_type_but_has_no_return_expression)); + } + } + }; + PullTypeResolver.prototype.typeCheckIndexSignature = function (funcDeclAST, context) { var _this = this; this.setTypeChecked(funcDeclAST, context); @@ -41614,16 +42741,16 @@ var TypeScript; var enclosingDecl = this.getEnclosingDecl(funcDecl); - this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.getType(funcDeclAST), context); + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); this.validateVariableDeclarationGroups(funcDecl, context); - this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.Parameters.fromParameter(funcDeclAST.parameter), TypeScript.getType(funcDeclAST), null, context); + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameter(funcDeclAST.parameter), TypeScript.ASTHelpers.getType(funcDeclAST), null, context); var signature = funcDecl.getSignatureSymbol(); this.typeCheckCallBacks.push(function (context) { var parentSymbol = funcDecl.getSignatureSymbol().getContainer(); - var allIndexSignatures = _this.getBothKindsOfIndexSignatures(parentSymbol, context); + var allIndexSignatures = _this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parentSymbol, context); var stringIndexSignature = allIndexSignatures.stringSignature; var numberIndexSignature = allIndexSignatures.numericSignature; var isNumericIndexer = numberIndexSignature === signature; @@ -41631,12 +42758,12 @@ var TypeScript; if (numberIndexSignature && stringIndexSignature && (isNumericIndexer || stringIndexSignature.getDeclarations()[0].getParentDecl() !== numberIndexSignature.getDeclarations()[0].getParentDecl())) { var comparisonInfo = new TypeComparisonInfo(); - if (!_this.sourceIsSubtypeOfTarget(numberIndexSignature.returnType, stringIndexSignature.returnType, funcDeclAST, context, comparisonInfo)) { + if (!_this.sourceIsAssignableToTarget(numberIndexSignature.returnType, stringIndexSignature.returnType, funcDeclAST, context, comparisonInfo)) { var enclosingSymbol = _this.getEnclosingSymbolForAST(funcDeclAST); if (comparisonInfo.message) { - context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_a_subtype_of_string_indexer_type_1_NL_2, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); } else { - context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_a_subtype_of_string_indexer_type_1, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol)])); + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol)])); } } } @@ -41657,7 +42784,7 @@ var TypeScript; if (indexerKindMatchesMemberNameKind || onlyStringIndexerIsPresent) { var comparisonInfo = new TypeComparisonInfo(); - if (!_this.sourceIsSubtypeOfTarget(allMembers[i].type, signature.returnType, funcDeclAST, context, comparisonInfo, false)) { + if (!_this.sourceIsAssignableToTarget(allMembers[i].type, signature.returnType, funcDeclAST, context, comparisonInfo, false)) { _this.reportErrorThatMemberIsNotSubtypeOfIndexer(allMembers[i], signature, funcDeclAST, context, comparisonInfo); } } @@ -41693,35 +42820,35 @@ var TypeScript; }; PullTypeResolver.prototype.resolveMemberFunctionDeclaration = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), funcDecl.block, context); + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); }; PullTypeResolver.prototype.resolveCallSignature = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.getType(funcDecl), null, context); + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; PullTypeResolver.prototype.resolveConstructSignature = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), null, context); + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; PullTypeResolver.prototype.resolveMethodSignature = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), null, context); + return this.resolveFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); }; PullTypeResolver.prototype.resolveAnyFunctionDeclaration = function (funcDecl, context) { - return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), funcDecl.block, context); + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); }; PullTypeResolver.prototype.resolveFunctionExpression = function (funcDecl, isContextuallyTyped, context) { - return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList), TypeScript.getType(funcDecl), funcDecl.block, null, isContextuallyTyped, context); + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, null, isContextuallyTyped, context); }; PullTypeResolver.prototype.resolveSimpleArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { - return this.resolveAnyFunctionExpression(funcDecl, null, TypeScript.Parameters.fromIdentifier(funcDecl.identifier), null, funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + return this.resolveAnyFunctionExpression(funcDecl, null, TypeScript.ASTHelpers.parametersFromIdentifier(funcDecl.identifier), null, funcDecl.block, funcDecl.expression, isContextuallyTyped, context); }; PullTypeResolver.prototype.resolveParenthesizedArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { - return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList), TypeScript.getType(funcDecl), funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, funcDecl.expression, isContextuallyTyped, context); }; PullTypeResolver.prototype.getEnclosingClassDeclaration = function (ast) { @@ -41786,18 +42913,16 @@ var TypeScript; } signature.startResolving(); - if (funcDeclAST.parameterList) { - var prevInTypeCheck = context.inTypeCheck; + var prevInTypeCheck = context.inTypeCheck; - context.inTypeCheck = false; + context.inTypeCheck = false; - for (var i = 0; i < funcDeclAST.parameterList.parameters.nonSeparatorCount(); i++) { - this.resolveParameter(funcDeclAST.parameterList.parameters.nonSeparatorAt(i), context); - } - - context.inTypeCheck = prevInTypeCheck; + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), context); } + context.inTypeCheck = prevInTypeCheck; + if (signature.isGeneric()) { if (funcSymbol) { funcSymbol.type.setHasGenericSignature(); @@ -41855,9 +42980,9 @@ var TypeScript; if (signature.inResolution) { if (funcDeclAST.typeAnnotation) { - var returnTypeSymbol = this.resolveTypeReference(TypeScript.getType(funcDeclAST), context); + var returnTypeSymbol = this.resolveTypeReference(TypeScript.ASTHelpers.getType(funcDeclAST), context); if (!returnTypeSymbol) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(TypeScript.getType(funcDeclAST), TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(TypeScript.ASTHelpers.getType(funcDeclAST), TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); signature.returnType = this.getNewErrorTypeSymbol(); hadError = true; } else { @@ -41891,7 +43016,7 @@ var TypeScript; } if (funcDeclAST.typeAnnotation) { - returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.getType(funcDeclAST), context); + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); if (!returnTypeSymbol) { signature.returnType = this.getNewErrorTypeSymbol(); @@ -41901,16 +43026,6 @@ var TypeScript; } } else { signature.returnType = this.semanticInfoChain.anyTypeSymbol; - var parentDeclFlags = 0 /* None */; - if (TypeScript.hasFlag(funcDecl.kind, 65536 /* Method */) || TypeScript.hasFlag(funcDecl.kind, 32768 /* ConstructorMethod */)) { - var parentDecl = funcDecl.getParentDecl(); - parentDeclFlags = parentDecl.flags; - } - - if (this.compilationSettings.noImplicitAny() && (!TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) || (TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) && !TypeScript.hasFlag(funcDecl.flags, 2 /* Private */)))) { - var funcDeclASTName = name; - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, ["Indexer"])); - } } if (!hadError) { @@ -41949,7 +43064,7 @@ var TypeScript; if (signature) { if (signature.isResolved) { if (this.canTypeCheckAST(funcDeclAST, context)) { - this.typeCheckFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); } return funcSymbol; } @@ -42073,7 +43188,7 @@ var TypeScript; } if (this.canTypeCheckAST(funcDeclAST, context)) { - this.typeCheckFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); } return funcSymbol; @@ -42081,7 +43196,7 @@ var TypeScript; PullTypeResolver.prototype.resolveGetterReturnTypeAnnotation = function (getterFunctionDeclarationAst, enclosingDecl, context) { if (getterFunctionDeclarationAst && getterFunctionDeclarationAst.typeAnnotation) { - return this.resolveTypeReference(TypeScript.getType(getterFunctionDeclarationAst), context); + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), context); } return null; @@ -42090,7 +43205,7 @@ var TypeScript; PullTypeResolver.prototype.resolveSetterArgumentTypeAnnotation = function (setterFunctionDeclarationAst, enclosingDecl, context) { if (setterFunctionDeclarationAst && setterFunctionDeclarationAst.parameterList && setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorCount() > 0) { var parameter = setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorAt(0); - return this.resolveTypeReference(TypeScript.getType(parameter), context); + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(parameter), context); } return null; @@ -42129,7 +43244,7 @@ var TypeScript; accessorSymbol.startResolving(); if (hasGetter) { - getterSymbol = this.resolveGetAccessorDeclaration(getterFunctionDeclarationAst, getterFunctionDeclarationAst.parameterList, TypeScript.getType(getterFunctionDeclarationAst), getterFunctionDeclarationAst.block, setterAnnotatedType, context); + getterSymbol = this.resolveGetAccessorDeclaration(getterFunctionDeclarationAst, getterFunctionDeclarationAst.parameterList, TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), getterFunctionDeclarationAst.block, setterAnnotatedType, context); } if (hasSetter) { @@ -42156,7 +43271,7 @@ var TypeScript; } } - if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol)) { + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { accessorSymbol.type = this.getNewErrorTypeSymbol(); } else { accessorSymbol.type = getterSuppliedTypeSymbol; @@ -42189,12 +43304,12 @@ var TypeScript; var getterSymbol = accessorSymbol.getGetter(); var setterSymbol = accessorSymbol.getSetter(); - var isGetter = funcDeclAst.kind() == 139 /* GetAccessor */; + var isGetter = funcDeclAst.kind() === 139 /* GetAccessor */; if (isGetter) { var getterFunctionDeclarationAst = funcDeclAst; - context.pushContextualType(getterSymbol.type, context.inProvisionalResolution(), null); + context.pushNewContextualType(getterSymbol.type); this.typeCheckGetAccessorDeclaration(getterFunctionDeclarationAst, context); - context.popContextualType(); + context.popAnyContextualType(); } else { var setterFunctionDeclarationAst = funcDeclAst; this.typeCheckSetAccessorDeclaration(setterFunctionDeclarationAst, context); @@ -42272,7 +43387,7 @@ var TypeScript; var setterSuppliedTypeSymbol = setterParameters[0].type; var getterSuppliedTypeSymbol = getterSig.returnType; - if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol)) { + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.get_and_set_accessor_must_have_the_same_type)); } } @@ -42283,7 +43398,7 @@ var TypeScript; var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); var accessorSymbol = funcDecl.getSymbol(); - this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.getType(funcDeclAST), context); + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); this.resolveAST(funcDeclAST.block, false, context); @@ -42291,10 +43406,10 @@ var TypeScript; var enclosingDecl = this.getEnclosingDecl(funcDecl); - var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) != 0; + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; var funcNameAST = funcDeclAST.propertyName; - if (!hasReturn && !(funcDeclAST.block.statements.childCount() > 0 && funcDeclAST.block.statements.childAt(0).kind() === 157 /* ThrowStatement */)) { + if (!hasReturn && !this.containsSingleThrowStatement(funcDeclAST.block)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getters_must_return_a_value)); } @@ -42304,18 +43419,18 @@ var TypeScript; var setterIsPrivate = TypeScript.hasFlag(setterDecl.flags, 2 /* Private */); var getterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); - if (getterIsPrivate != setterIsPrivate) { + if (getterIsPrivate !== setterIsPrivate) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); } this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); } - this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), TypeScript.getType(funcDeclAST), funcDeclAST.block, context); + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), TypeScript.ASTHelpers.getType(funcDeclAST), funcDeclAST.block, context); }; PullTypeResolver.hasSetAccessorParameterTypeAnnotation = function (setAccessor) { - return setAccessor.parameterList && setAccessor.parameterList.parameters.nonSeparatorCount() > 0 && setAccessor.parameterList.parameters.nonSeparatorAt(0).typeAnnotation != null; + return setAccessor.parameterList && setAccessor.parameterList.parameters.nonSeparatorCount() > 0 && setAccessor.parameterList.parameters.nonSeparatorAt(0).typeAnnotation !== null; }; PullTypeResolver.prototype.resolveSetAccessorDeclaration = function (funcDeclAST, parameterList, context) { @@ -42350,10 +43465,6 @@ var TypeScript; signature.returnType = this.semanticInfoChain.voidTypeSymbol; - if (signature.hasAGenericParameter) { - setterTypeSymbol.setHasGenericSignature(); - } - if (!hadError) { signature.setResolved(); } @@ -42376,7 +43487,7 @@ var TypeScript; this.validateVariableDeclarationGroups(funcDecl, context); - var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) != 0; + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; var getter = accessorSymbol.getGetter(); @@ -42387,7 +43498,7 @@ var TypeScript; var getterIsPrivate = TypeScript.hasFlag(getterDecl.flags, 2 /* Private */); var setterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); - if (getterIsPrivate != setterIsPrivate) { + if (getterIsPrivate !== setterIsPrivate) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); } @@ -42395,13 +43506,13 @@ var TypeScript; } else { if (this.compilationSettings.noImplicitAny()) { var setterFunctionDeclarationAst = funcDeclAST; - if (!PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterFunctionDeclarationAst) && accessorSymbol.type == this.semanticInfoChain.anyTypeSymbol) { + if (!PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterFunctionDeclarationAst) && accessorSymbol.type === this.semanticInfoChain.anyTypeSymbol) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type, [setterFunctionDeclarationAst.propertyName.text()])); } } } - this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); }; PullTypeResolver.prototype.resolveList = function (list, context) { @@ -42497,7 +43608,7 @@ var TypeScript; var nodeType = unaryExpression.kind(); var expression = this.resolveAST(unaryExpression.operand, false, context); - if (nodeType == 164 /* PlusExpression */ || nodeType == 165 /* NegateExpression */ || nodeType == 166 /* BitwiseNotExpression */) { + if (nodeType === 164 /* PlusExpression */ || nodeType == 165 /* NegateExpression */ || nodeType == 166 /* BitwiseNotExpression */) { return; } @@ -42632,14 +43743,14 @@ var TypeScript; var enclosingSymbol = this.getEnclosingSymbolForAST(binaryExpression); var isValidLHS = this.isAnyOrEquivalent(lhsType) || lhsType.isObject() || lhsType.isTypeParameter(); - var isValidRHS = this.isAnyOrEquivalent(rhsType) || this.typeIsSubtypeOfFunction(rhsType, binaryExpression, context); + var isValidRHS = this.isAnyOrEquivalent(rhsType) || this.typeIsAssignableToFunction(rhsType, binaryExpression, context); if (!isValidLHS) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); } if (!isValidRHS) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_a_subtype_of_the_Function_interface_type)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type)); } }; @@ -42650,8 +43761,6 @@ var TypeScript; this.resolveAST(commaExpression.left, false, context); } - var rhsType = this.resolveAST(commaExpression.right, false, context).type; - return this.resolveAST(commaExpression.right, false, context).type; }; @@ -42678,7 +43787,7 @@ var TypeScript; } if (!isValidRHS) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); } }; @@ -42707,29 +43816,27 @@ var TypeScript; PullTypeResolver.prototype.typeCheckForInStatement = function (forInStatement, context) { this.setTypeChecked(forInStatement, context); - var rhsType = this.resolveAST(forInStatement.expression, false, context).type; - var lval = forInStatement.variableDeclaration || forInStatement.left; - - var varSym = this.resolveAST(lval, false, context); - if (forInStatement.variableDeclaration) { var declaration = forInStatement.variableDeclaration; - var varDecl = declaration.declarators.nonSeparatorAt(0); - if (varDecl.typeAnnotation) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(lval, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation)); + if (declaration.declarators.nonSeparatorCount() === 1) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + if (varDecl.typeAnnotation) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declaration, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation)); + } } + } else { + var varSym = this.resolveAST(forInStatement.left, false, context); + var isStringOrNumber = varSym.type === this.semanticInfoChain.stringTypeSymbol || this.isAnyOrEquivalent(varSym.type); - var varSym = this.getSymbolForAST(varDecl, context); + if (!isStringOrNumber) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.left, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any)); + } } - var isStringOrNumber = varSym.type === this.semanticInfoChain.stringTypeSymbol || this.isAnyOrEquivalent(varSym.type); - - var isValidRHS = rhsType && (this.isAnyOrEquivalent(rhsType) || !rhsType.isPrimitive()); - - if (!isStringOrNumber) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(lval, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any)); - } + var rhsType = this.resolveAST(forInStatement.expression, false, context).type; + var isValidRHS = rhsType && (this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter()); if (!isValidRHS) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.expression, TypeScript.DiagnosticCode.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter)); @@ -42908,23 +44015,23 @@ var TypeScript; if (enclosingFunction) { var enclosingDeclAST = this.getASTForDecl(enclosingFunction); - var typeAnnotation = TypeScript.getType(enclosingDeclAST); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); if (typeAnnotation) { var returnTypeAnnotationSymbol = this.resolveTypeReference(typeAnnotation, context); if (returnTypeAnnotationSymbol) { isContextuallyTyped = true; - context.pushContextualType(returnTypeAnnotationSymbol, context.inProvisionalResolution(), null); + context.pushNewContextualType(returnTypeAnnotationSymbol); } } else { var currentContextualType = context.getContextualType(); if (currentContextualType && currentContextualType.isFunction()) { - var currentContextTypeDecls = currentContextualType.getDeclarations(); - var currentContextualTypeSignatureSymbol = currentContextTypeDecls && currentContextTypeDecls.length > 0 ? currentContextTypeDecls[0].getSignatureSymbol() : currentContextualType.getCallSignatures()[0]; + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; if (currentContextualTypeReturnTypeSymbol) { isContextuallyTyped = true; - context.pushContextualType(currentContextualTypeReturnTypeSymbol, context.inProvisionalResolution(), null); + context.propagateContextualType(currentContextualTypeReturnTypeSymbol); } } } @@ -42932,7 +44039,7 @@ var TypeScript; var result = this.resolveAST(expression, isContextuallyTyped, context).type; if (isContextuallyTyped) { - context.popContextualType(); + context.popAnyContextualType(); } return result; @@ -42959,7 +44066,7 @@ var TypeScript; if (enclosingFunction) { var enclosingDeclAST = this.getASTForDecl(enclosingFunction); - var typeAnnotation = TypeScript.getType(enclosingDeclAST); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); if (typeAnnotation || enclosingFunction.kind === 262144 /* GetAccessor */) { var signatureSymbol = enclosingFunction.getSignatureSymbol(); var sigReturnType = signatureSymbol.returnType; @@ -42968,22 +44075,6 @@ var TypeScript; var comparisonInfo = new TypeComparisonInfo(); var upperBound = null; - if (expressionType.isTypeParameter()) { - upperBound = expressionType.getConstraint(); - - if (upperBound) { - expressionType = upperBound; - } - } - - if (sigReturnType.isTypeParameter()) { - upperBound = sigReturnType.getConstraint(); - - if (upperBound) { - sigReturnType = upperBound; - } - } - this.resolveDeclaredSymbol(expressionType, context); this.resolveDeclaredSymbol(sigReturnType, context); @@ -43081,8 +44172,11 @@ var TypeScript; var breakableLabels = this.getEnclosingLabels(ast, true, false); - if (TypeScript.ArrayUtilities.contains(breakableLabels, labelIdentifier)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast.identifier, TypeScript.DiagnosticCode.Duplicate_identifier_0, [labelIdentifier])); + var matchingLabel = TypeScript.ArrayUtilities.firstOrDefault(breakableLabels, function (s) { + return s.identifier.valueText() === labelIdentifier; + }); + if (matchingLabel) { + context.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(ast.identifier, labelIdentifier, matchingLabel)); } this.resolveAST(ast.statement, false, context); @@ -43157,13 +44251,13 @@ var TypeScript; return false; }; - PullTypeResolver.prototype.inIterationStatement = function (ast) { + PullTypeResolver.prototype.inIterationStatement = function (ast, crossFunctions) { while (ast) { if (this.isIterationStatement(ast)) { return true; } - if (this.isAnyFunctionExpressionOrDeclaration(ast)) { + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { return false; } @@ -43181,10 +44275,10 @@ var TypeScript; if (ast.kind() === 160 /* LabeledStatement */) { var labeledStatement = ast; if (breakable) { - result.push(labeledStatement.identifier.valueText()); + result.push(labeledStatement); } else { if (this.labelIsOnContinuableConstruct(labeledStatement.statement)) { - result.push(labeledStatement.identifier.valueText()); + result.push(labeledStatement); } } } @@ -43202,15 +44296,23 @@ var TypeScript; PullTypeResolver.prototype.typeCheckContinueStatement = function (ast, context) { this.setTypeChecked(ast, context); - if (!this.inIterationStatement(ast)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.continue_statement_can_only_be_used_within_an_enclosing_iteration_statement)); + if (!this.inIterationStatement(ast, false)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.continue_statement_can_only_be_used_within_an_enclosing_iteration_statement)); + } } else if (ast.identifier) { var continuableLabels = this.getEnclosingLabels(ast, false, false); - if (!TypeScript.ArrayUtilities.contains(continuableLabels, ast.identifier.valueText())) { + if (!TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { var continuableLabels = this.getEnclosingLabels(ast, false, true); - if (TypeScript.ArrayUtilities.contains(continuableLabels, ast.identifier.valueText())) { + if (TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); } else { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); @@ -43233,16 +44335,24 @@ var TypeScript; if (ast.identifier) { var breakableLabels = this.getEnclosingLabels(ast, true, false); - if (!TypeScript.ArrayUtilities.contains(breakableLabels, ast.identifier.valueText())) { + if (!TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { var breakableLabels = this.getEnclosingLabels(ast, true, true); - if (TypeScript.ArrayUtilities.contains(breakableLabels, ast.identifier.valueText())) { + if (TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); } else { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); } } - } else if (!this.inIterationStatement(ast) && !this.inSwitchStatement(ast)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement)); + } else if (!this.inIterationStatement(ast, false) && !this.inSwitchStatement(ast)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement)); + } } }; @@ -43257,6 +44367,10 @@ var TypeScript; return symbol; } + if (ast.isExpression() && !isTypesOnlyLocation(ast)) { + return this.resolveExpressionAST(ast, isContextuallyTyped, context); + } + var nodeType = ast.kind(); switch (nodeType) { @@ -43322,9 +44436,6 @@ var TypeScript; case 133 /* ImportDeclaration */: return this.resolveImportDeclaration(ast, context); - case 215 /* ObjectLiteralExpression */: - return this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); - case 240 /* SimplePropertyAssignment */: return this.resolveSimplePropertyAssignment(ast, isContextuallyTyped, context); @@ -43332,14 +44443,8 @@ var TypeScript; return this.resolveFunctionPropertyAssignment(ast, isContextuallyTyped, context); case 11 /* IdentifierName */: - if (isTypesOnlyLocation(ast)) { - return this.resolveTypeNameExpression(ast, context); - } else { - return this.resolveNameExpression(ast, context); - } - - case 212 /* MemberAccessExpression */: - return this.resolveMemberAccessExpression(ast, context); + TypeScript.Debug.assert(isTypesOnlyLocation(ast)); + return this.resolveTypeNameExpression(ast, context); case 121 /* QualifiedName */: return this.resolveQualifiedName(ast, context); @@ -43372,6 +44477,94 @@ var TypeScript; case 129 /* FunctionDeclaration */: return this.resolveAnyFunctionDeclaration(ast, context); + case 244 /* TypeAnnotation */: + return this.resolveTypeAnnotation(ast, context); + + case 134 /* ExportAssignment */: + return this.resolveExportAssignmentStatement(ast, context); + + case 157 /* ThrowStatement */: + return this.resolveThrowStatement(ast, context); + + case 149 /* ExpressionStatement */: + return this.resolveExpressionStatement(ast, context); + + case 154 /* ForStatement */: + return this.resolveForStatement(ast, context); + + case 155 /* ForInStatement */: + return this.resolveForInStatement(ast, context); + + case 158 /* WhileStatement */: + return this.resolveWhileStatement(ast, context); + + case 161 /* DoStatement */: + return this.resolveDoStatement(ast, context); + + case 147 /* IfStatement */: + return this.resolveIfStatement(ast, context); + + case 235 /* ElseClause */: + return this.resolveElseClause(ast, context); + + case 146 /* Block */: + return this.resolveBlock(ast, context); + + case 148 /* VariableStatement */: + return this.resolveVariableStatement(ast, context); + + case 163 /* WithStatement */: + return this.resolveWithStatement(ast, context); + + case 159 /* TryStatement */: + return this.resolveTryStatement(ast, context); + + case 236 /* CatchClause */: + return this.resolveCatchClause(ast, context); + + case 237 /* FinallyClause */: + return this.resolveFinallyClause(ast, context); + + case 150 /* ReturnStatement */: + return this.resolveReturnStatement(ast, context); + + case 151 /* SwitchStatement */: + return this.resolveSwitchStatement(ast, context); + + case 153 /* ContinueStatement */: + return this.resolveContinueStatement(ast, context); + + case 152 /* BreakStatement */: + return this.resolveBreakStatement(ast, context); + + case 160 /* LabeledStatement */: + return this.resolveLabeledStatement(ast, context); + } + + return this.semanticInfoChain.anyTypeSymbol; + }; + + PullTypeResolver.prototype.resolveExpressionAST = function (ast, isContextuallyOrInferentiallyTyped, context) { + var expressionSymbol = this.resolveExpressionWorker(ast, isContextuallyOrInferentiallyTyped, context); + + if (isContextuallyOrInferentiallyTyped && context.isInferentiallyTyping()) { + return this.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference(expressionSymbol, context); + } else { + return expressionSymbol; + } + }; + + PullTypeResolver.prototype.resolveExpressionWorker = function (ast, isContextuallyTyped, context) { + switch (ast.kind()) { + case 215 /* ObjectLiteralExpression */: + return this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + return this.resolveNameExpression(ast, context); + + case 212 /* MemberAccessExpression */: + return this.resolveMemberAccessExpression(ast, context); + case 222 /* FunctionExpression */: return this.resolveFunctionExpression(ast, isContextuallyTyped, context); @@ -43399,12 +44592,6 @@ var TypeScript; case 220 /* CastExpression */: return this.resolveCastExpression(ast, context); - case 244 /* TypeAnnotation */: - return this.resolveTypeAnnotation(ast, context); - - case 134 /* ExportAssignment */: - return this.resolveExportAssignmentStatement(ast, context); - case 13 /* NumericLiteral */: return this.semanticInfoChain.numberTypeSymbol; @@ -43486,9 +44673,6 @@ var TypeScript; case 171 /* TypeOfExpression */: return this.resolveTypeOfExpression(ast, context); - case 157 /* ThrowStatement */: - return this.resolveThrowStatement(ast, context); - case 170 /* DeleteExpression */: return this.resolveDeleteExpression(ast, context); @@ -43501,9 +44685,6 @@ var TypeScript; case 217 /* ParenthesizedExpression */: return this.resolveParenthesizedExpression(ast, context); - case 149 /* ExpressionStatement */: - return this.resolveExpressionStatement(ast, context); - case 200 /* InstanceOfExpression */: return this.resolveInstanceOfExpression(ast, context); @@ -43513,59 +44694,11 @@ var TypeScript; case 201 /* InExpression */: return this.resolveInExpression(ast, context); - case 154 /* ForStatement */: - return this.resolveForStatement(ast, context); - - case 155 /* ForInStatement */: - return this.resolveForInStatement(ast, context); - - case 158 /* WhileStatement */: - return this.resolveWhileStatement(ast, context); - - case 161 /* DoStatement */: - return this.resolveDoStatement(ast, context); - - case 147 /* IfStatement */: - return this.resolveIfStatement(ast, context); - - case 235 /* ElseClause */: - return this.resolveElseClause(ast, context); - - case 146 /* Block */: - return this.resolveBlock(ast, context); - - case 148 /* VariableStatement */: - return this.resolveVariableStatement(ast, context); - - case 163 /* WithStatement */: - return this.resolveWithStatement(ast, context); - - case 159 /* TryStatement */: - return this.resolveTryStatement(ast, context); - - case 236 /* CatchClause */: - return this.resolveCatchClause(ast, context); - - case 237 /* FinallyClause */: - return this.resolveFinallyClause(ast, context); - - case 150 /* ReturnStatement */: - return this.resolveReturnStatement(ast, context); - - case 151 /* SwitchStatement */: - return this.resolveSwitchStatement(ast, context); - - case 153 /* ContinueStatement */: - return this.resolveContinueStatement(ast, context); - - case 152 /* BreakStatement */: - return this.resolveBreakStatement(ast, context); - - case 160 /* LabeledStatement */: - return this.resolveLabeledStatement(ast, context); + case 223 /* OmittedExpression */: + return this.semanticInfoChain.undefinedTypeSymbol; } - return this.semanticInfoChain.anyTypeSymbol; + TypeScript.Debug.fail("resolveExpressionASTWorker: Missing expression kind: " + TypeScript.SyntaxKind[ast.kind()]); }; PullTypeResolver.prototype.typeCheckAST = function (ast, isContextuallyTyped, context) { @@ -43644,8 +44777,25 @@ var TypeScript; return; case 222 /* FunctionExpression */: - this.typeCheckFunctionExpression(ast, context); - break; + this.typeCheckFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 137 /* ConstructorDeclaration */: + this.typeCheckConstructorDeclaration(ast, context); + return; + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + this.typeCheckAccessorDeclaration(ast, context); + return; + + case 135 /* MemberFunctionDeclaration */: + this.typeCheckMemberFunctionDeclaration(ast, context); + return; + + case 145 /* MethodSignature */: + this.typeCheckMethodSignature(ast, context); + return; case 144 /* IndexSignature */: this.typeCheckIndexSignature(ast, context); @@ -43653,24 +44803,24 @@ var TypeScript; case 142 /* CallSignature */: this.typeCheckCallSignature(ast, context); - break; + return; case 143 /* ConstructSignature */: this.typeCheckConstructSignature(ast, context); - break; + return; case 129 /* FunctionDeclaration */: { var funcDecl = ast; - this.typeCheckFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.getType(funcDecl), funcDecl.block, context); + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); return; } case 219 /* SimpleArrowFunctionExpression */: - this.typeCheckSimpleArrowFunctionExpression(ast, context); + this.typeCheckSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); return; case 218 /* ParenthesizedArrowFunctionExpression */: - this.typeCheckParenthesizedArrowFunctionExpression(ast, context); + this.typeCheckParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); return; case 214 /* ArrayLiteralExpression */: @@ -43758,36 +44908,112 @@ var TypeScript; PullTypeResolver.prototype.resolveNameExpression = function (nameAST, context) { var nameSymbol = this.getSymbolForAST(nameAST, context); - var foundCached = nameSymbol != null; + var foundCached = nameSymbol !== null; if (!foundCached || this.canTypeCheckAST(nameAST, context)) { if (this.canTypeCheckAST(nameAST, context)) { this.typeCheckNameExpression(nameAST, context); } - nameSymbol = this.computeNameExpression(nameAST, context, true); + nameSymbol = this.computeNameExpression(nameAST, context); } this.resolveDeclaredSymbol(nameSymbol, context); - if (nameSymbol && (nameSymbol.type != this.semanticInfoChain.anyTypeSymbol || nameSymbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + if (nameSymbol && (nameSymbol.type !== this.semanticInfoChain.anyTypeSymbol || nameSymbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { this.setSymbolForAST(nameAST, nameSymbol, context); } return nameSymbol; }; - PullTypeResolver.prototype.isSomeFunctionScope = function (declPath) { - for (var i = declPath.length - 1; i >= 0; i--) { - var decl = declPath[i]; - if (decl.kind & 1032192 /* SomeFunction */) { - return true; - } + PullTypeResolver.prototype.isInEnumDecl = function (decl) { + if (decl.kind & 64 /* Enum */) { + return true; } + var declPath = decl.getParentPath(); + + var disallowedKinds = 164 /* SomeContainer */ | 58728795 /* SomeType */; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + + if (decl.kind & 64 /* Enum */) { + return true; + } + + if (decl.kind & disallowedKinds) { + return false; + } + } return false; }; - PullTypeResolver.prototype.computeNameExpression = function (nameAST, context, reportDiagnostics) { + PullTypeResolver.prototype.getSomeInnermostFunctionScopeDecl = function (declPath) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (decl.kind & 1032192 /* SomeFunction */) { + return decl; + } + } + + return null; + }; + + PullTypeResolver.prototype.isFromFunctionScope = function (nameSymbol, functionScopeDecl) { + var _this = this; + return TypeScript.ArrayUtilities.any(nameSymbol.getDeclarations(), function (nameSymbolDecl) { + return _this.getSomeInnermostFunctionScopeDecl(nameSymbolDecl.getParentPath()) === functionScopeDecl; + }); + }; + + PullTypeResolver.prototype.findConstructorDeclOfEnclosingType = function (decl) { + var current = decl; + while (current) { + if (TypeScript.hasFlag(current.kind, 4096 /* Property */)) { + var parentDecl = current.getParentDecl(); + if (TypeScript.hasFlag(parentDecl.kind, 8 /* Class */)) { + return TypeScript.ArrayUtilities.lastOrDefault(parentDecl.getChildDecls(), function (decl) { + return TypeScript.hasFlag(decl.kind, 32768 /* ConstructorMethod */); + }); + } + } + + if (TypeScript.hasFlag(current.kind, 164 /* SomeContainer */)) { + return null; + } + + current = current.getParentDecl(); + } + return null; + }; + + PullTypeResolver.prototype.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable = function (nameAST) { + var id = nameAST.valueText(); + if (id.length === 0) { + return null; + } + + var memberVariableDeclarationAST = TypeScript.ASTHelpers.getEnclosingMemberVariableDeclaration(nameAST); + if (memberVariableDeclarationAST) { + var memberVariableDecl = this.semanticInfoChain.getDeclForAST(memberVariableDeclarationAST); + if (!TypeScript.hasFlag(memberVariableDecl.flags, 16 /* Static */)) { + var constructorDecl = this.findConstructorDeclOfEnclosingType(memberVariableDecl); + + if (constructorDecl) { + var childDecls = constructorDecl.searchChildDecls(id, 68147712 /* SomeValue */); + + if (childDecls.length) { + var memberVariableSymbol = memberVariableDecl.getSymbol(); + + return this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, [memberVariableSymbol.getScopedName(constructorDecl.getSymbol()), nameAST.text()]); + } + } + } + } + return null; + }; + + PullTypeResolver.prototype.computeNameExpression = function (nameAST, context) { var id = nameAST.valueText(); if (id.length === 0) { return this.semanticInfoChain.anyTypeSymbol; @@ -43796,37 +45022,47 @@ var TypeScript; var nameSymbol = null; var enclosingDecl = this.getEnclosingDeclForAST(nameAST); - if (TypeScript.isDeclarationASTOrDeclarationNameAST(nameAST)) { + if (TypeScript.hasFlag(enclosingDecl.flags, 8388608 /* PropertyParameter */)) { + var valueDecl = enclosingDecl.getValueDecl(); + if (valueDecl && TypeScript.hasFlag(valueDecl.kind, 2048 /* Parameter */)) { + enclosingDecl = valueDecl; + } + } + + var diagnosticForInitializer = this.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable(nameAST); + + if (TypeScript.ASTHelpers.isDeclarationASTOrDeclarationNameAST(nameAST)) { nameSymbol = this.semanticInfoChain.getDeclForAST(nameAST.parent).getSymbol(); } var declPath = enclosingDecl.getParentPath(); if (!nameSymbol) { - var nameSymbol = this.getSymbolFromDeclPath(id, declPath, 68147712 /* SomeValue */); + var searchKind = 68147712 /* SomeValue */; + + if (!this.isInEnumDecl(enclosingDecl)) { + searchKind = searchKind & ~(67108864 /* EnumMember */); + } + + var nameSymbol = this.getSymbolFromDeclPath(id, declPath, searchKind); } - if (!nameSymbol && id === "arguments" && this.isSomeFunctionScope(declPath)) { - nameSymbol = this.cachedFunctionArgumentsSymbol(); - - this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), context); - } - - if (!nameSymbol) { - nameSymbol = this.getSymbolFromDeclPath(id, declPath, 128 /* TypeAlias */); - - if (nameSymbol && !nameSymbol.isAlias()) { - nameSymbol = null; + if (id === "arguments") { + var functionScopeDecl = this.getSomeInnermostFunctionScopeDecl(declPath); + if (functionScopeDecl) { + if (!nameSymbol || !this.isFromFunctionScope(nameSymbol, functionScopeDecl)) { + nameSymbol = this.cachedFunctionArgumentsSymbol(); + this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), context); + } } } if (!nameSymbol) { - if (!reportDiagnostics) { - return null; - } else { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); - return this.getNewErrorTypeSymbol(id); - } + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (diagnosticForInitializer) { + context.postDiagnostic(diagnosticForInitializer); + return this.getNewErrorTypeSymbol(id); } var nameDeclaration = nameSymbol.getDeclarations()[0]; @@ -43835,22 +45071,26 @@ var TypeScript; var enclosingFunctionAST = this.semanticInfoChain.getASTForDecl(nameParentDecl); var currentParameterIndex = this.getCurrentParameterIndexForFunction(nameAST, enclosingFunctionAST); - var parameterList = TypeScript.getParameterList(enclosingFunctionAST); + var parameterList = TypeScript.ASTHelpers.getParameterList(enclosingFunctionAST); if (currentParameterIndex >= 0) { - var foundMatchingParameter = false; + var matchingParameter; if (parameterList) { for (var i = 0; i <= currentParameterIndex; i++) { var candidateParameter = parameterList.parameters.nonSeparatorAt(i); if (candidateParameter && candidateParameter.identifier.valueText() === id) { - foundMatchingParameter = true; + matchingParameter = candidateParameter; + break; } } } - if (!foundMatchingParameter) { + if (!matchingParameter) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text(), nameAST.text()])); return this.getNewErrorTypeSymbol(id); + } else if (matchingParameter === TypeScript.ASTHelpers.getEnclosingParameterForInitializer(nameAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Parameter_0_cannot_be_referenced_in_its_initializer, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text()])); + return this.getNewErrorTypeSymbol(id); } } } @@ -43860,7 +45100,7 @@ var TypeScript; if (nameSymbol.isType() && nameSymbol.isAlias()) { aliasSymbol = nameSymbol; if (!this.inTypeQuery(nameAST)) { - aliasSymbol.setIsUsedAsValue(true); + aliasSymbol.setIsUsedAsValue(); } this.resolveDeclaredSymbol(nameSymbol, context); @@ -43885,7 +45125,7 @@ var TypeScript; }; PullTypeResolver.prototype.getCurrentParameterIndexForFunction = function (parameter, funcDecl) { - var parameterList = TypeScript.getParameterList(funcDecl); + var parameterList = TypeScript.ASTHelpers.getParameterList(funcDecl); if (parameterList) { while (parameter && parameter.parent) { if (parameter.parent.parent === parameterList) { @@ -43905,7 +45145,7 @@ var TypeScript; PullTypeResolver.prototype.resolveDottedNameExpression = function (dottedNameAST, expression, name, context) { var symbol = this.getSymbolForAST(dottedNameAST, context); - var foundCached = symbol != null; + var foundCached = symbol !== null; if (!foundCached || this.canTypeCheckAST(dottedNameAST, context)) { var canTypeCheckDottedNameAST = this.canTypeCheckAST(dottedNameAST, context); @@ -43918,7 +45158,7 @@ var TypeScript; this.resolveDeclaredSymbol(symbol, context); - if (symbol && (symbol.type != this.semanticInfoChain.anyTypeSymbol || symbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + if (symbol && (symbol.type !== this.semanticInfoChain.anyTypeSymbol || symbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { this.setSymbolForAST(dottedNameAST, symbol, context); this.setSymbolForAST(name, symbol, context); } @@ -43933,17 +45173,23 @@ var TypeScript; } var lhs = this.resolveAST(expression, false, context); + return this.computeDottedNameExpressionFromLHS(lhs, expression, name, context, checkSuperPrivateAndStaticAccess); + }; + + PullTypeResolver.prototype.computeDottedNameExpressionFromLHS = function (lhs, expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + var lhsType = lhs.type; if (lhs.isAlias()) { + var lhsAlias = lhs; if (!this.inTypeQuery(expression)) { - lhs.setIsUsedAsValue(true); + lhsAlias.setIsUsedAsValue(); } - lhsType = lhs.getExportAssignedTypeSymbol(); - } - - if (this.isAnyOrEquivalent(lhsType)) { - return lhsType; + lhsType = lhsAlias.getExportAssignedTypeSymbol(); } if (lhsType.isAlias()) { @@ -43958,7 +45204,7 @@ var TypeScript; if (!lhsType.isResolved) { var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); - if (potentiallySpecializedType != lhsType) { + if (potentiallySpecializedType !== lhsType) { if (!lhs.isType()) { context.setTypeInContext(lhs, potentiallySpecializedType); } @@ -43975,47 +45221,37 @@ var TypeScript; } } - if (lhsType.isTypeParameter()) { - lhsType = this.substituteUpperBoundForType(lhsType); + var originalLhsTypeForErrorReporting = lhsType; + + lhsType = this.getApparentType(lhsType).widenedType(this, expression, context); + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; } - if ((lhsType === this.semanticInfoChain.numberTypeSymbol || lhsType.isEnum()) && this.cachedNumberInterfaceType()) { - lhsType = this.cachedNumberInterfaceType(); - } else if (lhsType === this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { - lhsType = this.cachedStringInterfaceType(); - } else if (lhsType === this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { - lhsType = this.cachedBooleanInterfaceType(); - } - - var nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, lhsType); + var nameSymbol = this._getNamedPropertySymbolOfAugmentedType(rhsName, lhsType); if (!nameSymbol) { - if ((lhsType.getCallSignatures().length || lhsType.getConstructSignatures().length) && this.cachedFunctionInterfaceType()) { - nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, this.cachedFunctionInterfaceType()); - } else if (lhsType.kind === 32 /* DynamicModule */) { + if (lhsType.kind === 32 /* DynamicModule */) { var container = lhsType; var associatedInstance = container.getInstanceSymbol(); if (associatedInstance) { var instanceType = associatedInstance.type; - nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, instanceType); + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, instanceType); } } else { var associatedType = lhsType.getAssociatedContainerType(); if (associatedType && !associatedType.isClass()) { - nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, associatedType); + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, associatedType); } } - if (!nameSymbol && !lhsType.isPrimitive() && this.cachedObjectInterfaceType()) { - nameSymbol = this.getMemberSymbol(rhsName, 68147712 /* SomeValue */, this.cachedObjectInterfaceType()); - } - if (!nameSymbol) { var enclosingDecl = this.getEnclosingDeclForAST(expression); - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [name.text(), lhsType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [name.text(), originalLhsTypeForErrorReporting.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); return this.getNewErrorTypeSymbol(rhsName); } } @@ -44055,8 +45291,8 @@ var TypeScript; var onLeftOfDot = this.isLeftSideOfQualifiedName(nameAST); - var kindToCheckFirst = onLeftOfDot ? 164 /* SomeContainer */ : 58728539 /* SomeType */; - var kindToCheckSecond = onLeftOfDot ? 58728539 /* SomeType */ : 164 /* SomeContainer */; + var kindToCheckFirst = onLeftOfDot ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + var kindToCheckSecond = onLeftOfDot ? 58728795 /* SomeType */ : 164 /* SomeContainer */; var typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckFirst); @@ -44080,11 +45316,11 @@ var TypeScript; } if (typeNameSymbol.isTypeParameter()) { - if (enclosingDecl && (enclosingDecl.kind & 1032192 /* SomeFunction */) && (enclosingDecl.flags & 16 /* Static */)) { + if (this.isInStaticMemberContext(enclosingDecl)) { var parentDecl = typeNameSymbol.getDeclarations()[0].getParentDecl(); - if (parentDecl.kind == 8 /* Class */) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Static_methods_cannot_reference_class_type_parameters)); + if (parentDecl.kind === 8 /* Class */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Static_members_cannot_reference_class_type_parameters)); return this.getNewErrorTypeSymbol(); } } @@ -44097,6 +45333,22 @@ var TypeScript; return typeNameSymbol; }; + PullTypeResolver.prototype.isInStaticMemberContext = function (decl) { + while (decl) { + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */ | 4096 /* Property */) && TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + return true; + } + + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + return false; + } + + decl = decl.getParentDecl(); + } + + return false; + }; + PullTypeResolver.prototype.isLeftSideOfQualifiedName = function (ast) { return ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.left === ast; }; @@ -44113,9 +45365,18 @@ var TypeScript; } if (genericTypeSymbol.isAlias()) { + if (this.inClassExtendsHeritageClause(genericTypeAST) && !this.inTypeArgumentList(genericTypeAST)) { + genericTypeSymbol.setIsUsedAsValue(); + } genericTypeSymbol = genericTypeSymbol.getExportAssignedTypeSymbol(); } + var typeParameters = genericTypeSymbol.getTypeParameters(); + if (typeParameters.length === 0) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_have_type_parameters, [genericTypeSymbol.toString()])); + return this.getNewErrorTypeSymbol(); + } + var typeArgs = []; if (genericTypeAST.typeArgumentList && genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount()) { @@ -44128,9 +45389,7 @@ var TypeScript; } } - var typeParameters = genericTypeSymbol.getTypeParameters(); - - if (typeArgs.length && typeArgs.length != typeParameters.length) { + if (typeArgs.length && typeArgs.length !== typeParameters.length) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Generic_type_0_requires_1_type_argument_s, [genericTypeSymbol.toString(), genericTypeSymbol.getTypeParameters().length])); return this.getNewErrorTypeSymbol(); } @@ -44177,7 +45436,7 @@ var TypeScript; if (typeConstraint) { if (typeConstraint.isTypeParameter()) { for (var j = 0; j < typeParameters.length && j < typeArgs.length; j++) { - if (typeParameters[j] == typeConstraint) { + if (typeParameters[j] === typeConstraint) { typeConstraint = typeArgs[j]; } } @@ -44196,6 +45455,7 @@ var TypeScript; if (typeArg.inResolution || (typeArg.isTypeReference() && typeArg.referencedTypeSymbol.inResolution)) { return specializedSymbol; } + if (!this.sourceIsAssignableToTarget(typeArg, typeConstraint, genericTypeAST, context)) { var enclosingSymbol = this.getEnclosingSymbolForAST(genericTypeAST); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [typeArg.toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[iArg].toString(enclosingSymbol, true)])); @@ -44227,6 +45487,10 @@ var TypeScript; return symbol; }; + PullTypeResolver.prototype.isLastNameOfModuleNameModuleReference = function (ast) { + return ast.kind() === 11 /* IdentifierName */ && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast && ast.parent.parent && ast.parent.parent.kind() === 246 /* ModuleNameModuleReference */; + }; + PullTypeResolver.prototype.computeQualifiedName = function (dottedNameAST, context) { var rhsName = dottedNameAST.right.valueText(); if (rhsName.length === 0) { @@ -44240,7 +45504,7 @@ var TypeScript; if (this.inClassExtendsHeritageClause(dottedNameAST) && !this.inTypeArgumentList(dottedNameAST)) { if (lhs.isAlias()) { - lhs.setIsUsedAsValue(true); + lhs.setIsUsedAsValue(); } } @@ -44254,15 +45518,20 @@ var TypeScript; var onLeftOfDot = this.isLeftSideOfQualifiedName(dottedNameAST); var isNameOfModule = dottedNameAST.parent.kind() === 130 /* ModuleDeclaration */ && dottedNameAST.parent.name === dottedNameAST; - var memberKind = (onLeftOfDot || isNameOfModule) ? 164 /* SomeContainer */ : 58728539 /* SomeType */; - var childTypeSymbol = this.getMemberSymbol(rhsName, memberKind, lhsType); + var memberKind = (onLeftOfDot || isNameOfModule) ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + + var childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + + if (!childTypeSymbol && !isNameOfModule && this.isLastNameOfModuleNameModuleReference(dottedNameAST.right)) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, lhsType); + } if (!childTypeSymbol && lhsType.isContainer()) { var exportedContainer = lhsType.getExportAssignedContainerSymbol(); if (exportedContainer) { - childTypeSymbol = this.getMemberSymbol(rhsName, memberKind, exportedContainer); + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, exportedContainer); } } @@ -44281,7 +45550,7 @@ var TypeScript; var enclosingSymbolType = parentDecl.getSymbol().type; if (enclosingSymbolType === lhsType) { - childTypeSymbol = this.getMemberSymbol(rhsName, memberKind, lhsType); + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); } } } @@ -44316,12 +45585,12 @@ var TypeScript; if (contextualFunctionTypeSymbol) { this.resolveDeclaredSymbol(contextualFunctionTypeSymbol, context); var callSignatures = contextualFunctionTypeSymbol.getCallSignatures(); - var exactlyOneCallSignature = callSignatures && callSignatures.length == 1; + var exactlyOneCallSignature = callSignatures && callSignatures.length === 1; if (!exactlyOneCallSignature) { return false; } - var callSignatureIsGeneric = callSignatures[0].typeParameters && callSignatures[0].typeParameters.length > 0; + var callSignatureIsGeneric = callSignatures[0].getTypeParameters().length > 0; return !callSignatureIsGeneric; } @@ -44358,36 +45627,7 @@ var TypeScript; assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; } - if (parameters) { - var contextParams = []; - - if (assigningFunctionSignature) { - contextParams = assigningFunctionSignature.parameters; - } - - var contextualParametersCount = contextParams.length; - for (var i = 0, n = parameters.length; i < n; i++) { - var actualParameterIsVarArgParameter = (i === (n - 1)) && parameters.lastParameterIsRest(); - var correspondingContextualParameter = null; - var contextualParameterType = null; - - if (i < contextualParametersCount) { - correspondingContextualParameter = contextParams[i]; - } else if (contextualParametersCount && contextParams[contextualParametersCount - 1].isVarArg) { - correspondingContextualParameter = contextParams[contextualParametersCount - 1]; - } - - if (correspondingContextualParameter) { - if (correspondingContextualParameter.isVarArg === actualParameterIsVarArgParameter) { - contextualParameterType = correspondingContextualParameter.type; - } else if (correspondingContextualParameter.isVarArg) { - contextualParameterType = correspondingContextualParameter.type.getElementType(); - } - } - - this.resolveFunctionExpressionParameter(parameters.astAt(i), parameters.identifierAt(i), parameters.typeAt(i), parameters.initializerAt(i), contextualParameterType, functionDecl, context); - } - } + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); if (returnTypeAnnotation) { signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); @@ -44396,10 +45636,9 @@ var TypeScript; var returnType = assigningFunctionSignature.returnType; if (returnType) { - context.pushContextualType(returnType, context.inProvisionalResolution(), null); - + context.propagateContextualType(returnType); this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, true, functionDecl, context); - context.popContextualType(); + context.popAnyContextualType(); } else { signature.returnType = this.semanticInfoChain.anyTypeSymbol; @@ -44422,21 +45661,63 @@ var TypeScript; funcDeclSymbol.setResolved(); if (this.canTypeCheckAST(funcDeclAST, context)) { - this.typeCheckAnyFunctionExpression(funcDeclAST, typeParameters, returnTypeAnnotation, block, bodyExpression, context); + this.typeCheckAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context); } return funcDeclSymbol; }; - PullTypeResolver.prototype.typeCheckSimpleArrowFunctionExpression = function (arrowFunction, context) { - return this.typeCheckAnyFunctionExpression(arrowFunction, null, null, arrowFunction.block, arrowFunction.expression, context); + PullTypeResolver.prototype.resolveAnyFunctionExpressionParameters = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context) { + if (!parameters) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var contextParams = []; + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + if (assigningFunctionSignature) { + contextParams = assigningFunctionSignature.parameters; + } + + var contextualParametersCount = contextParams.length; + for (var i = 0, n = parameters.length; i < n; i++) { + var actualParameterIsVarArgParameter = (i === (n - 1)) && parameters.lastParameterIsRest(); + var correspondingContextualParameter = null; + var contextualParameterType = null; + + if (i < contextualParametersCount) { + correspondingContextualParameter = contextParams[i]; + } else if (contextualParametersCount && contextParams[contextualParametersCount - 1].isVarArg) { + correspondingContextualParameter = contextParams[contextualParametersCount - 1]; + } + + if (correspondingContextualParameter) { + if (correspondingContextualParameter.isVarArg === actualParameterIsVarArgParameter) { + contextualParameterType = correspondingContextualParameter.type; + } else if (correspondingContextualParameter.isVarArg) { + contextualParameterType = correspondingContextualParameter.type.getElementType(); + } + } + + this.resolveFunctionExpressionParameter(parameters.astAt(i), parameters.identifierAt(i), parameters.typeAt(i), parameters.initializerAt(i), contextualParameterType, functionDecl, context); + } }; - PullTypeResolver.prototype.typeCheckParenthesizedArrowFunctionExpression = function (arrowFunction, context) { - return this.typeCheckAnyFunctionExpression(arrowFunction, arrowFunction.callSignature.typeParameterList, TypeScript.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, context); + PullTypeResolver.prototype.typeCheckSimpleArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), null, arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); }; - PullTypeResolver.prototype.typeCheckAnyFunctionExpression = function (funcDeclAST, typeParameters, returnTypeAnnotation, block, bodyExpression, context) { + PullTypeResolver.prototype.typeCheckParenthesizedArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { var _this = this; this.setTypeChecked(funcDeclAST, context); @@ -44453,27 +45734,19 @@ var TypeScript; } } - context.pushContextualType(null, context.inProvisionalResolution(), null); + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + context.pushNewContextualType(null); if (block) { this.resolveAST(block, false, context); } else { var bodyExpressionType = this.resolveReturnExpression(bodyExpression, functionDecl, context); this.typeCheckReturnExpression(bodyExpression, bodyExpressionType, functionDecl, context); } - context.popContextualType(); - var hasReturn = (functionDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) != 0; + context.popAnyContextualType(); - if (block && returnTypeAnnotation != null && !hasReturn) { - var isVoidOrAny = this.isAnyOrEquivalent(returnTypeSymbol) || returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol; - - if (!isVoidOrAny && !(block.statements.childCount() > 0 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */)) { - var funcName = functionDecl.getDisplayName(); - funcName = funcName ? "'" + funcName + "'" : "expression"; - - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_0_declared_a_non_void_return_type_but_has_no_return_expression, [funcName])); - } - } + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context); this.validateVariableDeclarationGroups(functionDecl, context); @@ -44587,9 +45860,11 @@ var TypeScript; var current = ast; while (current) { switch (current.kind()) { - case 137 /* ConstructorDeclaration */: - var constructorDecl = current; - return previous === constructorDecl.parameterList; + case 142 /* CallSignature */: + var callSignature = current; + if (previous === callSignature.parameterList && callSignature.parent.kind() === 137 /* ConstructorDeclaration */) { + return true; + } case 131 /* ClassDeclaration */: case 130 /* ModuleDeclaration */: @@ -44602,6 +45877,13 @@ var TypeScript; return false; }; + PullTypeResolver.prototype.isFunctionAccessorOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 262144 /* GetAccessor */ || decl.kind === 524288 /* SetAccessor */) { + return true; + } + + return this.isFunctionOrNonArrowFunctionExpression(decl); + }; PullTypeResolver.prototype.isFunctionOrNonArrowFunctionExpression = function (decl) { if (decl.kind === 16384 /* Function */) { @@ -44622,7 +45904,7 @@ var TypeScript; } for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { - if (this.isFunctionOrNonArrowFunctionExpression(currentDecl)) { + if (this.isFunctionAccessorOrNonArrowFunctionExpression(currentDecl)) { return; } else if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { if (currentDecl.getParentDecl() === null) { @@ -44631,6 +45913,9 @@ var TypeScript; context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_within_module_bodies)); return; } + } else if (currentDecl.kind === 64 /* Enum */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + return; } else if (currentDecl.kind === 32768 /* ConstructorMethod */) { if (this.inArgumentListOfSuperInvocation(thisExpression) && this.superCallMustBeFirstStatementInConstructor(currentDecl)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); @@ -44745,29 +46030,22 @@ var TypeScript; return; } } - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class)); return; } else { - for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { - if (this.isFunctionOrNonArrowFunctionExpression(currentDecl)) { - break; - } else if (currentDecl.kind === 32768 /* ConstructorMethod */) { - var classDecl = currentDecl.getParentDecl(); - - if (!this.enclosingClassIsDerived(classDecl)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); - return; - } else if (this.inConstructorParameterList(ast)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); - return; - } + if (enclosingDecl.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingDecl.getParentDecl(); + if (!this.enclosingClassIsDerived(classDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); return; } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors)); } - - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Super_calls_are_not_permitted_outside_constructors_or_in_local_functions_inside_constructors)); } }; @@ -44776,17 +46054,18 @@ var TypeScript; }; PullTypeResolver.prototype.resolveFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { - return this.resolveAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(funcProp.callSignature.parameterList), TypeScript.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + return this.resolveAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); }; PullTypeResolver.prototype.typeCheckFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { - this.typeCheckAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.getType(funcProp), funcProp.block, null, context); + this.typeCheckAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); }; PullTypeResolver.prototype.resolveObjectLiteralExpression = function (expressionAST, isContextuallyTyped, context, additionalResults) { var symbol = this.getSymbolForAST(expressionAST, context); + var hasResolvedSymbol = symbol && symbol.isResolved; - if (!symbol || additionalResults || this.canTypeCheckAST(expressionAST, context)) { + if (!hasResolvedSymbol || additionalResults || this.canTypeCheckAST(expressionAST, context)) { if (this.canTypeCheckAST(expressionAST, context)) { this.setTypeChecked(expressionAST, context); } @@ -44810,7 +46089,7 @@ var TypeScript; var decl = this.semanticInfoChain.getDeclForAST(propertyAssignment); TypeScript.Debug.assert(decl); - if (propertyAssignment.kind() == 240 /* SimplePropertyAssignment */) { + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { if (!isUsingExistingSymbol) { memberSymbol = new TypeScript.PullSymbol(assignmentText.memberName, 4096 /* Property */); memberSymbol.addDeclaration(decl); @@ -44826,8 +46105,9 @@ var TypeScript; } if (!isUsingExistingSymbol && !isAccessor) { - if (objectLiteralTypeSymbol.findMember(memberSymbol.name, true)) { - pullTypeContext.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(propertyAssignment, TypeScript.DiagnosticCode.Duplicate_identifier_0, [assignmentText.actualText])); + var existingMember = objectLiteralTypeSymbol.findMember(memberSymbol.name, true); + if (existingMember) { + pullTypeContext.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(propertyAssignment, assignmentText.actualText, existingMember.getDeclarations()[0].ast())); } objectLiteralTypeSymbol.addMember(memberSymbol); @@ -44848,9 +46128,10 @@ var TypeScript; var id = this.getPropertyAssignmentName(propertyAssignment); var memberSymbol = boundMemberSymbols[i]; + var contextualMemberType = null; if (objectLiteralContextualType) { - assigningSymbol = this.getMemberSymbol(memberSymbol.name, 68147712 /* SomeValue */, objectLiteralContextualType); + assigningSymbol = this.getNamedPropertySymbol(memberSymbol.name, 68147712 /* SomeValue */, objectLiteralContextualType); if (!assigningSymbol) { if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { @@ -44863,8 +46144,8 @@ var TypeScript; if (assigningSymbol) { this.resolveDeclaredSymbol(assigningSymbol, pullTypeContext); - var contextualMemberType = assigningSymbol.kind === 4194304 /* IndexSignature */ ? assigningSymbol.returnType : assigningSymbol.type; - pullTypeContext.pushContextualType(contextualMemberType, pullTypeContext.inProvisionalResolution(), null); + contextualMemberType = assigningSymbol.kind === 4194304 /* IndexSignature */ ? assigningSymbol.returnType : assigningSymbol.type; + pullTypeContext.propagateContextualType(contextualMemberType); acceptedContextualType = true; @@ -44874,32 +46155,31 @@ var TypeScript; } } - var propertySymbol = this.resolveAST(propertyAssignment, contextualMemberType != null, pullTypeContext); - var memberExpr = this.widenType(propertySymbol.type, propertyAssignment, pullTypeContext); + var memberSymbolType = this.resolveAST(propertyAssignment, contextualMemberType !== null, pullTypeContext).type; - if (memberExpr.type) { - if (memberExpr.type.isGeneric()) { + if (memberSymbolType) { + if (memberSymbolType.isGeneric()) { objectLiteralTypeSymbol.setHasGenericMember(); } if (stringIndexerSignature) { - allMemberTypes.push(memberExpr.type); + allMemberTypes.push(memberSymbolType); } if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { - allNumericMemberTypes.push(memberExpr.type); + allNumericMemberTypes.push(memberSymbolType); } } if (acceptedContextualType) { - pullTypeContext.popContextualType(); + pullTypeContext.popAnyContextualType(); } var isAccessor = propertyAssignment.kind() === 140 /* SetAccessor */ || propertyAssignment.kind() === 139 /* GetAccessor */; - if (!isUsingExistingSymbol) { + if (!memberSymbol.isResolved) { if (isAccessor) { - this.setSymbolForAST(id, memberExpr, pullTypeContext); + this.setSymbolForAST(id, memberSymbolType, pullTypeContext); } else { - pullTypeContext.setTypeInContext(memberSymbol, memberExpr.type); + pullTypeContext.setTypeInContext(memberSymbol, memberSymbolType); memberSymbol.setResolved(); this.setSymbolForAST(id, memberSymbol, pullTypeContext); @@ -44916,7 +46196,7 @@ var TypeScript; var isUsingExistingSymbol = !!typeSymbol; if (!typeSymbol) { - typeSymbol = new TypeScript.PullTypeSymbol("", 16 /* Interface */); + typeSymbol = new TypeScript.PullTypeSymbol("", 256 /* ObjectLiteral */); typeSymbol.addDeclaration(objectLitDecl); this.setSymbolForAST(objectLitAST, typeSymbol, context); objectLitDecl.setSymbol(typeSymbol); @@ -44936,17 +46216,18 @@ var TypeScript; var allNumericMemberTypes = null; if (contextualType) { - var indexSignatures = this.getBothKindsOfIndexSignatures(contextualType, context); + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); stringIndexerSignature = indexSignatures.stringSignature; numericIndexerSignature = indexSignatures.numericSignature; + var inInferentialTyping = context.isInferentiallyTyping(); if (stringIndexerSignature) { - allMemberTypes = [stringIndexerSignature.returnType]; + allMemberTypes = inInferentialTyping ? [] : [stringIndexerSignature.returnType]; } if (numericIndexerSignature) { - allNumericMemberTypes = [numericIndexerSignature.returnType]; + allNumericMemberTypes = inInferentialTyping ? [] : [numericIndexerSignature.returnType]; } } @@ -44994,8 +46275,8 @@ var TypeScript; } }; var decl = objectLiteralSymbol.getDeclarations()[0]; - var indexerReturnType = this.widenType(this.findBestCommonType(typeCollection, context)); - if (indexerReturnType == contextualIndexSignature.returnType) { + var indexerReturnType = this.findBestCommonType(typeCollection, context).widenedType(this, null, context); + if (indexerReturnType === contextualIndexSignature.returnType) { objectLiteralSymbol.addIndexSignature(contextualIndexSignature); } else { this.semanticInfoChain.addSyntheticIndexSignature(decl, objectLiteralSymbol, this.getASTForDecl(decl), contextualIndexSignature.parameters[0].name, contextualIndexSignature.parameters[0].type, indexerReturnType); @@ -45030,7 +46311,7 @@ var TypeScript; this.resolveDeclaredSymbol(contextualType, context); if (contextualType) { - var indexSignatures = this.getBothKindsOfIndexSignatures(contextualType, context); + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); if (indexSignatures.numericSignature) { contextualElementType = indexSignatures.numericSignature.returnType; } @@ -45039,7 +46320,7 @@ var TypeScript; if (elements) { if (contextualElementType) { - context.pushContextualType(contextualElementType, context.inProvisionalResolution(), null); + context.propagateContextualType(contextualElementType); } for (var i = 0, n = elements.nonSeparatorCount(); i < n; i++) { @@ -45047,7 +46328,7 @@ var TypeScript; } if (contextualElementType) { - context.popContextualType(); + context.popAnyContextualType(); } } @@ -45055,7 +46336,8 @@ var TypeScript; elementType = elementTypes[0]; } var collection; - if (contextualElementType) { + + if (contextualElementType && !context.isInferentiallyTyping()) { if (!elementType) { elementType = contextualElementType; } @@ -45085,19 +46367,7 @@ var TypeScript; elementType = this.semanticInfoChain.undefinedTypeSymbol; } - var arraySymbol = elementType.getArrayType(); - - if (!arraySymbol) { - arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); - - if (!arraySymbol) { - arraySymbol = this.semanticInfoChain.anyTypeSymbol; - } - - elementType.setArrayType(arraySymbol); - } - - return arraySymbol; + return this.getArrayType(elementType); }; PullTypeResolver.prototype.resolveElementAccessExpression = function (callEx, context) { @@ -45121,6 +46391,8 @@ var TypeScript; var targetTypeSymbol = targetSymbol.type; + targetTypeSymbol = this.getApparentType(targetTypeSymbol); + if (this.isAnyOrEquivalent(targetTypeSymbol)) { return { symbol: targetTypeSymbol }; } @@ -45136,7 +46408,7 @@ var TypeScript; if (callEx.argumentExpression.kind() === 14 /* StringLiteral */ || callEx.argumentExpression.kind() === 13 /* NumericLiteral */) { var memberName = callEx.argumentExpression.kind() === 14 /* StringLiteral */ ? TypeScript.stripStartAndEndQuotes(callEx.argumentExpression.text()) : callEx.argumentExpression.valueText(); - var member = this.getMemberSymbol(memberName, 68147712 /* SomeValue */, targetTypeSymbol); + var member = this._getNamedPropertySymbolOfAugmentedType(memberName, targetTypeSymbol); if (member) { this.resolveDeclaredSymbol(member, context); @@ -45145,11 +46417,7 @@ var TypeScript; } } - if (targetTypeSymbol == this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { - targetTypeSymbol = this.cachedStringInterfaceType(); - } - - var signatures = this.getBothKindsOfIndexSignatures(targetTypeSymbol, context); + var signatures = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(targetTypeSymbol, context); var stringSignature = signatures.stringSignature; var numberSignature = signatures.numericSignature; @@ -45159,6 +46427,9 @@ var TypeScript; } else if (stringSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol)) { return { symbol: stringSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; } else if (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol) { + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(callEx.argumentExpression, TypeScript.DiagnosticCode.Index_signature_of_object_type_implicitly_has_an_any_type)); + } return { symbol: this.semanticInfoChain.anyTypeSymbol }; } else { return { @@ -45168,8 +46439,16 @@ var TypeScript; } }; - PullTypeResolver.prototype.getBothKindsOfIndexSignatures = function (enclosingType, context) { - var signatures = enclosingType.getIndexSignatures(); + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesIncludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, true); + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesExcludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, false); + }; + + PullTypeResolver.prototype._getBothKindsOfIndexSignatures = function (enclosingType, context, includeAugmentedType) { + var signatures = includeAugmentedType ? enclosingType.getIndexSignaturesOfAugmentedType(this, this.cachedFunctionInterfaceType(), this.cachedObjectInterfaceType()) : enclosingType.getIndexSignatures(); var stringSignature = null; var numberSignature = null; @@ -45208,6 +46487,27 @@ var TypeScript; }; }; + PullTypeResolver.prototype._addUnhiddenSignaturesFromBaseType = function (derivedTypeSignatures, baseTypeSignatures, signaturesBeingAggregated) { + var _this = this; + if (!derivedTypeSignatures) { + signaturesBeingAggregated.push.apply(signaturesBeingAggregated, baseTypeSignatures); + return; + } + + var context = new TypeScript.PullTypeResolutionContext(this); + for (var i = 0; i < baseTypeSignatures.length; i++) { + var baseSignature = baseTypeSignatures[i]; + + var signatureIsHidden = TypeScript.ArrayUtilities.any(derivedTypeSignatures, function (sig) { + return _this.signaturesAreIdenticalWithNewEnclosingTypes(baseSignature, sig, context, false); + }); + + if (!signatureIsHidden) { + signaturesBeingAggregated.push(baseSignature); + } + } + }; + PullTypeResolver.prototype.resolveBinaryAdditionOperation = function (binaryExpression, context) { var lhsExpression = this.resolveAST(binaryExpression.left, false, context); var lhsType = lhsExpression.type; @@ -45215,22 +46515,23 @@ var TypeScript; if (TypeScript.PullHelpers.symbolIsEnum(lhsType)) { lhsType = this.semanticInfoChain.numberTypeSymbol; - } else if (lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol) { - if (rhsType != this.semanticInfoChain.nullTypeSymbol && rhsType != this.semanticInfoChain.undefinedTypeSymbol) { - lhsType = rhsType; - } else { - lhsType = this.semanticInfoChain.anyTypeSymbol; - } } if (TypeScript.PullHelpers.symbolIsEnum(rhsType)) { rhsType = this.semanticInfoChain.numberTypeSymbol; - } else if (rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol) { - if (lhsType != this.semanticInfoChain.nullTypeSymbol && lhsType != this.semanticInfoChain.undefinedTypeSymbol) { - rhsType = lhsType; + } + + var isLhsTypeNullOrUndefined = lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol; + var isRhsTypeNullOrUndefined = rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol; + + if (isLhsTypeNullOrUndefined) { + if (isRhsTypeNullOrUndefined) { + lhsType = rhsType = this.semanticInfoChain.anyTypeSymbol; } else { - rhsType = this.semanticInfoChain.anyTypeSymbol; + lhsType = rhsType; } + } else if (isRhsTypeNullOrUndefined) { + rhsType = lhsType; } var exprType = null; @@ -45310,13 +46611,13 @@ var TypeScript; var leftType = this.resolveAST(binex.left, isContextuallyTyped, context).type; var rightType = this.resolveAST(binex.right, isContextuallyTyped, context).type; - return this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + return context.isInferentiallyTyping() ? this.bestCommonTypeOfTwoTypes(leftType, rightType, context) : this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); } else { var leftType = this.resolveAST(binex.left, false, context).type; - context.pushContextualType(leftType, context.inProvisionalResolution(), null); + context.pushNewContextualType(leftType); var rightType = this.resolveAST(binex.right, true, context).type; - context.popContextualType(); + context.popAnyContextualType(); return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); } @@ -45333,7 +46634,7 @@ var TypeScript; }; PullTypeResolver.prototype.computeTypeOfConditionalExpression = function (leftType, rightType, isContextuallyTyped, context) { - if (isContextuallyTyped) { + if (isContextuallyTyped && !context.isInferentiallyTyping()) { var contextualType = context.getContextualType(); return this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); } else { @@ -45373,11 +46674,11 @@ var TypeScript; PullTypeResolver.prototype.conditionExpressionTypesAreValid = function (leftType, rightType, expressionType, isContextuallyTyped, context) { if (isContextuallyTyped) { var contextualType = context.getContextualType(); - if (this.typesAreIdentical(expressionType, leftType) || this.typesAreIdentical(expressionType, rightType) || this.typesAreIdentical(expressionType, contextualType)) { + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context) || this.typesAreIdentical(expressionType, contextualType, context)) { return true; } } else { - if (this.typesAreIdentical(expressionType, leftType) || this.typesAreIdentical(expressionType, rightType)) { + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context)) { return true; } } @@ -45414,7 +46715,7 @@ var TypeScript; if (this.canTypeCheckAST(callEx, context)) { this.setTypeChecked(callEx, context); } - if (symbol != this.semanticInfoChain.anyTypeSymbol) { + if (symbol !== this.semanticInfoChain.anyTypeSymbol) { this.setSymbolForAST(callEx, symbol, context); } this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); @@ -45424,7 +46725,7 @@ var TypeScript; } var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); - if (additionalResults && (callResolutionData != additionalResults)) { + if (additionalResults && (callResolutionData !== additionalResults)) { additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; additionalResults.candidateSignature = callResolutionData.candidateSignature; additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; @@ -45446,13 +46747,13 @@ var TypeScript; for (var i = 0; i < len; i++) { var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.pushNewContextualType(contextualType); } - this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType != null, context); + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); contextualType = null; } } @@ -45500,12 +46801,11 @@ var TypeScript; var signatures = isSuperCall ? targetTypeSymbol.getConstructSignatures() : targetTypeSymbol.getCallSignatures(); - if (!signatures.length && (targetTypeSymbol.kind == 33554432 /* ConstructorType */)) { + if (!signatures.length && (targetTypeSymbol.kind === 33554432 /* ConstructorType */)) { this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, [targetTypeSymbol.toString()]), additionalResults, context); } - var typeArgs = null; - var typeReplacementMap = null; + var explicitTypeArgs = null; var couldNotFindGenericOverload = false; var couldNotAssignToConstraint; var constraintDiagnostic = null; @@ -45513,21 +46813,19 @@ var TypeScript; var diagnostics = []; if (callEx.argumentList.typeArgumentList) { - typeArgs = []; + explicitTypeArgs = []; if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { - typeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); } } - } else if (isSuperCall && targetTypeSymbol.isGeneric()) { - typeArgs = targetTypeSymbol.getTypeArguments(); } var triedToInferTypeArgs = false; var resolvedSignatures = []; - var inferredTypeArgs; + var inferredOrExplicitTypeArgs; var specializedSignature; var typeParameters; var typeConstraint = null; @@ -45539,86 +46837,61 @@ var TypeScript; couldNotAssignToConstraint = false; if (signatures[i].isGeneric() && typeParameters.length) { - if (typeArgs) { - if (typeArgs.length == typeParameters.length) { - inferredTypeArgs = typeArgs; - } else { - typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, typeArgs.length]); - continue; - } - } else if (!typeArgs && callEx.argumentList.arguments && callEx.argumentList.arguments.nonSeparatorCount()) { - inferredTypeArgs = this.inferArgumentTypesForSignature(signatures[i], new TypeScript.ArgumentInferenceContext(this, callEx.argumentList.arguments), new TypeComparisonInfo(), context); - triedToInferTypeArgs = true; - } else { - inferredTypeArgs = []; + if (isSuperCall && targetTypeSymbol.isGeneric() && !callEx.argumentList.typeArgumentList) { + explicitTypeArgs = signatures[i].returnType.getTypeArguments(); } - if (inferredTypeArgs) { - typeReplacementMap = []; - - if (inferredTypeArgs.length) { - if (inferredTypeArgs.length != typeParameters.length) { - continue; - } - - if (targetTypeReplacementMap) { - for (var symbolID in targetTypeReplacementMap) { - if (targetTypeReplacementMap.hasOwnProperty(symbolID)) { - typeReplacementMap[symbolID] = targetTypeReplacementMap[symbolID]; - } - } - } - - for (var j = 0; j < typeParameters.length; j++) { - typeReplacementMap[typeParameters[j].pullSymbolID] = inferredTypeArgs[j]; - } - for (var j = 0; j < typeParameters.length; j++) { - typeConstraint = typeParameters[j].getConstraint(); - - if (typeConstraint) { - if (typeConstraint.isTypeParameter()) { - for (var k = 0; k < typeParameters.length && k < inferredTypeArgs.length; k++) { - if (typeParameters[k] == typeConstraint) { - typeConstraint = inferredTypeArgs[k]; - } else { - typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); - } - } - } else if (typeConstraint.isGeneric()) { - typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); - } - - if (!this.sourceIsAssignableToTarget(inferredTypeArgs[j], typeConstraint, targetAST, context, null, true)) { - var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); - constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); - couldNotAssignToConstraint = true; - } - - if (couldNotAssignToConstraint) { - break; - } - } - } + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; } else { - if (triedToInferTypeArgs) { - continue; - } - - for (var j = 0; j < typeParameters.length; j++) { - typeReplacementMap[typeParameters[j].pullSymbolID] = this.semanticInfoChain.emptyTypeSymbol; - } - } - - if (couldNotAssignToConstraint) { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); continue; } + } else { + TypeScript.Debug.assert(callEx.argumentList); + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, signatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } - specializedSignature = this.instantiateSignature(signatures[i], typeReplacementMap, true); + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); - if (specializedSignature) { - resolvedSignatures[resolvedSignatures.length] = specializedSignature; + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } } } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(signatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } } else { if (!(callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { resolvedSignatures[resolvedSignatures.length] = signatures[i]; @@ -45643,7 +46916,7 @@ var TypeScript; this.resolveAST(callEx.argumentList.arguments, false, context); if (!couldNotFindGenericOverload) { - if (this.cachedFunctionInterfaceType() && this.sourceIsSubtypeOfTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), targetAST, context)) { + if (this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), targetAST, context)) { if (callEx.argumentList.typeArgumentList) { this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); } @@ -45662,7 +46935,7 @@ var TypeScript; return this.getNewErrorTypeSymbol(); } - var signature = this.resolveOverloads(callEx, signatures, callEx.argumentList.typeArgumentList != null, context, diagnostics); + var signature = this.resolveOverloads(callEx, signatures, callEx.argumentList.typeArgumentList !== null, context, diagnostics); var useBeforeResolutionSignatures = signature == null; if (!signature) { @@ -45681,10 +46954,11 @@ var TypeScript; signature = signatures[0]; } - if (!signature.isGeneric() && callEx.argumentList.typeArgumentList) { + var rootSignature = signature.getRootSymbol(); + if (!rootSignature.isGeneric() && callEx.argumentList.typeArgumentList) { this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); - } else if (signature.isGeneric() && callEx.argumentList.typeArgumentList && signature.getTypeParameters() && (callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount() != signature.getTypeParameters().length)) { - this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [signature.getTypeParameters().length, callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()]), additionalResults, context); + } else if (rootSignature.isGeneric() && callEx.argumentList.typeArgumentList && rootSignature.getTypeParameters() && (callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount() !== rootSignature.getTypeParameters().length)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [rootSignature.getTypeParameters().length, callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()]), additionalResults, context); } var returnType = isSuperCall ? this.semanticInfoChain.voidTypeSymbol : signature.returnType; @@ -45710,14 +46984,14 @@ var TypeScript; } if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.pushNewContextualType(contextualType); actualParametersContextTypeSymbols[i] = contextualType; } - this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType != null, context); + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); contextualType = null; } } @@ -45763,7 +47037,7 @@ var TypeScript; } var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); - if (additionalResults && (callResolutionData != additionalResults)) { + if (additionalResults && (callResolutionData !== additionalResults)) { additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; additionalResults.candidateSignature = callResolutionData.candidateSignature; additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; @@ -45785,13 +47059,13 @@ var TypeScript; for (var i = 0; i < len; i++) { var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.pushNewContextualType(contextualType); } - this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType != null, context); + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); contextualType = null; } } @@ -45810,6 +47084,7 @@ var TypeScript; }; PullTypeResolver.prototype.computeObjectCreationExpressionSymbol = function (callEx, context, additionalResults) { + var _this = this; var returnType = null; var targetSymbol = this.resolveAST(callEx.expression, false, context); @@ -45819,8 +47094,7 @@ var TypeScript; var constructSignatures = targetTypeSymbol.getConstructSignatures(); - var typeArgs = null; - var typeReplacementMap = null; + var explicitTypeArgs = null; var usedCallSignaturesInstead = false; var couldNotAssignToConstraint; var constraintDiagnostic = null; @@ -45846,18 +47120,18 @@ var TypeScript; if (constructSignatures.length) { if (callEx.argumentList && callEx.argumentList.typeArgumentList) { - typeArgs = []; + explicitTypeArgs = []; if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { - typeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); } } } if (targetTypeSymbol.isGeneric()) { var resolvedSignatures = []; - var inferredTypeArgs; + var inferredOrExplicitTypeArgs; var specializedSignature; var typeParameters; var typeConstraint = null; @@ -45870,85 +47144,59 @@ var TypeScript; if (constructSignatures[i].isGeneric()) { typeParameters = constructSignatures[i].getTypeParameters(); - if (typeArgs) { - if (typeArgs.length == typeParameters.length) { - inferredTypeArgs = typeArgs; + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; } else { - typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, typeArgs.length]); + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); continue; } - } else if (!typeArgs && callEx.argumentList && callEx.argumentList.arguments && callEx.argumentList.arguments.nonSeparatorCount()) { - inferredTypeArgs = this.inferArgumentTypesForSignature(constructSignatures[i], new TypeScript.ArgumentInferenceContext(this, callEx.argumentList.arguments), new TypeComparisonInfo(), context); + } else if (callEx.argumentList) { + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, constructSignatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); triedToInferTypeArgs = true; } else { - inferredTypeArgs = []; + inferredOrExplicitTypeArgs = TypeScript.ArrayUtilities.select(typeParameters, function (typeParameter) { + return typeParameter.getDefaultConstraint(_this.semanticInfoChain); + }); } - if (inferredTypeArgs) { - typeReplacementMap = []; + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); - if (inferredTypeArgs.length) { - if (inferredTypeArgs.length < typeParameters.length) { - continue; - } + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; - if (targetTypeReplacementMap) { - for (var symbolID in targetTypeReplacementMap) { - if (targetTypeReplacementMap.hasOwnProperty(symbolID)) { - typeReplacementMap[symbolID] = targetTypeReplacementMap[symbolID]; - } + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); } - } - for (var j = 0; j < typeParameters.length; j++) { - typeReplacementMap[typeParameters[j].pullSymbolID] = inferredTypeArgs[j]; - } - for (var j = 0; j < typeParameters.length; j++) { - typeConstraint = typeParameters[j].getConstraint(); - - if (typeConstraint) { - if (typeConstraint.isTypeParameter()) { - for (var k = 0; k < typeParameters.length && k < inferredTypeArgs.length; k++) { - if (typeParameters[k] == typeConstraint) { - typeConstraint = inferredTypeArgs[k]; - } else { - typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); - } - } - } else if (typeConstraint.isGeneric()) { - typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); - } - - if (!this.sourceIsAssignableToTarget(inferredTypeArgs[j], typeConstraint, targetAST, context, null, true)) { - var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); - constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); - couldNotAssignToConstraint = true; - } - - if (couldNotAssignToConstraint) { - break; - } + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; } - } - } else { - if (triedToInferTypeArgs) { - continue; - } else { - for (var j = 0; j < typeParameters.length; j++) { - typeReplacementMap[typeParameters[j].pullSymbolID] = this.semanticInfoChain.emptyTypeSymbol; + + if (couldNotAssignToConstraint) { + break; } } } + } - if (couldNotAssignToConstraint) { - continue; - } + if (couldNotAssignToConstraint) { + continue; + } - specializedSignature = this.instantiateSignature(constructSignatures[i], typeReplacementMap, true); + specializedSignature = this.instantiateSignature(constructSignatures[i], typeReplacementMap); - if (specializedSignature) { - resolvedSignatures[resolvedSignatures.length] = specializedSignature; - } + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; } } else { if (!(callEx.argumentList && callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { @@ -45960,7 +47208,7 @@ var TypeScript; constructSignatures = resolvedSignatures; } - var signature = this.resolveOverloads(callEx, constructSignatures, callEx.argumentList && callEx.argumentList.typeArgumentList != null, context, diagnostics); + var signature = this.resolveOverloads(callEx, constructSignatures, callEx.argumentList && callEx.argumentList.typeArgumentList !== null, context, diagnostics); additionalResults.targetSymbol = targetSymbol; additionalResults.resolvedSignatures = constructSignatures; @@ -45998,15 +47246,15 @@ var TypeScript; returnType = signature.returnType; if (returnType && !signature.isGeneric() && returnType.isGeneric() && !returnType.getIsSpecialized()) { - if (typeArgs && typeArgs.length) { - returnType = this.createInstantiatedType(returnType, typeArgs); + if (explicitTypeArgs && explicitTypeArgs.length) { + returnType = this.createInstantiatedType(returnType, explicitTypeArgs); } else { returnType = this.instantiateTypeToAny(returnType, context); } } if (usedCallSignaturesInstead) { - if (returnType != this.semanticInfoChain.voidTypeSymbol) { + if (returnType !== this.semanticInfoChain.voidTypeSymbol) { this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Call_signatures_used_in_a_new_expression_must_have_a_void_return_type), additionalResults, context); return this.getNewErrorTypeSymbol(); @@ -46044,14 +47292,14 @@ var TypeScript; } if (contextualType) { - context.pushContextualType(contextualType, context.inProvisionalResolution(), null); + context.pushNewContextualType(contextualType); actualParametersContextTypeSymbols[i] = contextualType; } - this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType != null, context); + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); if (contextualType) { - context.popContextualType(); + context.popAnyContextualType(); contextualType = null; } } @@ -46080,23 +47328,18 @@ var TypeScript; return this.getNewErrorTypeSymbol(); }; - PullTypeResolver.prototype.instantiateSignatureInContext = function (signatureA, signatureB, context) { + PullTypeResolver.prototype.instantiateSignatureInContext = function (signatureAToInstantiate, contextualSignatureB, context, shouldFixContextualSignatureParameterTypes) { var typeReplacementMap = []; var inferredTypeArgs; var specializedSignature; - var typeParameters = signatureA.getTypeParameters(); + var typeParameters = signatureAToInstantiate.getTypeParameters(); var typeConstraint = null; - var fixedParameterTypes = []; + var typeArgumentInferenceContext = new TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext(this, context, signatureAToInstantiate, contextualSignatureB, shouldFixContextualSignatureParameterTypes); + inferredTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); - for (var i = 0; i < signatureB.parameters.length; i++) { - fixedParameterTypes.push(signatureB.parameters[i].isVarArg ? signatureB.parameters[i].type.getElementType() : signatureB.parameters[i].type); - } - - inferredTypeArgs = this.inferArgumentTypesForSignature(signatureA, new TypeScript.ArgumentInferenceContext(this, fixedParameterTypes), new TypeComparisonInfo(), context); - - var functionTypeA = signatureA.functionType; - var functionTypeB = signatureB.functionType; + var functionTypeA = signatureAToInstantiate.functionType; + var functionTypeB = contextualSignatureB.functionType; var enclosingTypeParameterMap; if (functionTypeA) { @@ -46115,34 +47358,9 @@ var TypeScript; } } - for (var i = 0; i < typeParameters.length; i++) { - typeReplacementMap[typeParameters[i].pullSymbolID] = inferredTypeArgs[i]; - } - for (var i = 0; i < typeParameters.length; i++) { - typeConstraint = typeParameters[i].getConstraint(); + TypeScript.PullInstantiationHelpers.updateTypeParameterArgumentMap(typeParameters, inferredTypeArgs, typeReplacementMap); - if (typeConstraint) { - if (typeConstraint.isTypeParameter()) { - for (var j = 0; j < typeParameters.length && j < inferredTypeArgs.length; j++) { - if (typeParameters[j] == typeConstraint) { - typeConstraint = inferredTypeArgs[j]; - } - } - } else if (typeConstraint.isGeneric()) { - typeConstraint = TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, typeConstraint, typeReplacementMap); - } - - if (!this.sourceIsAssignableToTarget(inferredTypeArgs[i], typeConstraint, null, context, null, true)) { - if (this.signaturesAreIdentical(signatureA, signatureB, true)) { - return signatureA; - } else { - return null; - } - } - } - } - - return this.instantiateSignature(signatureA, typeReplacementMap, true); + return this.instantiateSignature(signatureAToInstantiate, typeReplacementMap); }; PullTypeResolver.prototype.resolveCastExpression = function (assertionExpression, context) { @@ -46158,16 +47376,21 @@ var TypeScript; PullTypeResolver.prototype.typeCheckCastExpression = function (assertionExpression, context, typeAssertionType) { this.setTypeChecked(assertionExpression, context); - context.pushContextualType(typeAssertionType, context.inProvisionalResolution(), null); + context.pushNewContextualType(typeAssertionType); var exprType = this.resolveAST(assertionExpression.expression, true, context).type; - context.popContextualType(); + context.popAnyContextualType(); this.resolveDeclaredSymbol(typeAssertionType, context); this.resolveDeclaredSymbol(exprType, context); var comparisonInfo = new TypeComparisonInfo(); - var isAssignable = this.sourceIsAssignableToTarget(typeAssertionType, exprType, assertionExpression, context, comparisonInfo) || this.sourceIsAssignableToTarget(exprType, typeAssertionType, assertionExpression, context, comparisonInfo); + var isAssignable = this.sourceIsAssignableToTarget(exprType, typeAssertionType, assertionExpression, context, comparisonInfo); + + if (!isAssignable) { + var widenedExprType = exprType.widenedType(this, assertionExpression.expression, context); + isAssignable = this.sourceIsAssignableToTarget(typeAssertionType, widenedExprType, assertionExpression, context, comparisonInfo); + } if (!isAssignable) { var enclosingSymbol = this.getEnclosingSymbolForAST(assertionExpression); @@ -46183,9 +47406,9 @@ var TypeScript; var leftExpr = this.resolveAST(binaryExpression.left, false, context); var leftType = leftExpr.type; - context.pushContextualType(leftType, context.inProvisionalResolution(), null); + context.pushNewContextualType(leftType); var rightType = this.resolveAST(binaryExpression.right, true, context).type; - context.popContextualType(); + context.popAnyContextualType(); rightType = this.getInstanceTypeForAssignment(binaryExpression.left, rightType, context); @@ -46228,30 +47451,82 @@ var TypeScript; } if (type.isArrayNamedTypeReference()) { - var elementType = this.widenType(type.getElementType(), null, context); - - if (this.compilationSettings.noImplicitAny() && ast && ast.kind() === 214 /* ArrayLiteralExpression */) { - if (elementType === this.semanticInfoChain.anyTypeSymbol && type.getElementType() !== this.semanticInfoChain.anyTypeSymbol) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Array_Literal_implicitly_has_an_any_type_from_widening)); - } - } - - var arraySymbol = elementType.getArrayType(); - - if (!arraySymbol) { - arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); - - if (!arraySymbol) { - arraySymbol = this.semanticInfoChain.anyTypeSymbol; - } - } - - return arraySymbol; + return this.widenArrayType(type, ast, context); + } else if (type.kind === 256 /* ObjectLiteral */) { + return this.widenObjectLiteralType(type, ast, context); } return type; }; + PullTypeResolver.prototype.widenArrayType = function (type, ast, context) { + var elementType = type.getElementType().widenedType(this, ast, context); + + if (this.compilationSettings.noImplicitAny() && ast) { + if (elementType === this.semanticInfoChain.anyTypeSymbol && type.getElementType() !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Array_Literal_implicitly_has_an_any_type_from_widening)); + } + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.widenObjectLiteralType = function (type, ast, context) { + if (!this.needsToWidenObjectLiteralType(type, ast, context)) { + return type; + } + + TypeScript.Debug.assert(type.name === ""); + var newObjectTypeSymbol = new TypeScript.PullTypeSymbol(type.name, type.kind); + var declsOfObjectType = type.getDeclarations(); + TypeScript.Debug.assert(declsOfObjectType.length === 1); + newObjectTypeSymbol.addDeclaration(declsOfObjectType[0]); + var members = type.getMembers(); + + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + + var widenedMemberType = members[i].type.widenedType(this, ast, context); + var newMember = new TypeScript.PullSymbol(members[i].name, members[i].kind); + + var declsOfMember = members[i].getDeclarations(); + + newMember.addDeclaration(declsOfMember[0]); + newMember.type = widenedMemberType; + newObjectTypeSymbol.addMember(newMember); + newMember.setResolved(); + + if (this.compilationSettings.noImplicitAny() && ast && widenedMemberType === this.semanticInfoChain.anyTypeSymbol && memberType !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Object_literal_s_property_0_implicitly_has_an_any_type_from_widening, [members[i].name])); + } + } + + var indexers = type.getIndexSignatures(); + for (var i = 0; i < indexers.length; i++) { + var newIndexer = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var parameter = indexers[i].parameters[0]; + var newParameter = new TypeScript.PullSymbol(parameter.name, parameter.kind); + newParameter.type = parameter.type; + newIndexer.addParameter(newParameter); + newIndexer.returnType = indexers[i].returnType; + newObjectTypeSymbol.addIndexSignature(newIndexer); + } + + return newObjectTypeSymbol; + }; + + PullTypeResolver.prototype.needsToWidenObjectLiteralType = function (type, ast, context) { + var members = type.getMembers(); + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + if (memberType !== memberType.widenedType(this, ast, context)) { + return true; + } + } + + return false; + }; + PullTypeResolver.prototype.findBestCommonType = function (collection, context, comparisonInfo) { var len = collection.getLength(); @@ -46268,15 +47543,11 @@ var TypeScript; PullTypeResolver.prototype.typeIsBestCommonTypeCandidate = function (candidateType, collection, context) { for (var i = 0; i < collection.getLength(); i++) { var otherType = collection.getTypeAtIndex(i); - if (candidateType == otherType) { + if (candidateType === otherType) { continue; } - if (candidateType.isTypeParameter() && !otherType.isTypeParameter()) { - return false; - } else if (!candidateType.isTypeParameter() && otherType.isTypeParameter()) { - continue; - } else if (!this.sourceIsSubtypeOfTarget(otherType, candidateType, null, context)) { + if (!this.sourceIsSubtypeOfTarget(otherType, candidateType, null, context)) { return false; } } @@ -46284,7 +47555,7 @@ var TypeScript; return true; }; - PullTypeResolver.prototype.typesAreIdenticalInEnclosingTypes = function (t1, t2, t1EnclosingType, t2EnclosingType, val) { + PullTypeResolver.prototype.typesAreIdenticalInEnclosingTypes = function (t1, t2, context) { t1 = this.getSymbolForRelationshipCheck(t1); t2 = this.getSymbolForRelationshipCheck(t2); @@ -46293,17 +47564,22 @@ var TypeScript; } if (t1 && t2) { - var t1GenerativeTypeKind = t1EnclosingType ? t1.getGenerativeTypeClassification(t1EnclosingType) : 0 /* Unknown */; - var t2GenerativeTypeKind = t2EnclosingType ? t2.getGenerativeTypeClassification(t2EnclosingType) : 0 /* Unknown */; - if (t1GenerativeTypeKind == 3 /* InfinitelyExpanding */ || t2GenerativeTypeKind == 3 /* InfinitelyExpanding */) { - return this.infinitelyExpandingTypesAreIdentical(t1, t2); + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingTypesAreIdentical(t1, t2, context); } } - return this.typesAreIdentical(t1, t2, val); + return this.typesAreIdentical(t1, t2, context); }; - PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, val) { + PullTypeResolver.prototype.typesAreIdenticalWithNewEnclosingTypes = function (t1, t2, context) { + var enclosingTypeWalkers = context.resetEnclosingTypeWalkers(); + var areTypesIdentical = this.typesAreIdentical(t1, t2, context); + context.setEnclosingTypeWalkers(enclosingTypeWalkers); + return areTypesIdentical; + }; + + PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, context) { t1 = this.getSymbolForRelationshipCheck(t1); t2 = this.getSymbolForRelationshipCheck(t2); @@ -46315,12 +47591,8 @@ var TypeScript; return false; } - if (val && t1.isPrimitive() && t1.isStringConstant() && t2 === this.semanticInfoChain.stringTypeSymbol) { - return (val.kind() === 14 /* StringLiteral */) && (TypeScript.stripStartAndEndQuotes(val.text()) === TypeScript.stripStartAndEndQuotes(t1.name)); - } - - if (val && t2.isPrimitive() && t2.isStringConstant() && t2 === this.semanticInfoChain.stringTypeSymbol) { - return (val.kind() === 14 /* StringLiteral */) && (TypeScript.stripStartAndEndQuotes(val.text()) === TypeScript.stripStartAndEndQuotes(t2.name)); + if (TypeScript.hasFlag(t1.kind, 64 /* Enum */) || TypeScript.hasFlag(t2.kind, 64 /* Enum */)) { + return false; } if (t1.isPrimitive() && t1.isStringConstant() && t2.isPrimitive() && t2.isStringConstant()) { @@ -46335,7 +47607,12 @@ var TypeScript; return true; } - if (t1.isTypeParameter() != t2.isTypeParameter()) { + var isIdentical = this.identicalCache.valueAt(t1.pullSymbolID, t2.pullSymbolID); + if (isIdentical != undefined) { + return isIdentical; + } + + if (t1.isTypeParameter() !== t2.isTypeParameter()) { return false; } else if (t1.isTypeParameter()) { var t1ParentDeclaration = t1.getDeclarations()[0].getParentDecl(); @@ -46348,27 +47625,42 @@ var TypeScript; } } - var isIdentical = this.identicalCache.valueAt(t1.pullSymbolID, t2.pullSymbolID); - if (isIdentical != undefined) { - return isIdentical; - } - - if ((t1.kind & 64 /* Enum */) || (t2.kind & 64 /* Enum */)) { - return t1.getAssociatedContainerType() === t2 || t2.getAssociatedContainerType() === t1; - } - - if (t1.isPrimitive() != t2.isPrimitive()) { + if (t1.isPrimitive() !== t2.isPrimitive()) { return false; } - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, false); + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, true); + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(t1, t2); + isIdentical = this.typesAreIdenticalWorker(t1, t2, context); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, isIdentical); + + return isIdentical; + }; + + PullTypeResolver.prototype.typesAreIdenticalWorker = function (t1, t2, context) { + if (t1.getIsSpecialized() && t2.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(t1) === TypeScript.PullHelpers.getRootType(t2) && TypeScript.PullHelpers.getRootType(t1).isNamedTypeSymbol()) { + var t1TypeArguments = t1.getTypeArguments(); + var t2TypeArguments = t2.getTypeArguments(); + + if (t1TypeArguments && t2TypeArguments) { + for (var i = 0; i < t1TypeArguments.length; i++) { + if (!this.typesAreIdenticalWithNewEnclosingTypes(t1TypeArguments[i], t2TypeArguments[i], context)) { + return false; + } + } + } + + return true; + } + } if (t1.hasMembers() && t2.hasMembers()) { var t1Members = t1.getAllMembers(68147712 /* SomeValue */, 0 /* all */); var t2Members = t2.getAllMembers(68147712 /* SomeValue */, 0 /* all */); - if (t1Members.length != t2Members.length) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); + if (t1Members.length !== t2Members.length) { return false; } @@ -46380,22 +47672,13 @@ var TypeScript; for (var iMember = 0; iMember < t1Members.length; iMember++) { t1MemberSymbol = t1Members[iMember]; - t2MemberSymbol = this.getMemberSymbol(t1MemberSymbol.name, 68147712 /* SomeValue */, t2); + t2MemberSymbol = this.getNamedPropertySymbol(t1MemberSymbol.name, 68147712 /* SomeValue */, t2); - if (!t2MemberSymbol || (t1MemberSymbol.isOptional != t2MemberSymbol.isOptional)) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); - return false; - } - - t1MemberType = t1MemberSymbol.type; - t2MemberType = t2MemberSymbol.type; - - if (!this.typesAreIdenticalInEnclosingTypes(t1MemberType, t2MemberType, t1, t2)) { + if (!this.propertiesAreIdentical(t1MemberSymbol, t2MemberSymbol, context)) { return false; } } } else if (t1.hasMembers() || t2.hasMembers()) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); return false; } @@ -46408,26 +47691,57 @@ var TypeScript; var t1IndexSigs = t1.getIndexSignatures(); var t2IndexSigs = t2.getIndexSignatures(); - if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs)) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); + if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs, context)) { return false; } - if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs)) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); + if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs, context)) { return false; } - if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs)) { - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, undefined); + if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs, context)) { return false; } - this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, true); return true; }; - PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { + PullTypeResolver.prototype.propertiesAreIdentical = function (propertySymbol1, propertySymbol2, context) { + if (!propertySymbol2 || (propertySymbol1.isOptional !== propertySymbol2.isOptional)) { + return false; + } + + var t1MemberSymbolIsPrivate = propertySymbol1.anyDeclHasFlag(2 /* Private */); + var t2MemberSymbolIsPrivate = propertySymbol2.anyDeclHasFlag(2 /* Private */); + + if (t1MemberSymbolIsPrivate !== t2MemberSymbolIsPrivate) { + return false; + } else if (t2MemberSymbolIsPrivate && t1MemberSymbolIsPrivate) { + var t1MemberSymbolDecl = propertySymbol1.getDeclarations()[0]; + var sourceDecl = propertySymbol2.getDeclarations()[0]; + if (t1MemberSymbolDecl !== sourceDecl) { + return false; + } + } + + var t1MemberType = propertySymbol1.type; + var t2MemberType = propertySymbol2.type; + + context.walkMemberTypes(propertySymbol1.name); + var areMemberTypesIdentical = this.typesAreIdenticalInEnclosingTypes(t1MemberType, t2MemberType, context); + context.postWalkMemberTypes(); + return areMemberTypesIdentical; + }; + + PullTypeResolver.prototype.propertiesAreIdenticalWithNewEnclosingTypes = function (type1, type2, property1, property2, context) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(type1, type2); + var arePropertiesIdentical = this.propertiesAreIdentical(property1, property2, context); + context.setEnclosingTypeWalkers(enclosingWalkers); + return arePropertiesIdentical; + }; + + PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2, context) { if (sg1 === sg2) { return true; } @@ -46436,75 +47750,15 @@ var TypeScript; return false; } - if (sg1.length != sg2.length) { + if (sg1.length !== sg2.length) { return false; } - var sig1 = null; - var sig2 = null; - var sigsMatch = false; - - for (var iSig1 = 0; iSig1 < sg1.length; iSig1++) { - sig1 = sg1[iSig1]; - - for (var iSig2 = 0; iSig2 < sg2.length; iSig2++) { - sig2 = sg2[iSig2]; - - if (this.signaturesAreIdentical(sig1, sig2)) { - sigsMatch = true; - break; - } - } - - if (sigsMatch) { - sigsMatch = false; - continue; - } - - return false; - } - - return true; - }; - - PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2, includingReturnType) { - if (typeof includingReturnType === "undefined") { includingReturnType = true; } - if (s1 === s2) { - return true; - } - - if (s1.hasVarArgs != s2.hasVarArgs) { - return false; - } - - if (s1.nonOptionalParamCount != s2.nonOptionalParamCount) { - return false; - } - - if (!!(s1.typeParameters && s1.typeParameters.length) != !!(s2.typeParameters && s2.typeParameters.length)) { - return false; - } - - if (s1.typeParameters && s2.typeParameters && (s1.typeParameters.length != s2.typeParameters.length)) { - return false; - } - - if (s1.parameters.length != s2.parameters.length) { - return false; - } - - this.resolveDeclaredSymbol(s1); - this.resolveDeclaredSymbol(s2); - - var s1Params = s1.parameters; - var s2Params = s2.parameters; - - if (includingReturnType && !this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, s1.functionType, s2.functionType)) { - return false; - } - - for (var iParam = 0; iParam < s1Params.length; iParam++) { - if (!this.typesAreIdenticalInEnclosingTypes(s1Params[iParam].type, s2Params[iParam].type, s1.functionType, s2.functionType)) { + for (var i = 0; i < sg1.length; i++) { + context.walkSignatures(sg1[i].kind, i); + var areSignaturesIdentical = this.signaturesAreIdentical(sg1[i], sg2[i], context, true); + context.postWalkSignatures(); + if (!areSignaturesIdentical) { return false; } } @@ -46512,18 +47766,152 @@ var TypeScript; return true; }; - PullTypeResolver.prototype.substituteUpperBoundForType = function (type) { - if (!type || !type.isTypeParameter()) { - return type; + PullTypeResolver.prototype.typeParametersAreIdentical = function (tp1, tp2, context) { + var typeParamsAreIdentical = this.typeParametersAreIdenticalWorker(tp1, tp2, context); + + this.setTypeParameterIdentity(tp1, tp2, undefined); + + return typeParamsAreIdentical; + }; + + PullTypeResolver.prototype.typeParametersAreIdenticalWorker = function (tp1, tp2, context) { + if (!!(tp1 && tp1.length) !== !!(tp2 && tp2.length)) { + return false; } - var constraint = type.getConstraint(); - - if (constraint && (constraint != type)) { - return this.substituteUpperBoundForType(constraint); + if (tp1 && tp2 && (tp1.length !== tp2.length)) { + return false; } - return type; + if (tp1 && tp2) { + for (var i = 0; i < tp1.length; i++) { + context.walkTypeParameterConstraints(i); + var areConstraintsIdentical = this.typesAreIdentical(tp1[i].getConstraint(), tp2[i].getConstraint(), context); + context.postWalkTypeParameterConstraints(); + if (!areConstraintsIdentical) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.setTypeParameterIdentity = function (tp1, tp2, val) { + if (tp1 && tp2 && tp1.length === tp2.length) { + for (var i = 0; i < tp1.length; i++) { + this.identicalCache.setValueAt(tp1[i].pullSymbolID, tp2[i].pullSymbolID, val); + } + } + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWithNewEnclosingTypes = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(s1, s2); + var areSignaturesIdentical = this.signaturesAreIdentical(s1, s2, context, includingReturnType); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSignaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1 === s2) { + return true; + } + + var signaturesIdentical = this.identicalCache.valueAt(s1.pullSymbolID, s2.pullSymbolID); + if (signaturesIdentical || (signaturesIdentical != undefined && includingReturnType)) { + return signaturesIdentical; + } + + var oldValue = signaturesIdentical; + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, true); + + signaturesIdentical = this.signaturesAreIdenticalWorker(s1, s2, context, includingReturnType); + + if (includingReturnType) { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, signaturesIdentical); + } else { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, oldValue); + } + + return signaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWorker = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1.hasVarArgs !== s2.hasVarArgs) { + return false; + } + + if (s1.nonOptionalParamCount !== s2.nonOptionalParamCount) { + return false; + } + + if (s1.parameters.length !== s2.parameters.length) { + return false; + } + + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var typeParametersParametersAndReturnTypesAreIdentical = this.signatureTypeParametersParametersAndReturnTypesAreIdentical(s1, s2, context, includingReturnType); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + return typeParametersParametersAndReturnTypesAreIdentical; + }; + + PullTypeResolver.prototype.signatureTypeParametersParametersAndReturnTypesAreIdentical = function (s1, s2, context, includingReturnType) { + if (!this.typeParametersAreIdenticalWorker(s1.getTypeParameters(), s2.getTypeParameters(), context)) { + return false; + } + + if (includingReturnType) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2); + context.walkReturnTypes(); + var areReturnTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + context.postWalkReturnTypes(); + if (!areReturnTypesIdentical) { + return false; + } + } + + var s1Params = s1.parameters; + var s2Params = s2.parameters; + + for (var iParam = 0; iParam < s1Params.length; iParam++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1Params[iParam]); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2Params[iParam]); + context.walkParameterTypes(iParam); + var areParameterTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1Params[iParam].type, s2Params[iParam].type, context); + context.postWalkParameterTypes(); + + if (!areParameterTypesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureReturnTypesAreIdentical = function (s1, s2, context) { + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(s1, s2); + context.walkReturnTypes(); + var returnTypeIsIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + + context.setEnclosingTypeWalkers(enclosingWalkers); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + + return returnTypeIsIdentical; }; PullTypeResolver.prototype.symbolsShareDeclaration = function (symbol1, symbol2) { @@ -46531,58 +47919,7 @@ var TypeScript; var decls2 = symbol2.getDeclarations(); if (decls1.length && decls2.length) { - return decls1[0].isEqual(decls2[0]); - } - - return false; - }; - - PullTypeResolver.prototype.sourceExtendsTarget = function (source, target, context) { - if (source.isGeneric() != target.isGeneric()) { - return false; - } - - if (source.isTypeReference() && target.isTypeReference()) { - if (source.referencedTypeSymbol.hasBase(target.referencedTypeSymbol)) { - var sourceTypeArguments = source.getTypeArguments(); - var targetTypeArguments = target.getTypeArguments(); - - if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length != targetTypeArguments.length) { - return false; - } - - for (var i = 0; i < targetTypeArguments.length; i++) { - if (!this.sourceExtendsTarget(sourceTypeArguments[i], targetTypeArguments[i], context)) { - return false; - } - } - - return true; - } - } - - if (source.hasBase(target)) { - return true; - } - - if (context.isInBaseTypeResolution() && (source.kind & (16 /* Interface */ | 8 /* Class */)) && (target.kind & (16 /* Interface */ | 8 /* Class */))) { - var sourceDecls = source.getDeclarations(); - var extendsSymbol = null; - - for (var i = 0; i < sourceDecls.length; i++) { - var sourceAST = this.semanticInfoChain.getASTForDecl(sourceDecls[i]); - var extendsClause = TypeScript.getExtendsHeritageClause(sourceAST.heritageClauses); - - if (extendsClause) { - for (var j = 0; j < extendsClause.typeNames.nonSeparatorCount(); j++) { - extendsSymbol = this.semanticInfoChain.getSymbolForAST(extendsClause.typeNames.nonSeparatorAt(j)); - - if (extendsSymbol && (extendsSymbol == target || this.sourceExtendsTarget(extendsSymbol, target, context))) { - return true; - } - } - } - } + return decls1[0] === decls2[0]; } return false; @@ -46592,44 +47929,68 @@ var TypeScript; return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); }; - PullTypeResolver.prototype.sourceMembersAreSubtypeOfTargetMembers = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourceMembersAreRelatableToTargetMembers(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceMembersAreAssignableToTargetMembers = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var areSourceMembersAreAssignableToTargetMembers = this.sourceMembersAreRelatableToTargetMembers(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSourceMembersAreAssignableToTargetMembers; }; - PullTypeResolver.prototype.sourcePropertyIsSubtypeOfTargetProperty = function (source, target, sourceProp, targetProp, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourcePropertyIsAssignableToTargetProperty = function (source, target, sourceProp, targetProp, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var isSourcePropertyIsAssignableToTargetProperty = this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return isSourcePropertyIsAssignableToTargetProperty; }; - PullTypeResolver.prototype.sourceCallSignaturesAreSubtypeOfTargetCallSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceCallSignaturesAreAssignableToTargetCallSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var areSourceCallSignaturesAssignableToTargetCallSignatures = this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSourceCallSignaturesAssignableToTargetCallSignatures; }; - PullTypeResolver.prototype.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceConstructSignaturesAreAssignableToTargetConstructSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var areSourceConstructSignaturesAssignableToTargetConstructSignatures = this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSourceConstructSignaturesAssignableToTargetConstructSignatures; }; - PullTypeResolver.prototype.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceIndexSignaturesAreAssignableToTargetIndexSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(source, target); + var areSourceIndexSignaturesAssignableToTargetIndexSignatures = this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return areSourceIndexSignaturesAssignableToTargetIndexSignatures; }; - PullTypeResolver.prototype.typeIsSubtypeOfFunction = function (source, ast, context) { - if (source.getCallSignatures().length || source.getConstructSignatures().length) { + PullTypeResolver.prototype.typeIsAssignableToFunction = function (source, ast, context) { + if (source.isFunctionType()) { return true; } - return this.cachedFunctionInterfaceType() && this.sourceIsSubtypeOfTarget(source, this.cachedFunctionInterfaceType(), ast, context); + return this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(source, this.cachedFunctionInterfaceType(), ast, context); }; - PullTypeResolver.prototype.signatureIsSubtypeOfTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + context.setEnclosingTypes(s1, s2); + var isSignatureIsAssignableToTarget = this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return isSignatureIsAssignableToTarget; }; PullTypeResolver.prototype.sourceIsAssignableToTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); }; - PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + PullTypeResolver.prototype.sourceIsAssignableToTargetWithNewEnclosingTypes = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTargetWithNewEnclosingTypes(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); }; PullTypeResolver.prototype.getSymbolForRelationshipCheck = function (symbol) { @@ -46640,7 +48001,7 @@ var TypeScript; return symbol; }; - PullTypeResolver.prototype.sourceIsRelatableToTargetInEnclosingTypes = function (source, target, sourceEnclosingType, targetEnclosingType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + PullTypeResolver.prototype.sourceIsRelatableToTargetInEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { source = this.getSymbolForRelationshipCheck(source); target = this.getSymbolForRelationshipCheck(target); @@ -46649,9 +48010,7 @@ var TypeScript; } if (source && target) { - var sourceGenerativeTypeKind = sourceEnclosingType ? source.getGenerativeTypeClassification(sourceEnclosingType) : 0 /* Unknown */; - var targetGenerativeTypeKind = targetEnclosingType ? target.getGenerativeTypeClassification(targetEnclosingType) : 0 /* Unknown */; - if (sourceGenerativeTypeKind == 3 /* InfinitelyExpanding */ || targetGenerativeTypeKind == 3 /* InfinitelyExpanding */) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { return this.infinitelyExpandingSourceTypeIsRelatableToTargetType(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); } } @@ -46659,6 +48018,27 @@ var TypeScript; return this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); }; + PullTypeResolver.prototype.sourceIsRelatableToTargetWithNewEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingWalkers = context.resetEnclosingTypeWalkers(); + var isSourceRelatable = this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkers(enclosingWalkers); + return isSourceRelatable; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInCache = function (source, target, comparisonCache, comparisonInfo) { + var isRelatable = comparisonCache.valueAt(source.pullSymbolID, target.pullSymbolID); + + if (isRelatable) { + return { isRelatable: isRelatable }; + } + + if (isRelatable != undefined && !comparisonInfo) { + return { isRelatable: isRelatable }; + } + + return null; + }; + PullTypeResolver.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { source = this.getSymbolForRelationshipCheck(source); target = this.getSymbolForRelationshipCheck(target); @@ -46671,25 +48051,11 @@ var TypeScript; return true; } - var sourceSubstitution = source; + var sourceApparentType = this.getApparentType(source); - if (source == this.semanticInfoChain.stringTypeSymbol && this.cachedStringInterfaceType()) { - this.resolveDeclaredSymbol(this.cachedStringInterfaceType(), context); - sourceSubstitution = this.cachedStringInterfaceType(); - } else if (source == this.semanticInfoChain.numberTypeSymbol && this.cachedNumberInterfaceType()) { - this.resolveDeclaredSymbol(this.cachedNumberInterfaceType(), context); - sourceSubstitution = this.cachedNumberInterfaceType(); - } else if (source == this.semanticInfoChain.booleanTypeSymbol && this.cachedBooleanInterfaceType()) { - this.resolveDeclaredSymbol(this.cachedBooleanInterfaceType(), context); - sourceSubstitution = this.cachedBooleanInterfaceType(); - } else if (TypeScript.PullHelpers.symbolIsEnum(source) && this.cachedNumberInterfaceType()) { - sourceSubstitution = this.cachedNumberInterfaceType(); - } else if (source.isTypeParameter()) { - sourceSubstitution = this.substituteUpperBoundForType(source); - } - - if (comparisonCache.valueAt(source.pullSymbolID, target.pullSymbolID) != undefined) { - return true; + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(source, target, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; } if (source === this.semanticInfoChain.stringTypeSymbol && target.isPrimitive() && target.isStringConstant()) { @@ -46704,10 +48070,10 @@ var TypeScript; if (this.isAnyOrEquivalent(target)) { return true; } + } - if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && source.isStringConstant()) { - return true; - } + if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && source.isStringConstant()) { + return true; } if (source.isPrimitive() && source.isStringConstant() && target.isPrimitive() && target.isStringConstant()) { @@ -46718,18 +48084,18 @@ var TypeScript; return true; } - if ((source === this.semanticInfoChain.nullTypeSymbol) && (target != this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { + if ((source === this.semanticInfoChain.nullTypeSymbol) && (target !== this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { return true; } - if (target == this.semanticInfoChain.voidTypeSymbol) { - if (source == this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { + if (target === this.semanticInfoChain.voidTypeSymbol) { + if (source === this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { return true; } return false; - } else if (source == this.semanticInfoChain.voidTypeSymbol) { - if (target == this.semanticInfoChain.anyTypeSymbol) { + } else if (source === this.semanticInfoChain.voidTypeSymbol) { + if (target === this.semanticInfoChain.anyTypeSymbol) { return true; } @@ -46753,21 +48119,20 @@ var TypeScript; } if (source.getIsSpecialized() && target.getIsSpecialized()) { - if (TypeScript.PullHelpers.getRootType(source) == TypeScript.PullHelpers.getRootType(target)) { + if (TypeScript.PullHelpers.getRootType(source) === TypeScript.PullHelpers.getRootType(target) && TypeScript.PullHelpers.getRootType(source).isNamedTypeSymbol()) { var sourceTypeArguments = source.getTypeArguments(); var targetTypeArguments = target.getTypeArguments(); if (sourceTypeArguments && targetTypeArguments) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, false); + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); for (var i = 0; i < sourceTypeArguments.length; i++) { - if (!this.sourceIsRelatableToTarget(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + if (!this.sourceIsRelatableToTargetWithNewEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, null, isComparingInstantiatedSignatures)) { break; } } - if (i == sourceTypeArguments.length) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + if (i === sourceTypeArguments.length) { return true; } else { comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); @@ -46776,57 +48141,75 @@ var TypeScript; } } - if (sourceSubstitution.isPrimitive() || target.isPrimitive()) { - return false; - } - if (target.isTypeParameter()) { - if (source.isTypeParameter() && (source === sourceSubstitution)) { - return this.typesAreIdentical(target, source); + if (source.isTypeParameter()) { + if (!source.getConstraint()) { + return this.typesAreIdentical(target, source, context); + } else { + return this.isSourceTypeParameterConstrainedToTargetTypeParameter(source, target); + } } else { if (isComparingInstantiatedSignatures) { - target = this.substituteUpperBoundForType(target); + target = target.getBaseConstraint(this.semanticInfoChain); } else { - return this.typesAreIdentical(target, sourceSubstitution); + return this.typesAreIdentical(target, sourceApparentType, context); } } } - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, false); - - if ((source.kind & 8216 /* SomeInstantiatableType */) && (target.kind & 8216 /* SomeInstantiatableType */) && this.sourceExtendsTarget(source, target, context)) { - return true; - } - - if (this.cachedObjectInterfaceType() && target === this.cachedObjectInterfaceType()) { - return true; - } - - if (this.cachedFunctionInterfaceType() && (sourceSubstitution.getCallSignatures().length || sourceSubstitution.getConstructSignatures().length) && target.hasBase(this.cachedFunctionInterfaceType())) { - return true; - } - - if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); - return false; - } - - if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); - return false; - } - - if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); - return false; - } - - if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { - comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); + if (sourceApparentType.isPrimitive() || target.isPrimitive()) { return false; } comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(sourceApparentType, target); + + var needsSourceSubstitutionUpdate = source != sourceApparentType && context.enclosingTypeWalker1._canWalkStructure() && context.enclosingTypeWalker1._getCurrentSymbol() != sourceApparentType; + if (needsSourceSubstitutionUpdate) { + context.enclosingTypeWalker1.setCurrentSymbol(sourceApparentType); + } + + var isRelatable = this.sourceIsRelatableToTargetWorker(source, target, sourceApparentType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + + if (needsSourceSubstitutionUpdate) { + context.enclosingTypeWalker1.setCurrentSymbol(source); + } + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.isSourceTypeParameterConstrainedToTargetTypeParameter = function (source, target) { + var current = source; + while (current && current.isTypeParameter()) { + if (current === target) { + return true; + } + + current = current.getConstraint(); + } + return false; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWorker = function (source, target, sourceSubstitution, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(sourceSubstitution, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + return true; }; @@ -46835,38 +48218,23 @@ var TypeScript; for (var itargetProp = 0; itargetProp < targetProps.length; itargetProp++) { var targetProp = targetProps[itargetProp]; - var sourceProp = this.getMemberSymbol(targetProp.name, 68147712 /* SomeValue */, source); + + var sourceProp = this._getNamedPropertySymbolOfAugmentedType(targetProp.name, source); this.resolveDeclaredSymbol(targetProp, context); var targetPropType = targetProp.type; - if (sourceProp && sourceProp.anyDeclHasFlag(16 /* Static */) && source.isClass()) { - sourceProp = null; - } - if (!sourceProp) { - if (this.cachedObjectInterfaceType()) { - sourceProp = this.getMemberSymbol(targetProp.name, 68147712 /* SomeValue */, this.cachedObjectInterfaceType()); - } - - if (!sourceProp) { - if (this.cachedFunctionInterfaceType() && (targetPropType.getCallSignatures().length || targetPropType.getConstructSignatures().length)) { - sourceProp = this.getMemberSymbol(targetProp.name, 68147712 /* SomeValue */, this.cachedFunctionInterfaceType()); - } - - if (!sourceProp) { - if (!(targetProp.isOptional)) { - if (comparisonInfo) { - var enclosingSymbol = this.getEnclosingSymbolForAST(ast); - comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_is_missing_property_1_from_type_2, [source.toString(enclosingSymbol), targetProp.getScopedNameEx().toString(), target.toString(enclosingSymbol)])); - } - return false; - } - continue; + if (!(targetProp.isOptional)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_is_missing_property_1_from_type_2, [source.toString(enclosingSymbol), targetProp.getScopedNameEx().toString(), target.toString(enclosingSymbol)])); } + return false; } + continue; } if (!this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { @@ -46878,18 +48246,18 @@ var TypeScript; }; PullTypeResolver.prototype.infinitelyExpandingSourceTypeIsRelatableToTargetType = function (sourceType, targetType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - var widenedTargetType = this.widenType(targetType); - var widenedSourceType = this.widenType(sourceType); + var widenedTargetType = targetType.widenedType(this, null, context); + var widenedSourceType = sourceType.widenedType(this, null, context); - if ((widenedSourceType != this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType != this.semanticInfoChain.anyTypeSymbol)) { + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); - if (sourceTypeNamedTypeReference != targetTypeNamedTypeReference) { + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); if (comparisonInfo) { var enclosingSymbol = this.getEnclosingSymbolForAST(ast); - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_inifinitely_expanding_type_reference_do_not_refer_to_same_named_type, [sourceType.getScopedNameEx(enclosingSymbol).toString(), targetType.toString(enclosingSymbol)])); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type, [sourceType.getScopedNameEx(enclosingSymbol).toString(), targetType.toString(enclosingSymbol)])); } return false; } @@ -46902,11 +48270,11 @@ var TypeScript; return true; } - if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length != targetTypeArguments.length) { + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); if (comparisonInfo) { var enclosingSymbol = this.getEnclosingSymbolForAST(ast); - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)])); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)])); } return false; } @@ -46915,35 +48283,41 @@ var TypeScript; if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { comparisonInfoTypeArgumentsCheck = new TypeComparisonInfo(comparisonInfo); } - for (var i = 0; i < sourceTypeArguments.length; i++) { - if (!this.sourceIsRelatableToTarget(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + var isRelatable = true; + for (var i = 0; i < sourceTypeArguments.length && isRelatable; i++) { + context.walkTypeArgument(i); + + if (!this.sourceIsRelatableToTargetInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfoTypeArgumentsCheck, isComparingInstantiatedSignatures)) { + isRelatable = false; if (comparisonInfo) { var message; var enclosingSymbol = this.getEnclosingSymbolForAST(ast); if (comparisonInfoTypeArgumentsCheck && comparisonInfoTypeArgumentsCheck.message) { - message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol), comparisonInfoTypeArgumentsCheck.message]); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol), comparisonInfoTypeArgumentsCheck.message]); } else { - message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_inifinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)]); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)]); } comparisonInfo.addMessage(message); } } + + context.postWalkTypeArgument(); } } - comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); - return true; + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, isRelatable); + return isRelatable; }; - PullTypeResolver.prototype.infinitelyExpandingTypesAreIdentical = function (sourceType, targetType) { - var widenedTargetType = this.widenType(targetType); - var widenedSourceType = this.widenType(sourceType); + PullTypeResolver.prototype.infinitelyExpandingTypesAreIdentical = function (sourceType, targetType, context) { + var widenedTargetType = targetType.widenedType(this, null, null); + var widenedSourceType = sourceType.widenedType(this, null, null); - if ((widenedSourceType != this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType != this.semanticInfoChain.anyTypeSymbol)) { + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); - if (sourceTypeNamedTypeReference != targetTypeNamedTypeReference) { + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); return false; } @@ -46956,13 +48330,17 @@ var TypeScript; return true; } - if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length != targetTypeArguments.length) { + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); return false; } for (var i = 0; i < sourceTypeArguments.length; i++) { - if (!this.typesAreIdentical(sourceTypeArguments[i], targetTypeArguments[i])) { + context.walkTypeArgument(i); + var areIdentical = this.typesAreIdenticalInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], context); + context.postWalkTypeArgument(); + + if (!areIdentical) { this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); return false; } @@ -46974,17 +48352,37 @@ var TypeScript; }; PullTypeResolver.prototype.sourcePropertyIsRelatableToTargetProperty = function (source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceAndTargetAreConstructors = source.isConstructor() && target.isConstructor(); + + var getNames = function (takeTypesFromPropertyContainers) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(ast); + var sourceType = takeTypesFromPropertyContainers ? sourceProp.getContainer() : source; + var targetType = takeTypesFromPropertyContainers ? targetProp.getContainer() : target; + if (sourceAndTargetAreConstructors) { + sourceType = sourceType.getAssociatedContainerType(); + targetType = targetType.getAssociatedContainerType(); + } + return { + propertyName: targetProp.getScopedNameEx().toString(), + sourceTypeName: sourceType.toString(enclosingSymbol), + targetTypeName: targetType.toString(enclosingSymbol) + }; + }; + var targetPropIsPrivate = targetProp.anyDeclHasFlag(2 /* Private */); var sourcePropIsPrivate = sourceProp.anyDeclHasFlag(2 /* Private */); - if (targetPropIsPrivate != sourcePropIsPrivate) { + if (targetPropIsPrivate !== sourcePropIsPrivate) { if (comparisonInfo) { - var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var names = getNames(true); + var code; if (targetPropIsPrivate) { - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(enclosingSymbol), targetProp.getContainer().toString(enclosingSymbol)])); + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2; } else { - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(enclosingSymbol), targetProp.getContainer().toString(enclosingSymbol)])); + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2; } + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName])); comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; } return false; @@ -46992,12 +48390,13 @@ var TypeScript; var targetDecl = targetProp.getDeclarations()[0]; var sourceDecl = sourceProp.getDeclarations()[0]; - if (!targetDecl.isEqual(sourceDecl)) { + if (targetDecl !== sourceDecl) { if (comparisonInfo) { - var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var names = getNames(true); comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_define_property_2_as_private, [sourceProp.getContainer().toString(enclosingSymbol), targetProp.getContainer().toString(enclosingSymbol), targetProp.getScopedNameEx().toString()])); + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_0_and_1_define_static_property_2_as_private : TypeScript.DiagnosticCode.Types_0_and_1_define_property_2_as_private; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.sourceTypeName, names.targetTypeName, names.propertyName])); } return false; @@ -47006,9 +48405,9 @@ var TypeScript; if (sourceProp.isOptional && !targetProp.isOptional) { if (comparisonInfo) { - var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var names = getNames(true); comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2, [targetProp.getScopedNameEx().toString(), sourceProp.getContainer().toString(enclosingSymbol), targetProp.getContainer().toString(enclosingSymbol)])); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2, [names.propertyName, names.sourceTypeName, names.targetTypeName])); } return false; } @@ -47018,8 +48417,9 @@ var TypeScript; var sourcePropType = sourceProp.type; var targetPropType = targetProp.type; - if (comparisonCache.valueAt(sourcePropType.pullSymbolID, targetPropType.pullSymbolID)) { - return true; + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourcePropType, targetPropType, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; } var comparisonInfoPropertyTypeCheck = null; @@ -47027,23 +48427,26 @@ var TypeScript; comparisonInfoPropertyTypeCheck = new TypeComparisonInfo(comparisonInfo); } - if (this.sourceIsRelatableToTargetInEnclosingTypes(sourcePropType, targetPropType, source, target, assignableTo, comparisonCache, ast, context, comparisonInfoPropertyTypeCheck, isComparingInstantiatedSignatures)) { - return true; - } + context.walkMemberTypes(targetProp.name); + var isSourcePropertyRelatableToTargetProperty = this.sourceIsRelatableToTargetInEnclosingTypes(sourcePropType, targetPropType, assignableTo, comparisonCache, ast, context, comparisonInfoPropertyTypeCheck, isComparingInstantiatedSignatures); + context.postWalkMemberTypes(); - if (comparisonInfo) { + if (!isSourcePropertyRelatableToTargetProperty && comparisonInfo) { var enclosingSymbol = this.getEnclosingSymbolForAST(ast); comparisonInfo.flags |= 32 /* IncompatiblePropertyTypes */; var message; + var names = getNames(false); if (comparisonInfoPropertyTypeCheck && comparisonInfoPropertyTypeCheck.message) { - message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3, [targetProp.getScopedNameEx().toString(), source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoPropertyTypeCheck.message]); + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3 : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName, comparisonInfoPropertyTypeCheck.message]); } else { - message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible, [targetProp.getScopedNameEx().toString(), source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName]); } comparisonInfo.addMessage(message); } - return false; + return isSourcePropertyRelatableToTargetProperty; }; PullTypeResolver.prototype.sourceCallSignaturesAreRelatableToTargetCallSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { @@ -47056,7 +48459,7 @@ var TypeScript; } var sourceCallSigs = source.getCallSignatures(); - if (!this.signatureGroupIsRelatableToTarget(sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { if (comparisonInfo) { var message; var enclosingSymbol = this.getEnclosingSymbolForAST(ast); @@ -47090,7 +48493,7 @@ var TypeScript; } var sourceConstructSigs = source.getConstructSignatures(); - if (!this.signatureGroupIsRelatableToTarget(sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { if (comparisonInfo) { var enclosingSymbol = this.getEnclosingSymbolForAST(ast); var message; @@ -47116,12 +48519,13 @@ var TypeScript; }; PullTypeResolver.prototype.sourceIndexSignaturesAreRelatableToTargetIndexSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { - var targetIndexSigs = this.getBothKindsOfIndexSignatures(target, context); + var targetIndexSigs = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(target, context); var targetStringSig = targetIndexSigs.stringSignature; var targetNumberSig = targetIndexSigs.numericSignature; if (targetStringSig || targetNumberSig) { - var sourceIndexSigs = this.getBothKindsOfIndexSignatures(source, context); + var sourceIndexSigs = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(source, context); + var enclosingTypeIndexSigs = context.getBothKindOfIndexSignatures(true, false); var sourceStringSig = sourceIndexSigs.stringSignature; var sourceNumberSig = sourceIndexSigs.numericSignature; @@ -47133,7 +48537,9 @@ var TypeScript; if (targetStringSig) { if (sourceStringSig) { - comparable = this.signatureIsAssignableToTarget(sourceStringSig, targetStringSig, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, true); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetStringSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); } else { comparable = false; } @@ -47141,9 +48547,13 @@ var TypeScript; if (comparable && targetNumberSig) { if (sourceNumberSig) { - comparable = this.signatureIsAssignableToTarget(sourceNumberSig, targetNumberSig, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, false, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceNumberSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); } else if (sourceStringSig) { - comparable = this.sourceIsAssignableToTarget(sourceStringSig.returnType, targetNumberSig.returnType, ast, context, comparisonInfoSignatuesTypeCheck); + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); } else { comparable = false; } @@ -47168,7 +48578,7 @@ var TypeScript; return true; }; - PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (source, target, sourceSG, targetSG, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { if (sourceSG === targetSG) { return true; } @@ -47177,27 +48587,37 @@ var TypeScript; return false; } - var mSig = null; - var nSig = null; var foundMatch = false; var targetExcludeDefinition = targetSG.length > 1; var sourceExcludeDefinition = sourceSG.length > 1; + var sigsCompared = 0; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo, true); + comparisonInfoSignatuesTypeCheck.message = comparisonInfo.message; + } for (var iMSig = 0; iMSig < targetSG.length; iMSig++) { - mSig = targetSG[iMSig]; + var mSig = targetSG[iMSig]; if (mSig.isStringConstantOverloadSignature() || (targetExcludeDefinition && mSig.isDefinition())) { continue; } for (var iNSig = 0; iNSig < sourceSG.length; iNSig++) { - nSig = sourceSG[iNSig]; + var nSig = sourceSG[iNSig]; if (nSig.isStringConstantOverloadSignature() || (sourceExcludeDefinition && nSig.isDefinition())) { continue; } - if (this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + context.walkSignatures(nSig.kind, iNSig, iMSig); + var isSignatureRelatableToTarget = this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, ast, context, sigsCompared == 0 ? comparisonInfoSignatuesTypeCheck : null, isComparingInstantiatedSignatures); + context.postWalkSignatures(); + + sigsCompared++; + + if (isSignatureRelatableToTarget) { foundMatch = true; break; } @@ -47207,6 +48627,11 @@ var TypeScript; foundMatch = false; continue; } + + if (comparisonInfo && sigsCompared == 1) { + comparisonInfo.message = comparisonInfoSignatuesTypeCheck.message; + } + return false; } @@ -47214,6 +48639,19 @@ var TypeScript; }; PullTypeResolver.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourceSig, targetSig, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, true); + var isRelatable = this.signatureIsRelatableToTargetWorker(sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTargetWorker = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; var sourceParameters = sourceSig.parameters; var targetParameters = targetSig.parameters; @@ -47221,43 +48659,37 @@ var TypeScript; return false; } - var targetVarArgCount = targetSig.nonOptionalParamCount; - var sourceVarArgCount = sourceSig.nonOptionalParamCount; + var targetNonOptionalParamCount = targetSig.nonOptionalParamCount; + var sourceNonOptionalParamCount = sourceSig.nonOptionalParamCount; - if (sourceVarArgCount > targetVarArgCount) { + if (!targetSig.hasVarArgs && sourceNonOptionalParamCount > targetParameters.length) { if (comparisonInfo) { comparisonInfo.flags |= 3 /* SourceSignatureHasTooManyParameters */; - comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signature_expects_0_or_fewer_parameters, [targetVarArgCount])); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signature_expects_0_or_fewer_parameters, [targetParameters.length])); } return false; } - if (sourceSig.isGeneric()) { - var rootSourceSig = sourceSig.getRootSymbol(); - var rootTargetSig = targetSig.getRootSymbol(); - - if (comparisonCache.valueAt(rootSourceSig.pullSymbolID, rootTargetSig.pullSymbolID) != undefined) { - return true; - } - - comparisonCache.setValueAt(rootSourceSig.pullSymbolID, rootTargetSig.pullSymbolID, false); - - sourceSig = this.instantiateSignatureInContext(sourceSig, targetSig, context); - - if (!sourceSig) { - return false; - } else { - sourceParameters = sourceSig.parameters; - } + if (this.signaturesAreIdentical(sourceSig, targetSig, context)) { + return true; } - comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, false); + if (targetSig.isGeneric()) { + targetSig = this.instantiateSignatureToAny(targetSig); + } + + if (sourceSig.isGeneric()) { + sourceSig = this.instantiateSignatureToAny(sourceSig); + } var sourceReturnType = sourceSig.returnType; var targetReturnType = targetSig.returnType; - if (targetReturnType != this.semanticInfoChain.voidTypeSymbol) { - if (!this.sourceIsRelatableToTargetInEnclosingTypes(sourceReturnType, targetReturnType, sourceSig.functionType, targetSig.functionType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + if (targetReturnType !== this.semanticInfoChain.voidTypeSymbol) { + context.walkReturnTypes(); + var returnTypesAreRelatable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceReturnType, targetReturnType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.postWalkReturnTypes(); + if (!returnTypesAreRelatable) { if (comparisonInfo) { comparisonInfo.flags |= 16 /* IncompatibleReturnTypes */; } @@ -47266,51 +48698,24 @@ var TypeScript; } } - var len = (sourceVarArgCount < targetVarArgCount && (sourceSig.hasVarArgs || (sourceParameters.length > sourceVarArgCount))) ? targetVarArgCount : sourceVarArgCount; - - if (!len) { - len = (sourceParameters.length < targetParameters.length) ? sourceParameters.length : targetParameters.length; - } - - var sourceParamType = null; - var targetParamType = null; - var sourceParamName = ""; - var targetParamName = ""; - - for (var iSource = 0, iTarget = 0; iSource < len; iSource++, iTarget++) { - if (iSource < sourceParameters.length && (!sourceSig.hasVarArgs || iSource < sourceVarArgCount)) { - sourceParamType = sourceParameters[iSource].type; - sourceParamName = sourceParameters[iSource].name; - } else if (iSource === sourceVarArgCount) { - sourceParamType = sourceParameters[iSource].type; - if (sourceParamType.isArrayNamedTypeReference()) { - sourceParamType = sourceParamType.getElementType(); - } - sourceParamName = sourceParameters[iSource].name; + return targetSig.forAllCorrespondingParameterTypesInThisAndOtherSignature(sourceSig, function (targetParamType, sourceParamType, iParam) { + context.walkParameterTypes(iParam); + var areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(sourceParamType, targetParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + if (!areParametersRelatable) { + context.swapEnclosingTypeWalkers(); + areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(targetParamType, sourceParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.swapEnclosingTypeWalkers(); } + context.postWalkParameterTypes(); - if (iTarget < targetParameters.length && !targetSig.hasVarArgs && (!targetVarArgCount || (iTarget < targetVarArgCount))) { - targetParamType = targetParameters[iTarget].type; - targetParamName = targetParameters[iTarget].name; - } else if (targetSig.hasVarArgs && iTarget === targetVarArgCount) { - targetParamType = targetParameters[iTarget].type; - - if (targetParamType.isArrayNamedTypeReference()) { - targetParamType = targetParamType.getElementType(); - } - targetParamName = targetParameters[iTarget].name; - } - - if (!(this.sourceIsRelatableToTargetInEnclosingTypes(sourceParamType, targetParamType, sourceSig.functionType, targetSig.functionType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) || this.sourceIsRelatableToTargetInEnclosingTypes(targetParamType, sourceParamType, targetSig.functionType, sourceSig.functionType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures))) { + if (!areParametersRelatable) { if (comparisonInfo) { comparisonInfo.flags |= 64 /* IncompatibleParameterTypes */; } - - return false; } - } - return true; + return areParametersRelatable; + }); }; PullTypeResolver.prototype.resolveOverloads = function (application, group, haveTypeArgumentsAtCallSite, context, diagnostics) { @@ -47324,7 +48729,8 @@ var TypeScript; return false; } - if (haveTypeArgumentsAtCallSite && !signature.isGeneric()) { + var rootSignature = signature.getRootSymbol(); + if (haveTypeArgumentsAtCallSite && !rootSignature.isGeneric()) { return false; } @@ -47423,13 +48829,13 @@ var TypeScript; return 1 /* AssignableButWithProvisionalErrors */; } else if (arg.kind() === 219 /* SimpleArrowFunctionExpression */) { var simpleArrowFunction = arg; - return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, null, TypeScript.Parameters.fromIdentifier(simpleArrowFunction.identifier), null, simpleArrowFunction.block, simpleArrowFunction.expression, argIndex, context, comparisonInfo); + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, null, TypeScript.ASTHelpers.parametersFromIdentifier(simpleArrowFunction.identifier), null, simpleArrowFunction.block, simpleArrowFunction.expression, argIndex, context, comparisonInfo); } else if (arg.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { var arrowFunction = arg; - return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, arrowFunction.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(arrowFunction.callSignature.parameterList), TypeScript.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, argIndex, context, comparisonInfo); + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, argIndex, context, comparisonInfo); } else if (arg.kind() === 222 /* FunctionExpression */) { var functionExpression = arg; - return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, functionExpression.callSignature.typeParameterList, TypeScript.Parameters.fromParameterList(functionExpression.callSignature.parameterList), TypeScript.getType(functionExpression), functionExpression.block, null, argIndex, context, comparisonInfo); + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, functionExpression.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(functionExpression.callSignature.parameterList), TypeScript.ASTHelpers.getType(functionExpression), functionExpression.block, null, argIndex, context, comparisonInfo); } else if (arg.kind() === 215 /* ObjectLiteralExpression */) { return this.overloadIsApplicableForObjectLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); } else if (arg.kind() === 214 /* ArrayLiteralExpression */) { @@ -47444,13 +48850,13 @@ var TypeScript; return 2 /* AssignableWithNoProvisionalErrors */; } - context.pushContextualType(paramType, true, null); + context.pushProvisionalType(paramType); var argSym = this.resolveAnyFunctionExpression(arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, true, context); var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); - context.popContextualType(); + context.popAnyContextualType(); return applicabilityStatus; }; @@ -47460,12 +48866,12 @@ var TypeScript; return 2 /* AssignableWithNoProvisionalErrors */; } - context.pushContextualType(paramType, true, null); + context.pushProvisionalType(paramType); var argSym = this.resolveObjectLiteralExpression(arg, true, context); var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); - context.popContextualType(); + context.popAnyContextualType(); return applicabilityStatus; }; @@ -47475,12 +48881,12 @@ var TypeScript; return 2 /* AssignableWithNoProvisionalErrors */; } - context.pushContextualType(paramType, true, null); + context.pushProvisionalType(paramType); var argSym = this.resolveArrayLiteralExpression(arg, true, context); var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); - context.popContextualType(); + context.popAnyContextualType(); return applicabilityStatus; }; @@ -47516,92 +48922,34 @@ var TypeScript; return 0 /* NotAssignable */; }; - PullTypeResolver.prototype.inferArgumentTypesForSignature = function (signature, argContext, comparisonInfo, context) { - var cxt = null; + PullTypeResolver.prototype.inferArgumentTypesForSignature = function (argContext, comparisonInfo, context) { + var inferenceResultTypes = argContext.inferTypeArguments(); + var typeParameters = argContext.signatureBeingInferred.getTypeParameters(); + TypeScript.Debug.assert(typeParameters.length == inferenceResultTypes.length); - var parameters = signature.parameters; - var typeParameters = signature.getTypeParameters(); - - var parameterType = null; - var argCount = argContext.getInferenceArgumentCount(); - - for (var i = 0; i < typeParameters.length; i++) { - argContext.addInferenceRoot(typeParameters[i]); - } - - for (var i = 0; i < argCount; i++) { - if (i >= parameters.length) { - break; - } - - parameterType = parameters[i].type; - - if (signature.hasVarArgs && (i >= signature.nonOptionalParamCount - 1) && parameterType.isArrayNamedTypeReference()) { - parameterType = parameterType.getElementType(); - } - - var inferenceCandidates = argContext.getInferenceCandidates(); - - if (inferenceCandidates.length) { - for (var j = 0; j < inferenceCandidates.length; j++) { - argContext.resetRelationshipCache(); - var substitutions = inferenceCandidates[j]; - - context.pushContextualType(parameterType, true, substitutions); - - this.relateTypeToTypeParameters(argContext.getArgumentTypeSymbolAtIndex(i, context), parameterType, false, argContext, context); - - cxt = context.popContextualType(); - } - } else { - context.pushContextualType(parameterType, true, []); - - this.relateTypeToTypeParameters(argContext.getArgumentTypeSymbolAtIndex(i, context), parameterType, false, argContext, context); - - cxt = context.popContextualType(); - } - } - - var inferenceResults = argContext.inferArgumentTypes(this, context); - - if (inferenceResults.unfit) { - return null; - } - - var resultTypes = []; - - for (var i = 0; i < typeParameters.length; i++) { - for (var j = 0; j < inferenceResults.results.length; j++) { - if ((inferenceResults.results[j].param == typeParameters[i]) && inferenceResults.results[j].type) { - resultTypes[resultTypes.length] = inferenceResults.results[j].type; - break; + var typeReplacementMapForConstraints = null; + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (typeParameters[i].getConstraint()) { + typeReplacementMapForConstraints = typeReplacementMapForConstraints || TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, inferenceResultTypes); + var associatedConstraint = this.instantiateType(typeParameters[i].getConstraint(), typeReplacementMapForConstraints); + if (!this.sourceIsAssignableToTargetWithNewEnclosingTypes(inferenceResultTypes[i], associatedConstraint, null, context, null, false)) { + inferenceResultTypes[i] = associatedConstraint; } } } - if (!argCount && !resultTypes.length && typeParameters.length) { - for (var i = 0; i < typeParameters.length; i++) { - resultTypes[resultTypes.length] = this.semanticInfoChain.emptyTypeSymbol; - } - } else if (resultTypes.length < typeParameters.length) { - for (var i = resultTypes.length; i < typeParameters.length; i++) { - resultTypes[i] = this.semanticInfoChain.emptyTypeSymbol; - } - } - - var inferringAtCallExpression = argContext.argumentASTs && argContext.argumentASTs.parent && argContext.argumentASTs.parent.kind() === 226 /* ArgumentList */ && (argContext.argumentASTs.parent.parent.kind() === 213 /* InvocationExpression */ || argContext.argumentASTs.parent.parent.kind() === 216 /* ObjectCreationExpression */); - - if (inferringAtCallExpression) { - if (!this.typeParametersAreInScopeAtArgumentList(typeParameters, argContext.argumentASTs)) { - for (var i = 0; i < resultTypes.length; i++) { - if (resultTypes[i].wrapsSomeTypeParameter(argContext.candidateCache)) { - resultTypes[i] = this.semanticInfoChain.emptyTypeSymbol; + if (argContext.isInvocationInferenceContext()) { + var invocationContext = argContext; + if (!this.typeParametersAreInScopeAtArgumentList(typeParameters, invocationContext.argumentASTs)) { + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (inferenceResultTypes[i].wrapsSomeTypeParameter(argContext.candidateCache)) { + inferenceResultTypes[i] = this.semanticInfoChain.anyTypeSymbol; } } } } - return resultTypes; + return inferenceResultTypes; }; PullTypeResolver.prototype.typeParametersAreInScopeAtArgumentList = function (typeParameters, args) { @@ -47610,19 +48958,23 @@ var TypeScript; return enclosingDecl.getParentPath().indexOf(typeParameterParentDecl) > -1; }; - PullTypeResolver.prototype.relateTypeToTypeParametersInEnclosingType = function (expressionType, parameterType, expressionTypeEnclosingType, parameterTypeEnclosingType, shouldFix, argContext, context) { + PullTypeResolver.prototype.relateTypeToTypeParametersInEnclosingType = function (expressionType, parameterType, argContext, context) { if (expressionType && parameterType) { - var expressionTypeGenerativeTypeClassification = expressionTypeEnclosingType ? expressionType.getGenerativeTypeClassification(expressionTypeEnclosingType) : 0 /* Unknown */; - var parameterTypeGenerativeTypeClassification = parameterTypeEnclosingType ? parameterType.getGenerativeTypeClassification(parameterTypeEnclosingType) : 0 /* Unknown */; - if (expressionTypeGenerativeTypeClassification == 3 /* InfinitelyExpanding */ || parameterTypeGenerativeTypeClassification == 3 /* InfinitelyExpanding */) { - this.relateInifinitelyExpandingTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + this.relateInifinitelyExpandingTypeToTypeParameters(expressionType, parameterType, argContext, context); return; } } - this.relateTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); }; - PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, shouldFix, argContext, context) { + PullTypeResolver.prototype.relateTypeToTypeParametersWithNewEnclosingTypes = function (expressionType, parameterType, argContext, context) { + var enclosingTypeWalkers = context.resetEnclosingTypeWalkers(); + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.setEnclosingTypeWalkers(enclosingTypeWalkers); + }; + + PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { if (!expressionType || !parameterType) { return; } @@ -47632,82 +48984,73 @@ var TypeScript; } if (parameterType.isTypeParameter()) { - argContext.addCandidateForInference(parameterType, expressionType, shouldFix); + var typeParameter = parameterType; + argContext.addCandidateForInference(typeParameter, expressionType); return; } - var parameterDeclarations = parameterType.getDeclarations(); - var expressionDeclarations = expressionType.getDeclarations(); - - if (!parameterType.isArrayNamedTypeReference() && parameterDeclarations.length && expressionDeclarations.length && !(parameterType.isTypeParameter() || expressionType.isTypeParameter()) && (parameterDeclarations[0].isEqual(expressionDeclarations[0]) || (expressionType.isGeneric() && parameterType.isGeneric() && this.sourceIsSubtypeOfTarget(this.instantiateTypeToAny(expressionType, context), this.instantiateTypeToAny(parameterType, context), null, context, null))) && expressionType.isGeneric()) { - this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); - } - - if (expressionType.isArrayNamedTypeReference() && parameterType.isArrayNamedTypeReference()) { - this.relateArrayTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); - + if (parameterType.isNamedTypeSymbol() && !parameterType.isGeneric() && !parameterType.getTypeArguments()) { return; } - this.relateObjectTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); - }; - - PullTypeResolver.prototype.relateTypeArgumentsOfTypeToTypeParameters = function (expressionType, parameterType, shouldFix, argContext, context) { - var typeParameters = parameterType.getTypeArgumentsOrTypeParameters(); - var typeArguments = expressionType.getTypeArguments(); - - if (!typeArguments) { - typeParameters = parameterType.getTypeArguments(); - typeArguments = expressionType.getTypeArgumentsOrTypeParameters(); - } - - if (typeParameters && typeArguments && typeParameters.length === typeArguments.length) { - for (var i = 0; i < typeParameters.length; i++) { - if (typeArguments[i] != typeParameters[i]) { - this.relateTypeToTypeParameters(typeArguments[i], typeParameters[i], true, argContext, context); - } - } + if (TypeScript.PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType(expressionType, parameterType)) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } else { + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(expressionType, parameterType); + this.relateObjectTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); } }; - PullTypeResolver.prototype.relateInifinitelyExpandingTypeToTypeParameters = function (expressionType, parameterType, shouldFix, argContext, context) { + PullTypeResolver.prototype.relateTypeArgumentsOfTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + var parameterSideTypeArguments = parameterType.getTypeArguments(); + var argumentSideTypeArguments = expressionType.getTypeArguments(); + + TypeScript.Debug.assert(parameterSideTypeArguments && argumentSideTypeArguments && parameterSideTypeArguments.length === argumentSideTypeArguments.length); + for (var i = 0; i < parameterSideTypeArguments.length; i++) { + this.relateTypeToTypeParametersWithNewEnclosingTypes(argumentSideTypeArguments[i], parameterSideTypeArguments[i], argContext, context); + } + }; + + PullTypeResolver.prototype.relateInifinitelyExpandingTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { if (!expressionType || !parameterType) { return; } var expressionTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(expressionType); var parameterTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(parameterType); - if (expressionTypeNamedTypeReference != parameterTypeNamedTypeReference) { + if (expressionTypeNamedTypeReference !== parameterTypeNamedTypeReference) { return; } var expressionTypeTypeArguments = expressionType.getTypeArguments(); - var parameterTypeParameters = parameterType.getTypeParameters(); + var parameterTypeArguments = parameterType.getTypeArguments(); - if (expressionTypeTypeArguments && parameterTypeParameters && expressionTypeTypeArguments.length === parameterTypeParameters.length) { + if (expressionTypeTypeArguments && parameterTypeArguments && expressionTypeTypeArguments.length === parameterTypeArguments.length) { for (var i = 0; i < expressionTypeTypeArguments.length; i++) { - this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, shouldFix, argContext, context); + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); } } }; PullTypeResolver.prototype.relateFunctionSignatureToTypeParameters = function (expressionSignature, parameterSignature, argContext, context) { - var expressionParams = expressionSignature.parameters; + var _this = this; var expressionReturnType = expressionSignature.returnType; - - var parameterParams = parameterSignature.parameters; var parameterReturnType = parameterSignature.returnType; - var len = parameterParams.length < expressionParams.length ? parameterParams.length : expressionParams.length; + parameterSignature.forAllCorrespondingParameterTypesInThisAndOtherSignature(expressionSignature, function (parameterSignatureParameterType, expressionSignatureParameterType, i) { + context.walkParameterTypes(i); + _this.relateTypeToTypeParametersInEnclosingType(expressionSignatureParameterType, parameterSignatureParameterType, argContext, context); + context.postWalkParameterTypes(); + return true; + }); - for (var i = 0; i < len; i++) { - this.relateTypeToTypeParametersInEnclosingType(expressionParams[i].type, parameterParams[i].type, expressionSignature.functionType, parameterSignature.functionType, true, argContext, context); - } - - this.relateTypeToTypeParametersInEnclosingType(expressionReturnType, parameterReturnType, expressionSignature.functionType, parameterSignature.functionType, false, argContext, context); + context.walkReturnTypes(); + this.relateTypeToTypeParametersInEnclosingType(expressionReturnType, parameterReturnType, argContext, context); + context.postWalkReturnTypes(); }; - PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, shouldFix, argContext, context) { + PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, argContext, context) { var parameterTypeMembers = parameterType.getMembers(); var parameterSignatures; @@ -47718,58 +49061,98 @@ var TypeScript; return; } - var objectTypeArguments = objectType.getTypeArguments(); - var parameterTypeParameters = parameterType.getTypeParameters(); - - if (objectTypeArguments) { - if (objectTypeArguments.length === parameterTypeParameters.length) { - for (var i = 0; i < objectTypeArguments.length; i++) { - argContext.addCandidateForInference(parameterTypeParameters[i], objectTypeArguments[i], shouldFix); - } - } else if (parameterType == this.semanticInfoChain.anyTypeSymbol) { - for (var i = 0; i < objectTypeArguments.length; i++) { - this.relateTypeToTypeParameters(parameterType, objectTypeArguments[i], shouldFix, argContext, context); - } - } - } - for (var i = 0; i < parameterTypeMembers.length; i++) { - objectMember = this.getMemberSymbol(parameterTypeMembers[i].name, 68147712 /* SomeValue */, objectType); + objectMember = this.getNamedPropertySymbol(parameterTypeMembers[i].name, 68147712 /* SomeValue */, objectType); if (objectMember) { - this.relateTypeToTypeParametersInEnclosingType(objectMember.type, parameterTypeMembers[i].type, objectType, parameterType, shouldFix, argContext, context); + this.resolveDeclaredSymbol(objectMember); + this.resolveDeclaredSymbol(parameterTypeMembers[i]); + context.walkMemberTypes(parameterTypeMembers[i].name); + this.relateTypeToTypeParametersInEnclosingType(objectMember.type, parameterTypeMembers[i].type, argContext, context); + context.postWalkMemberTypes(); } } - parameterSignatures = parameterType.getCallSignatures(); - objectSignatures = objectType.getCallSignatures(); + this.relateSignatureGroupToTypeParameters(objectType.getCallSignatures(), parameterType.getCallSignatures(), 1048576 /* CallSignature */, argContext, context); - if ((parameterSignatures.length == 1) && (objectSignatures.length == 1) && !objectSignatures[0].isGeneric() && (parameterSignatures[0].nonOptionalParamCount >= objectSignatures[0].nonOptionalParamCount)) { - this.relateFunctionSignatureToTypeParameters(objectSignatures[0], parameterSignatures[0], argContext, context); - } + this.relateSignatureGroupToTypeParameters(objectType.getConstructSignatures(), parameterType.getConstructSignatures(), 2097152 /* ConstructSignature */, argContext, context); - parameterSignatures = parameterType.getConstructSignatures(); - objectSignatures = objectType.getConstructSignatures(); - - if ((parameterSignatures.length == 1) && (objectSignatures.length == 1) && !objectSignatures[0].isGeneric() && (parameterSignatures[0].nonOptionalParamCount >= objectSignatures[0].nonOptionalParamCount)) { - this.relateFunctionSignatureToTypeParameters(objectSignatures[0], parameterSignatures[0], argContext, context); - } - - var parameterIndexSignatures = this.getBothKindsOfIndexSignatures(parameterType, context); - var objectIndexSignatures = this.getBothKindsOfIndexSignatures(objectType, context); + var parameterIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parameterType, context); + var objectIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(objectType, context); + var indexSigInfo = context.getBothKindOfIndexSignatures(false, false); if (parameterIndexSignatures.stringSignature && objectIndexSignatures.stringSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, true, true, true); this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.stringSignature, parameterIndexSignatures.stringSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); } if (parameterIndexSignatures.numericSignature && objectIndexSignatures.numericSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, false, false, true); this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.numericSignature, parameterIndexSignatures.numericSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); } }; - PullTypeResolver.prototype.relateArrayTypeToTypeParameters = function (argArrayType, parameterArrayType, shouldFix, argContext, context) { - var argElement = argArrayType.getElementType(); - var paramElement = parameterArrayType.getElementType(); + PullTypeResolver.prototype.relateSignatureGroupToTypeParameters = function (argumentSignatures, parameterSignatures, signatureKind, argContext, context) { + for (var i = 0; i < parameterSignatures.length; i++) { + var paramSignature = parameterSignatures[i]; + if (argumentSignatures.length > 0 && paramSignature.isGeneric()) { + paramSignature = this.instantiateSignatureToAny(paramSignature); + } + for (var j = 0; j < argumentSignatures.length; j++) { + var argumentSignature = argumentSignatures[j]; + if (argumentSignature.nonOptionalParamCount > paramSignature.nonOptionalParamCount) { + continue; + } - this.relateTypeToTypeParameters(argElement, paramElement, shouldFix, argContext, context); + if (argumentSignature.isGeneric()) { + argumentSignature = this.instantiateSignatureToAny(argumentSignature); + } + + context.walkSignatures(signatureKind, j, i); + this.relateFunctionSignatureToTypeParameters(argumentSignature, paramSignature, argContext, context); + context.postWalkSignatures(); + } + } + }; + + PullTypeResolver.prototype.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference = function (expressionSymbol, context) { + var inferentialType = context.getContextualType(); + TypeScript.Debug.assert(inferentialType); + var expressionType = expressionSymbol.type; + if (this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(expressionType, true) && this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(inferentialType, false)) { + var genericExpressionSignature = expressionType.getCallSignatures()[0]; + var contextualSignature = inferentialType.getCallSignatures()[0]; + + var instantiatedSignature = this.instantiateSignatureInContext(genericExpressionSignature, contextualSignature, context, true); + if (instantiatedSignature === null) { + return expressionSymbol; + } + + var newType = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + newType.appendCallSignature(instantiatedSignature); + return newType; + } + + return expressionSymbol; + }; + + PullTypeResolver.prototype.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers = function (type, callSignatureShouldBeGeneric) { + TypeScript.Debug.assert(type); + if (type.getCallSignatures().length !== 1) { + return false; + } + + var callSignatureIsGeneric = type.getCallSignatures()[0].isGeneric(); + if (callSignatureIsGeneric !== callSignatureShouldBeGeneric) { + return false; + } + + var typeHasOtherMembers = type.getConstructSignatures().length || type.getIndexSignatures().length || type.getAllMembers(68147712 /* SomeValue */, 0 /* all */).length; + if (typeHasOtherMembers) { + return false; + } + + return true; }; PullTypeResolver.prototype.instantiateTypeToAny = function (typeToSpecialize, context) { @@ -47806,6 +49189,32 @@ var TypeScript; return type; }; + PullTypeResolver.prototype.instantiateSignatureToAny = function (signature) { + var typeParameters = signature.getTypeParameters(); + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + var typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var typeParameterArgumentMap = TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, typeArguments); + return this.instantiateSignature(signature, typeParameterArgumentMap); + }; + PullTypeResolver.typeCheck = function (compilationSettings, semanticInfoChain, document) { var sourceUnit = document.sourceUnit(); @@ -47826,66 +49235,23 @@ var TypeScript; }; PullTypeResolver.prototype.validateVariableDeclarationGroups = function (enclosingDecl, context) { - var importDeclarationNames = null; - if (enclosingDecl.kind & (4 /* Container */ | 32 /* DynamicModule */ | 1 /* Script */)) { - var childDecls = enclosingDecl.getChildDecls(); - for (var i = 0, n = childDecls.length; i < n; i++) { - var childDecl = childDecls[i]; - if (childDecl.kind === 128 /* TypeAlias */) { - importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); - importDeclarationNames[childDecl.name] = true; - } - } - } - - var declGroups = enclosingDecl.getVariableDeclGroups(); - - for (var i = 0, i_max = declGroups.length; i < i_max; i++) { - var firstSymbol = null; - var firstSymbolType = null; - - if (enclosingDecl.kind === 1 /* Script */ && declGroups[i].length) { - var name = declGroups[i][0].name; - var candidateSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 512 /* Variable */, enclosingDecl); - if (candidateSymbol && candidateSymbol.isResolved) { - if (!candidateSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */)) { - firstSymbol = candidateSymbol; - firstSymbolType = candidateSymbol.type; - } - } - - var importSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 128 /* TypeAlias */, null); - if (importSymbol && importSymbol.isAlias()) { - importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); - } + var _this = this; + this.scanVariableDeclarationGroups(enclosingDecl, function (_) { + }, function (subsequentDecl, firstSymbol) { + if (TypeScript.hasFlag(subsequentDecl.kind, 2048 /* Parameter */) || TypeScript.hasFlag(subsequentDecl.flags, 8388608 /* PropertyParameter */)) { + return; } - for (var j = 0, j_max = declGroups[i].length; j < j_max; j++) { - var decl = declGroups[i][j]; - var boundDeclAST = this.semanticInfoChain.getASTForDecl(decl); + var boundDeclAST = _this.semanticInfoChain.getASTForDecl(subsequentDecl); - var name = decl.name; + var symbol = subsequentDecl.getSymbol(); + var symbolType = symbol.type; + var firstSymbolType = firstSymbol.type; - if (importDeclarationNames && importDeclarationNames[name]) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Variable_declaration_cannot_have_the_same_name_as_an_import_declaration)); - continue; - } - - var symbol = decl.getSymbol(); - var symbolType = symbol.type; - - if (j === 0 && !firstSymbol) { - firstSymbol = symbol; - firstSymbolType = symbolType; - continue; - } - - if (symbolType && firstSymbolType && symbolType !== firstSymbolType && !this.typesAreIdentical(symbolType, firstSymbolType)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, [symbol.getScopedName(), firstSymbolType.toString(), symbolType.toString()])); - continue; - } + if (symbolType && firstSymbolType && symbolType !== firstSymbolType && !_this.typesAreIdentical(symbolType, firstSymbolType, context)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, [symbol.getScopedName(), firstSymbolType.toString(firstSymbol), symbolType.toString(symbol)])); } - } + }); }; PullTypeResolver.prototype.typeCheckFunctionOverloads = function (funcDecl, context, signature, allSignatures) { @@ -47906,13 +49272,19 @@ var TypeScript; } if (!signature.isDefinition()) { + var signatureParentDecl = signature.getDeclarations()[0].getParentDecl(); for (var i = 0; i < allSignatures.length; i++) { if (allSignatures[i] === signature) { break; } - if (this.signaturesAreIdentical(allSignatures[i], signature, false)) { - if (!this.typesAreIdentical(allSignatures[i].returnType, signature.returnType)) { + var allSignaturesParentDecl = allSignatures[i].getDeclarations()[0].getParentDecl(); + if (allSignaturesParentDecl !== signatureParentDecl) { + continue; + } + + if (this.signaturesAreIdenticalWithNewEnclosingTypes(allSignatures[i], signature, context, false)) { + if (!this.signatureReturnTypesAreIdentical(allSignatures[i], signature, context)) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overloads_cannot_differ_only_by_return_type)); } else if (funcDecl.kind() === 137 /* ConstructorDeclaration */) { context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_constructor_overload_signature)); @@ -47948,17 +49320,17 @@ var TypeScript; continue; } - if (this.signatureIsSubtypeOfTarget(signature, allSignatures[i], null, context)) { + if (this.signatureIsAssignableToTarget(signature, allSignatures[i], null, context)) { foundSubtypeSignature = true; break; } } if (!foundSubtypeSignature) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Specialized_overload_signature_is_not_subtype_of_any_non_specialized_signature)); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature)); } } - } else if (definitionSignature && definitionSignature != signature) { + } else if (definitionSignature && definitionSignature !== signature) { var comparisonInfo = new TypeComparisonInfo(); if (!definitionSignature.isResolved) { @@ -47982,16 +49354,16 @@ var TypeScript; signatureForVisibilityCheck = allSignatures[0]; } - if (funcDecl.kind() !== 137 /* ConstructorDeclaration */ && functionDeclaration.kind !== 2097152 /* ConstructSignature */ && signatureForVisibilityCheck && signature != signatureForVisibilityCheck) { + if (funcDecl.kind() !== 137 /* ConstructorDeclaration */ && functionDeclaration.kind !== 2097152 /* ConstructSignature */ && signatureForVisibilityCheck && signature !== signatureForVisibilityCheck) { var errorCode; - if (signatureForVisibilityCheck.anyDeclHasFlag(2 /* Private */) != signature.anyDeclHasFlag(2 /* Private */)) { + if (signatureForVisibilityCheck.anyDeclHasFlag(2 /* Private */) !== signature.anyDeclHasFlag(2 /* Private */)) { errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_public_or_private; - } else if (signatureForVisibilityCheck.anyDeclHasFlag(1 /* Exported */) != signature.anyDeclHasFlag(1 /* Exported */)) { + } else if (signatureForVisibilityCheck.anyDeclHasFlag(1 /* Exported */) !== signature.anyDeclHasFlag(1 /* Exported */)) { errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_exported_or_not_exported; - } else if (signatureForVisibilityCheck.anyDeclHasFlag(8 /* Ambient */) != signature.anyDeclHasFlag(8 /* Ambient */)) { + } else if (signatureForVisibilityCheck.anyDeclHasFlag(8 /* Ambient */) !== signature.anyDeclHasFlag(8 /* Ambient */)) { errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_ambient_or_non_ambient; - } else if (signatureForVisibilityCheck.anyDeclHasFlag(128 /* Optional */) != signature.anyDeclHasFlag(128 /* Optional */)) { + } else if (signatureForVisibilityCheck.anyDeclHasFlag(128 /* Optional */) !== signature.anyDeclHasFlag(128 /* Optional */)) { errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_optional_or_required; } @@ -48045,7 +49417,7 @@ var TypeScript; this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getCallSignatures(), privacyErrorReporter); this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getConstructSignatures(), privacyErrorReporter); this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getIndexSignatures(), privacyErrorReporter); - } else if (typeSymbol.kind == 8192 /* TypeParameter */) { + } else if (typeSymbol.kind === 8192 /* TypeParameter */) { this.checkSymbolPrivacy(declSymbol, typeSymbol.getConstraint(), privacyErrorReporter); } @@ -48059,27 +49431,27 @@ var TypeScript; if (declSymbol.isExternallyVisible()) { var symbolIsVisible = symbol.isExternallyVisible(); - if (symbolIsVisible && symbol.kind != 8192 /* TypeParameter */) { + if (symbolIsVisible && symbol.kind !== 8192 /* TypeParameter */) { var symbolPath = symbol.pathToRoot(); var declSymbolPath = declSymbol.pathToRoot(); - if (symbolPath[symbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1].kind == 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1] != symbolPath[symbolPath.length - 1]) { + if (symbolPath[symbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1] !== symbolPath[symbolPath.length - 1]) { symbolIsVisible = false; var declSymbolScope = declSymbolPath[declSymbolPath.length - 1]; for (var i = symbolPath.length - 1; i >= 0; i--) { var aliasSymbols = symbolPath[i].getExternalAliasedSymbols(declSymbolScope); if (aliasSymbols) { symbolIsVisible = true; - aliasSymbols[0].setTypeUsedExternally(true); + aliasSymbols[0].setTypeUsedExternally(); break; } } symbol = symbolPath[symbolPath.length - 1]; } - } else if (symbol.kind == 128 /* TypeAlias */) { + } else if (symbol.kind === 128 /* TypeAlias */) { var aliasSymbol = symbol; symbolIsVisible = true; - aliasSymbol.setTypeUsedExternally(true); + aliasSymbol.setTypeUsedExternally(); } if (!symbolIsVisible) { @@ -48111,7 +49483,7 @@ var TypeScript; } }; - PullTypeResolver.prototype.typeParameterOfTypeDeclarationPrivacyErrorReporter = function (classOrInterface, indexOfTypeParameter, typeParameter, symbol, context) { + PullTypeResolver.prototype.typeParameterOfTypeDeclarationPrivacyErrorReporter = function (classOrInterface, typeParameterAST, typeParameter, symbol, context) { var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); var enclosingDecl = this.getEnclosingDecl(decl); var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; @@ -48119,8 +49491,6 @@ var TypeScript; var typeParameters = classOrInterface.kind() === 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; - var typeParameterAST = typeParameters.typeParameters.nonSeparatorAt(indexOfTypeParameter); - var typeSymbol = symbol; var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { @@ -48254,7 +49624,7 @@ var TypeScript; if (functionSymbol && functionSymbol.isType() && !functionSymbol.isNamedTypeSymbol()) { return; } - } else if (functionSymbol.kind == 65536 /* Method */ && !isStatic && !functionSymbol.getContainer().isNamedTypeSymbol()) { + } else if (functionSymbol.kind === 65536 /* Method */ && !isStatic && !functionSymbol.getContainer().isNamedTypeSymbol()) { return; } functionSignature = functionDecl.getSignatureSymbol(); @@ -48659,7 +50029,7 @@ var TypeScript; }; PullTypeResolver.prototype.typeCheckMembersAgainstIndexer = function (containerType, containerTypeDecl, context) { - var indexSignatures = this.getBothKindsOfIndexSignatures(containerType, context); + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(containerType, context); var stringSignature = indexSignatures.stringSignature; var numberSignature = indexSignatures.numericSignature; @@ -48672,7 +50042,7 @@ var TypeScript; var relevantSignature = this.determineRelevantIndexerForMember(memberSymbol, numberSignature, stringSignature); if (relevantSignature) { var comparisonInfo = new TypeComparisonInfo(); - if (!this.sourceIsSubtypeOfTarget(memberSymbol.type, relevantSignature.returnType, member.ast(), context, comparisonInfo)) { + if (!this.sourceIsAssignableToTarget(memberSymbol.type, relevantSignature.returnType, member.ast(), context, comparisonInfo)) { this.reportErrorThatMemberIsNotSubtypeOfIndexer(memberSymbol, relevantSignature, member.ast(), context, comparisonInfo); } } @@ -48695,15 +50065,15 @@ var TypeScript; var enclosingSymbol = this.getEnclosingSymbolForAST(astForError); if (indexSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { if (comparisonInfo.message) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); } else { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_subtypes_of_numeric_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); } } else { if (comparisonInfo.message) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_subtypes_of_string_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); } else { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_subtypes_of_string_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); } } }; @@ -48756,7 +50126,7 @@ var TypeScript; foundError1 = !this.typeCheckIfTypeMemberPropertyOkToOverride(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, enclosingDecl, comparisonInfo); if (!foundError1) { - foundError2 = !this.sourcePropertyIsSubtypeOfTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, classOrInterface, context, comparisonInfo); + foundError2 = !this.sourcePropertyIsAssignableToTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, classOrInterface, context, comparisonInfo); } if (foundError1 || foundError2) { @@ -48767,15 +50137,15 @@ var TypeScript; } if (!foundError && typeSymbol.hasOwnCallSignatures()) { - foundError = !this.sourceCallSignaturesAreSubtypeOfTargetCallSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); } if (!foundError && typeSymbol.hasOwnConstructSignatures()) { - foundError = !this.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); } if (!foundError && typeSymbol.hasOwnIndexSignatures()) { - foundError = !this.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); } if (!foundError && typeSymbol.isClass()) { @@ -48793,17 +50163,7 @@ var TypeScript; this.resolveDeclaredSymbol(extendedConstructorTypeProp, context); } - var typeConstructorTypePropType = typeConstructorTypeMembers[i].type; - var extendedConstructorTypePropType = extendedConstructorTypeProp.type; - if (!this.sourceIsSubtypeOfTarget(typeConstructorTypePropType, extendedConstructorTypePropType, classOrInterface, context, comparisonInfoForPropTypeCheck)) { - var propMessage; - var enclosingSymbol = this.getEnclosingSymbolForAST(classOrInterface); - if (comparisonInfoForPropTypeCheck.message) { - propMessage = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3, [extendedConstructorTypeProp.getScopedNameEx().toString(), typeSymbol.toString(enclosingSymbol), extendedType.toString(enclosingSymbol), comparisonInfoForPropTypeCheck.message]); - } else { - propMessage = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible, [extendedConstructorTypeProp.getScopedNameEx().toString(), typeSymbol.toString(enclosingSymbol), extendedType.toString(enclosingSymbol)]); - } - comparisonInfo.addMessage(propMessage); + if (!this.sourcePropertyIsAssignableToTargetProperty(typeConstructorType, extendedConstructorType, typeConstructorTypeMembers[i], extendedConstructorTypeProp, classOrInterface, context, comparisonInfo)) { foundError = true; break; } @@ -48830,13 +50190,13 @@ var TypeScript; PullTypeResolver.prototype.typeCheckIfClassImplementsType = function (classDecl, classSymbol, implementedType, enclosingDecl, context) { var comparisonInfo = new TypeComparisonInfo(); - var foundError = !this.sourceMembersAreSubtypeOfTargetMembers(classSymbol, implementedType, classDecl, context, comparisonInfo); + var foundError = !this.sourceMembersAreAssignableToTargetMembers(classSymbol, implementedType, classDecl, context, comparisonInfo); if (!foundError) { - foundError = !this.sourceCallSignaturesAreSubtypeOfTargetCallSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); if (!foundError) { - foundError = !this.sourceConstructSignaturesAreSubtypeOfTargetConstructSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); if (!foundError) { - foundError = !this.sourceIndexSignaturesAreSubtypeOfTargetIndexSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); } } } @@ -48847,15 +50207,39 @@ var TypeScript; } }; - PullTypeResolver.prototype.hasClassTypeSymbolConflictAsValue = function (valueDeclAST, typeSymbol, enclosingDecl, context) { + PullTypeResolver.prototype.computeValueSymbolFromAST = function (valueDeclAST, context) { + var prevInTypeCheck = context.inTypeCheck; + context.inTypeCheck = false; + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); - var valueSymbol = this.computeNameExpression(valueDeclAST, context, false); + + if (valueDeclAST.kind() == 11 /* IdentifierName */) { + var valueSymbol = this.computeNameExpression(valueDeclAST, context); + } else { + TypeScript.Debug.assert(valueDeclAST.kind() == 121 /* QualifiedName */); + var qualifiedName = valueDeclAST; + + var lhs = this.computeValueSymbolFromAST(qualifiedName.left, context); + var valueSymbol = this.computeDottedNameExpressionFromLHS(lhs.symbol, qualifiedName.left, qualifiedName.right, context, false); + } var valueSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); this.semanticInfoChain.setAliasSymbolForAST(valueDeclAST, typeSymbolAlias); + context.inTypeCheck = prevInTypeCheck; + + return { symbol: valueSymbol, alias: valueSymbolAlias }; + }; + + PullTypeResolver.prototype.hasClassTypeSymbolConflictAsValue = function (baseDeclAST, typeSymbol, enclosingDecl, context) { + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(baseDeclAST); + + var valueDeclAST = baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST; + var valueSymbolInfo = this.computeValueSymbolFromAST(valueDeclAST, context); + var valueSymbol = valueSymbolInfo.symbol; + var valueSymbolAlias = valueSymbolInfo.alias; if (typeSymbolAlias && valueSymbolAlias) { - return typeSymbolAlias != valueSymbolAlias; + return typeSymbolAlias !== valueSymbolAlias; } if (!valueSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */)) { @@ -48865,7 +50249,7 @@ var TypeScript; var associatedContainerType = valueSymbol.type ? valueSymbol.type.getAssociatedContainerType() : null; if (associatedContainerType) { - return associatedContainerType != typeSymbol.getRootSymbol(); + return associatedContainerType !== typeSymbol.getRootSymbol(); } return true; @@ -48896,9 +50280,9 @@ var TypeScript; } } return; - } else if (typeDeclIsClass && isExtendedType && baseDeclAST.kind() == 11 /* IdentifierName */) { + } else if (typeDeclIsClass && isExtendedType) { if (this.hasClassTypeSymbolConflictAsValue(baseDeclAST, baseType, enclosingDecl, context)) { - context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.Type_reference_0_in_extends_clause_does_not_reference_constructor_function_for_1, [baseDeclAST.text(), baseType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1, [TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST), baseType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); } } @@ -48911,11 +50295,15 @@ var TypeScript; } if (isExtendedType) { - this.typeCheckIfTypeExtendsType(classOrInterface, name, typeSymbol, baseType, enclosingDecl, context); + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfTypeExtendsType(classOrInterface, name, typeSymbol, baseType, enclosingDecl, context); + }); } else { TypeScript.Debug.assert(classOrInterface.kind() === 131 /* ClassDeclaration */); - this.typeCheckIfClassImplementsType(classOrInterface, typeSymbol, baseType, enclosingDecl, context); + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfClassImplementsType(classOrInterface, typeSymbol, baseType, enclosingDecl, context); + }); } this.checkSymbolPrivacy(typeSymbol, baseType, function (errorSymbol) { @@ -48925,14 +50313,12 @@ var TypeScript; PullTypeResolver.prototype.typeCheckBases = function (classOrInterface, name, heritageClauses, typeSymbol, enclosingDecl, context) { var _this = this; - var extendsClause = TypeScript.getExtendsHeritageClause(heritageClauses); - var implementsClause = TypeScript.getImplementsHeritageClause(heritageClauses); + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); if (!extendsClause && !implementsClause) { return; } - var typeDeclIsClass = classOrInterface.kind() === 131 /* ClassDeclaration */; - if (extendsClause) { for (var i = 0; i < extendsClause.typeNames.nonSeparatorCount(); i++) { this.typeCheckBase(classOrInterface, name, typeSymbol, extendsClause.typeNames.nonSeparatorAt(i), true, enclosingDecl, context); @@ -48978,7 +50364,7 @@ var TypeScript; } var baseTypes = typeSymbol.getExtendedTypes(); for (var i = 0; i < baseTypes.length; i++) { - if (this.checkNamedPropertyTypeIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedMembersMap, context) || this.checkIndexSignatureIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedIndexSignatures, typeHasOwnNumberIndexer, typeHasOwnStringIndexer, context)) { + if (this.checkNamedPropertyIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedMembersMap, context) || this.checkIndexSignatureIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedIndexSignatures, typeHasOwnNumberIndexer, typeHasOwnStringIndexer, context)) { return; } } @@ -48990,7 +50376,7 @@ var TypeScript; this.checkInheritedMembersAgainstInheritedIndexSignatures(name, typeSymbol, inheritedIndexSignatures, inheritedMembersMap, context); }; - PullTypeResolver.prototype.checkNamedPropertyTypeIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, inheritedMembersMap, context) { + PullTypeResolver.prototype.checkNamedPropertyIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, inheritedMembersMap, context) { var baseMembers = baseTypeSymbol.getAllMembers(4096 /* Property */ | 65536 /* Method */, 0 /* all */); for (var i = 0; i < baseMembers.length; i++) { var member = baseMembers[i]; @@ -49000,10 +50386,12 @@ var TypeScript; continue; } + this.resolveDeclaredSymbol(member, context); + if (inheritedMembersMap[memberName]) { var prevMember = inheritedMembersMap[memberName]; - if (prevMember.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(member.type, prevMember.memberSymbol.type)) { - var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_not_identical, [memberName, prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + if (prevMember.baseOrigin !== baseTypeSymbol && !this.propertiesAreIdenticalWithNewEnclosingTypes(baseTypeSymbol, prevMember.baseOrigin, member, prevMember.memberSymbol, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Named_properties_0_of_types_1_and_2_are_not_identical, [memberName, prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); return true; } @@ -49025,14 +50413,15 @@ var TypeScript; var currentInheritedSignature = indexSignaturesFromThisBaseType[i]; var parameterTypeIsString = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.stringTypeSymbol; - var parameterTypeIsNumber = !parameterTypeIsString; + var parameterTypeIsNumber = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + if (parameterTypeIsString && derivedTypeHasOwnStringSignature || parameterTypeIsNumber && derivedTypeHasOwnNumberSignature) { continue; } if (parameterTypeIsString) { if (allInheritedSignatures.stringSignatureWithBaseOrigin) { - if (allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.stringSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType)) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.stringSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_string_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); return true; @@ -49042,7 +50431,7 @@ var TypeScript; } } else if (parameterTypeIsNumber) { if (allInheritedSignatures.numberSignatureWithBaseOrigin) { - if (allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.numberSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType)) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.numberSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_number_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); return true; @@ -49082,16 +50471,16 @@ var TypeScript; continue; } - var memberIsSubtype = this.sourceIsSubtypeOfTarget(memberWithBaseOrigin.memberSymbol.type, relevantSignature.returnType, interfaceName, context, comparisonInfo); + var memberIsSubtype = this.sourceIsAssignableToTarget(memberWithBaseOrigin.memberSymbol.type, relevantSignature.returnType, interfaceName, context, comparisonInfo); if (!memberIsSubtype) { var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); if (relevantSignatureIsNumberSignature) { - var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_a_subtype_of_number_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); } else { - var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_a_subtype_of_string_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); } @@ -49109,11 +50498,11 @@ var TypeScript; } var comparisonInfo = new TypeComparisonInfo(); - var signatureIsSubtype = this.sourceIsSubtypeOfTarget(inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature.returnType, inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature.returnType, interfaceName, context, comparisonInfo); + var signatureIsSubtype = this.sourceIsAssignableToTarget(inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature.returnType, inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature.returnType, interfaceName, context, comparisonInfo); if (!signatureIsSubtype) { var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); - var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_number_indexer_in_type_0_is_not_a_subtype_of_string_indexer_type_in_type_1_NL_2, [ + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2, [ inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [ @@ -49159,7 +50548,7 @@ var TypeScript; return false; } - if (astSymbol.kind === 32768 /* ConstructorMethod */) { + if (astSymbol.kind === 32768 /* ConstructorMethod */ || astSymbol.kind === 16384 /* Function */) { return false; } } @@ -49216,8 +50605,7 @@ var TypeScript; return false; }; - PullTypeResolver.prototype.instantiateType = function (type, typeParameterArgumentMap, instantiateFunctionTypeParameters) { - if (typeof instantiateFunctionTypeParameters === "undefined") { instantiateFunctionTypeParameters = false; } + PullTypeResolver.prototype.instantiateType = function (type, typeParameterArgumentMap) { if (type.isPrimitive()) { return type; } @@ -49230,48 +50618,63 @@ var TypeScript; return typeParameterArgumentMap[type.pullSymbolID]; } - if (type.isTypeParameter() && type.isFunctionTypeParameter()) { - return type; + type._resolveDeclaredSymbol(); + if (type.isTypeParameter()) { + return this.instantiateTypeParameter(type, typeParameterArgumentMap); } - type._resolveDeclaredSymbol(); if (type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { - return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap, instantiateFunctionTypeParameters); + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); } return type; }; - PullTypeResolver.prototype.instantiateSignature = function (signature, typeParameterArgumentMap, instantiateFunctionTypeParameters) { - if (typeof instantiateFunctionTypeParameters === "undefined") { instantiateFunctionTypeParameters = false; } + PullTypeResolver.prototype.instantiateTypeParameter = function (typeParameter, typeParameterArgumentMap) { + var constraint = typeParameter.getConstraint(); + if (!constraint) { + return typeParameter; + } + + var instantiatedConstraint = this.instantiateType(constraint, typeParameterArgumentMap); + + if (instantiatedConstraint == constraint) { + return typeParameter; + } + + var rootTypeParameter = typeParameter.getRootSymbol(); + var instantiation = rootTypeParameter.getSpecialization([instantiatedConstraint]); + if (instantiation) { + return instantiation; + } + + instantiation = new TypeScript.PullInstantiatedTypeParameterSymbol(rootTypeParameter, instantiatedConstraint); + return instantiation; + }; + + PullTypeResolver.prototype.instantiateSignature = function (signature, typeParameterArgumentMap) { if (!signature.wrapsSomeTypeParameter(typeParameterArgumentMap)) { return signature; } - var typeArguments = []; + var rootSignature = signature.getRootSymbol(); + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(this, signature, mutableTypeParameterMap); - TypeScript.nSpecializedSignaturesCreated++; - - var instantiatedSignature = new TypeScript.PullSignatureSymbol(signature.kind); - instantiatedSignature.setRootSymbol(signature); - - var typeParameters = signature.getTypeParameters(); - var constraint = null; - var typeParameter = null; - - for (var i = 0; i < typeParameters.length; i++) { - typeParameter = typeParameters[i]; - - instantiatedSignature.addTypeParameter(typeParameter); + var instantiatedSignature = rootSignature.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiatedSignature) { + return instantiatedSignature; } - instantiatedSignature.returnType = this.instantiateType((signature.returnType || this.semanticInfoChain.anyTypeSymbol), typeParameterArgumentMap, instantiateFunctionTypeParameters); + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(signature, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; - if (instantiateFunctionTypeParameters) { - instantiatedSignature.functionType = this.instantiateType(signature.functionType, typeParameterArgumentMap, instantiateFunctionTypeParameters); - } + instantiatedSignature = new TypeScript.PullInstantiatedSignatureSymbol(rootSignature, typeParameterArgumentMap); - var parameters = signature.parameters; + instantiatedSignature.returnType = this.instantiateType((rootSignature.returnType || this.semanticInfoChain.anyTypeSymbol), typeParameterArgumentMap); + instantiatedSignature.functionType = this.instantiateType(rootSignature.functionType, typeParameterArgumentMap); + + var parameters = rootSignature.parameters; var parameter = null; if (parameters) { @@ -49288,7 +50691,7 @@ var TypeScript; } instantiatedSignature.addParameter(parameter, parameter.isOptional); - parameter.type = this.instantiateType(parameters[j].type, typeParameterArgumentMap, instantiateFunctionTypeParameters); + parameter.type = this.instantiateType(parameters[j].type, typeParameterArgumentMap); } } @@ -49300,7 +50703,7 @@ var TypeScript; TypeScript.PullTypeResolver = PullTypeResolver; var TypeComparisonInfo = (function () { - function TypeComparisonInfo(sourceComparisonInfo) { + function TypeComparisonInfo(sourceComparisonInfo, useSameIndent) { this.onlyCaptureFirstError = false; this.flags = 0 /* SuccessfulComparison */; this.message = ""; @@ -49310,7 +50713,10 @@ var TypeScript; this.flags = sourceComparisonInfo.flags; this.onlyCaptureFirstError = sourceComparisonInfo.onlyCaptureFirstError; this.stringConstantVal = sourceComparisonInfo.stringConstantVal; - this.indent = sourceComparisonInfo.indent + 1; + this.indent = sourceComparisonInfo.indent; + if (!useSameIndent) { + this.indent++; + } } } TypeComparisonInfo.prototype.indentString = function () { @@ -49441,25 +50847,24 @@ var TypeScript; this._resolver = null; this._topLevelDecls = null; this._fileNames = null; - var span = new TypeScript.TextSpan(0, 0); - var globalDecl = new TypeScript.RootPullDecl("", "", 0 /* Global */, 0 /* None */, span, this, false); + var globalDecl = new TypeScript.RootPullDecl("", "", 0 /* Global */, 0 /* None */, this, false); this.documents[0] = new TypeScript.Document(this.compiler, this, "", [], null, 0 /* None */, 0, false, null, globalDecl); - this.anyTypeDecl = new TypeScript.NormalPullDecl("any", "any", 2 /* Primitive */, 0 /* None */, globalDecl, span); - this.booleanTypeDecl = new TypeScript.NormalPullDecl("boolean", "boolean", 2 /* Primitive */, 0 /* None */, globalDecl, span); - this.numberTypeDecl = new TypeScript.NormalPullDecl("number", "number", 2 /* Primitive */, 0 /* None */, globalDecl, span); - this.stringTypeDecl = new TypeScript.NormalPullDecl("string", "string", 2 /* Primitive */, 0 /* None */, globalDecl, span); - this.voidTypeDecl = new TypeScript.NormalPullDecl("void", "void", 2 /* Primitive */, 0 /* None */, globalDecl, span); + this.anyTypeDecl = new TypeScript.NormalPullDecl("any", "any", 2 /* Primitive */, 0 /* None */, globalDecl); + this.booleanTypeDecl = new TypeScript.NormalPullDecl("boolean", "boolean", 2 /* Primitive */, 0 /* None */, globalDecl); + this.numberTypeDecl = new TypeScript.NormalPullDecl("number", "number", 2 /* Primitive */, 0 /* None */, globalDecl); + this.stringTypeDecl = new TypeScript.NormalPullDecl("string", "string", 2 /* Primitive */, 0 /* None */, globalDecl); + this.voidTypeDecl = new TypeScript.NormalPullDecl("void", "void", 2 /* Primitive */, 0 /* None */, globalDecl); - this.nullTypeDecl = new TypeScript.RootPullDecl("null", "", 2 /* Primitive */, 0 /* None */, span, this, false); - this.undefinedTypeDecl = new TypeScript.RootPullDecl("undefined", "", 2 /* Primitive */, 0 /* None */, span, this, false); - this.undefinedValueDecl = new TypeScript.NormalPullDecl("undefined", "undefined", 512 /* Variable */, 8 /* Ambient */, globalDecl, span); + this.nullTypeDecl = new TypeScript.RootPullDecl("null", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedTypeDecl = new TypeScript.RootPullDecl("undefined", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedValueDecl = new TypeScript.NormalPullDecl("undefined", "undefined", 512 /* Variable */, 8 /* Ambient */, globalDecl); this.invalidate(); } SemanticInfoChain.prototype.getDocument = function (fileName) { var document = this.fileNameToDocument[fileName]; - return document ? document : null; + return document || null; }; SemanticInfoChain.prototype.lineMap = function (fileName) { @@ -49505,8 +50910,7 @@ var TypeScript; this.undefinedTypeSymbol = this.addPrimitiveTypeSymbol(this.undefinedTypeDecl); this.undefinedValueSymbol = this.addPrimitiveValueSymbol(this.undefinedValueDecl, this.undefinedTypeSymbol); - var span = new TypeScript.TextSpan(0, 0); - var emptyTypeDecl = new TypeScript.PullSynthesizedDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, null, span, this); + var emptyTypeDecl = new TypeScript.PullSynthesizedDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, null, this); var emptyTypeSymbol = new TypeScript.PullTypeSymbol("{}", 8388608 /* ObjectType */); emptyTypeDecl.setSymbol(emptyTypeSymbol); emptyTypeSymbol.addDeclaration(emptyTypeDecl); @@ -49567,7 +50971,7 @@ var TypeScript; break; } - if (doNotGoPastThisDecl && topLevelDecl.name == doNotGoPastThisDecl.fileName()) { + if (doNotGoPastThisDecl && topLevelDecl.name === doNotGoPastThisDecl.fileName()) { return null; } } @@ -49604,13 +51008,6 @@ var TypeScript; SemanticInfoChain.prototype.findExternalModule = function (id) { id = TypeScript.normalizePath(id); - var dtsFile = id + ".d.ts"; - var dtsCacheID = this.getDeclPathCacheID([dtsFile], 32 /* DynamicModule */); - var symbol = this.symbolCache[dtsCacheID]; - if (symbol) { - return symbol; - } - var tsFile = id + ".ts"; var tsCacheID = this.getDeclPathCacheID([tsFile], 32 /* DynamicModule */); symbol = this.symbolCache[tsCacheID]; @@ -49618,27 +51015,44 @@ var TypeScript; return symbol; } - symbol = null; + var dtsFile = id + ".d.ts"; + var dtsCacheID = this.getDeclPathCacheID([dtsFile], 32 /* DynamicModule */); + var symbol = this.symbolCache[dtsCacheID]; + if (symbol) { + return symbol; + } + + var dtsSymbol; for (var i = 0; i < this.documents.length; i++) { var document = this.documents[i]; var topLevelDecl = document.topLevelDecl(); if (topLevelDecl.isExternalModule()) { - var isDtsFile = document.fileName == dtsFile; - if (isDtsFile || document.fileName == tsFile) { + var isTsFile = document.fileName === tsFile; + if (isTsFile || document.fileName === dtsFile) { var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; symbol = dynamicModuleDecl.getSymbol(); - this.symbolCache[dtsCacheID] = isDtsFile ? symbol : null; - this.symbolCache[tsCacheID] = !TypeScript.isDTSFile ? symbol : null; - return symbol; + + if (isTsFile) { + this.symbolCache[tsCacheID] = symbol; + + return symbol; + } else { + dtsSymbol = symbol; + } } } } + if (dtsSymbol) { + this.symbolCache[dtsCacheID] = symbol; + return dtsSymbol; + } + this.symbolCache[dtsCacheID] = null; this.symbolCache[tsCacheID] = null; - return symbol; + return null; }; SemanticInfoChain.prototype.findAmbientExternalModuleInGlobalContext = function (id) { @@ -49685,25 +51099,21 @@ var TypeScript; var decls = TypeScript.sentinelEmptyArray; var path; var foundDecls = TypeScript.sentinelEmptyArray; - var keepSearching = (declKind & 164 /* SomeContainer */) || (declKind & 16 /* Interface */); for (var i = 0; i < declPath.length; i++) { path = declPath[i]; decls = TypeScript.sentinelEmptyArray; + var kind = (i === declPath.length - 1) ? declKind : 164 /* SomeContainer */; for (var j = 0; j < declsToSearch.length; j++) { - foundDecls = declsToSearch[j].searchChildDecls(path, declKind); + foundDecls = declsToSearch[j].searchChildDecls(path, kind); for (var k = 0; k < foundDecls.length; k++) { - if (decls == TypeScript.sentinelEmptyArray) { + if (decls === TypeScript.sentinelEmptyArray) { decls = []; } decls[decls.length] = foundDecls[k]; } - - if (foundDecls.length && !keepSearching) { - break; - } } declsToSearch = decls; @@ -49752,9 +51162,20 @@ var TypeScript; var symbol = null; if (decls.length) { - symbol = decls[0].getSymbol(); + var decl = decls[0]; + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + var valueDecl = decl.getValueDecl(); + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + } + symbol = decl.getSymbol(); if (symbol) { + for (var i = 1; i < decls.length; i++) { + decls[i].ensureSymbolIsBound(); + } + this.symbolCache[cacheID] = symbol; } } @@ -49806,7 +51227,6 @@ var TypeScript; } TypeScript.pullSymbolID = 0; - TypeScript.globalTyvarID = 0; this.resetGlobalSymbols(); @@ -49814,7 +51234,7 @@ var TypeScript; }; SemanticInfoChain.prototype.settingsChangeAffectsSyntax = function (before, after) { - return before.allowAutomaticSemicolonInsertion() !== after.allowAutomaticSemicolonInsertion() || before.codeGenTarget() !== after.codeGenTarget() || before.propagateEnumConstants() != after.propagateEnumConstants(); + return before.allowAutomaticSemicolonInsertion() !== after.allowAutomaticSemicolonInsertion() || before.codeGenTarget() !== after.codeGenTarget() || before.propagateEnumConstants() !== after.propagateEnumConstants(); }; SemanticInfoChain.prototype.setSymbolForAST = function (ast, symbol) { @@ -49822,7 +51242,7 @@ var TypeScript; }; SemanticInfoChain.prototype.getSymbolForAST = function (ast) { - return this.astSymbolMap[ast.syntaxID()]; + return this.astSymbolMap[ast.syntaxID()] || null; }; SemanticInfoChain.prototype.setAliasSymbolForAST = function (ast, symbol) { @@ -49872,7 +51292,7 @@ var TypeScript; SemanticInfoChain.prototype.getDiagnostics = function (fileName) { var diagnostics = this.fileNameToDiagnostics[fileName]; - return diagnostics ? diagnostics : []; + return diagnostics || []; }; SemanticInfoChain.prototype.getBinder = function () { @@ -49902,9 +51322,8 @@ var TypeScript; containingSymbol.addIndexSignature(indexSignature); - var span = TypeScript.TextSpan.fromBounds(ast.start(), ast.end()); - var indexSigDecl = new TypeScript.PullSynthesizedDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, containingDecl, span, containingDecl.semanticInfoChain()); - var indexParamDecl = new TypeScript.PullSynthesizedDecl(indexParamName, indexParamName, 2048 /* Parameter */, 0 /* None */, indexSigDecl, span, containingDecl.semanticInfoChain()); + var indexSigDecl = new TypeScript.PullSynthesizedDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, containingDecl, containingDecl.semanticInfoChain); + var indexParamDecl = new TypeScript.PullSynthesizedDecl(indexParamName, indexParamName, 2048 /* Parameter */, 0 /* None */, indexSigDecl, containingDecl.semanticInfoChain); indexSigDecl.setSignatureSymbol(indexSignature); indexParamDecl.setSymbol(indexParameterSymbol); indexSignature.addDeclaration(indexSigDecl); @@ -49961,14 +51380,28 @@ var TypeScript; return this._topLevelDecls; }; - SemanticInfoChain.prototype.addDiagnosticFromAST = function (ast, diagnosticKey, arguments) { - if (typeof arguments === "undefined") { arguments = null; } - this.addDiagnostic(this.diagnosticFromAST(ast, diagnosticKey, arguments)); + SemanticInfoChain.prototype.addDiagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + this.addDiagnostic(this.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations)); }; - SemanticInfoChain.prototype.diagnosticFromAST = function (ast, diagnosticKey, arguments) { - if (typeof arguments === "undefined") { arguments = null; } - return new TypeScript.Diagnostic(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width(), diagnosticKey, arguments); + SemanticInfoChain.prototype.diagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + return new TypeScript.Diagnostic(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width(), diagnosticKey, _arguments, additionalLocations); + }; + + SemanticInfoChain.prototype.locationFromAST = function (ast) { + return new TypeScript.Location(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width()); + }; + + SemanticInfoChain.prototype.duplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + return this.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0, [identifier], additionalLocationAST ? [this.locationFromAST(additionalLocationAST)] : null); + }; + + SemanticInfoChain.prototype.addDuplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + this.addDiagnostic(this.duplicateIdentifierDiagnosticFromAST(ast, identifier, additionalLocationAST)); }; return SemanticInfoChain; })(); @@ -50039,7 +51472,6 @@ var TypeScript; function preCollectImportDecls(ast, context) { var importDecl = ast; var declFlags = 0 /* None */; - var span = TypeScript.TextSpan.fromBounds(importDecl.start(), importDecl.end()); var parent = context.getParent(); @@ -50047,19 +51479,17 @@ var TypeScript; declFlags |= 1 /* Exported */; } - var decl = new TypeScript.NormalPullDecl(importDecl.identifier.valueText(), importDecl.identifier.text(), 128 /* TypeAlias */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(importDecl.identifier.valueText(), importDecl.identifier.text(), 128 /* TypeAlias */, declFlags, parent); context.semanticInfoChain.setDeclForAST(ast, decl); context.semanticInfoChain.setASTForDecl(decl, ast); } function preCollectScriptDecls(sourceUnit, context) { - var span = TypeScript.TextSpan.fromBounds(sourceUnit.start(), sourceUnit.end()); - var fileName = sourceUnit.fileName(); var isExternalModule = context.document.isExternalModule(); - var decl = new TypeScript.RootPullDecl(fileName, fileName, 1 /* Script */, 0 /* None */, span, context.semanticInfoChain, isExternalModule); + var decl = new TypeScript.RootPullDecl(fileName, fileName, 1 /* Script */, 0 /* None */, context.semanticInfoChain, isExternalModule); context.semanticInfoChain.setDeclForAST(sourceUnit, decl); context.semanticInfoChain.setASTForDecl(decl, sourceUnit); @@ -50075,10 +51505,9 @@ var TypeScript; var moduleContainsExecutableCode = containsExecutableCode(sourceUnit.moduleElements); var kind = 32 /* DynamicModule */; - var span = TypeScript.TextSpan.fromBounds(sourceUnit.start(), sourceUnit.end()); var valueText = TypeScript.quoteStr(fileName); - var decl = new TypeScript.NormalPullDecl(valueText, fileName, kind, declFlags, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(valueText, fileName, kind, declFlags, context.getParent()); context.semanticInfoChain.setASTForDecl(decl, sourceUnit); @@ -50095,7 +51524,6 @@ var TypeScript; function preCollectEnumDecls(enumDecl, context) { var declFlags = 0 /* None */; var enumName = enumDecl.identifier.valueText(); - var kind = 4 /* Container */; if ((TypeScript.hasModifier(enumDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(enumDecl, context)) && !containingModuleHasExportAssignment(enumDecl)) { declFlags |= 1 /* Exported */; @@ -50106,18 +51534,13 @@ var TypeScript; } declFlags |= 4096 /* Enum */; - kind = 64 /* Enum */; + var kind = 64 /* Enum */; - var span = TypeScript.TextSpan.fromBounds(enumDecl.start(), enumDecl.end()); - - var enumDeclaration = new TypeScript.NormalPullDecl(enumName, enumDecl.identifier.text(), kind, declFlags, context.getParent(), span); + var enumDeclaration = new TypeScript.NormalPullDecl(enumName, enumDecl.identifier.text(), kind, declFlags, context.getParent()); context.semanticInfoChain.setDeclForAST(enumDecl, enumDeclaration); context.semanticInfoChain.setASTForDecl(enumDeclaration, enumDecl); - var enumIndexerDecl = new TypeScript.NormalPullDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, enumDeclaration, span); - var enumIndexerParameter = new TypeScript.NormalPullDecl("x", "x", 2048 /* Parameter */, 0 /* None */, enumIndexerDecl, span); - - var valueDecl = new TypeScript.NormalPullDecl(enumDeclaration.name, enumDeclaration.getDisplayName(), 512 /* Variable */, enumDeclaration.flags, context.getParent(), enumDeclaration.getSpan()); + var valueDecl = new TypeScript.NormalPullDecl(enumDeclaration.name, enumDeclaration.getDisplayName(), 512 /* Variable */, enumDeclaration.flags, context.getParent()); enumDeclaration.setValueDecl(valueDecl); context.semanticInfoChain.setASTForDecl(valueDecl, enumDecl); @@ -50127,9 +51550,7 @@ var TypeScript; function createEnumElementDecls(propertyDecl, context) { var parent = context.getParent(); - var span = TypeScript.TextSpan.fromBounds(propertyDecl.start(), propertyDecl.end()); - - var decl = new TypeScript.PullEnumElementDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), parent, span); + var decl = new TypeScript.PullEnumElementDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), parent); context.semanticInfoChain.setDeclForAST(propertyDecl, decl); context.semanticInfoChain.setASTForDecl(decl, propertyDecl); } @@ -50151,13 +51572,11 @@ var TypeScript; var kind = isDynamic ? 32 /* DynamicModule */ : 4 /* Container */; - var span = TypeScript.TextSpan.fromBounds(moduleDecl.start(), moduleDecl.end()); - if (moduleDecl.stringLiteral) { var valueText = TypeScript.quoteStr(moduleDecl.stringLiteral.valueText()); var text = moduleDecl.stringLiteral.text(); - var decl = new TypeScript.NormalPullDecl(valueText, text, kind, declFlags, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(valueText, text, kind, declFlags, context.getParent()); context.semanticInfoChain.setDeclForAST(moduleDecl, decl); context.semanticInfoChain.setDeclForAST(moduleDecl.stringLiteral, decl); @@ -50178,7 +51597,7 @@ var TypeScript; specificFlags |= 1 /* Exported */; } - var decl = new TypeScript.NormalPullDecl(moduleName.valueText(), moduleName.text(), kind, specificFlags, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(moduleName.valueText(), moduleName.text(), kind, specificFlags, context.getParent()); context.semanticInfoChain.setDeclForAST(moduleDecl, decl); context.semanticInfoChain.setDeclForAST(moduleName, decl); @@ -50210,7 +51629,7 @@ var TypeScript; function createModuleVariableDecl(decl, moduleNameAST, context) { decl.setFlags(decl.flags | getInitializationFlag(decl)); - var valueDecl = new TypeScript.NormalPullDecl(decl.name, decl.getDisplayName(), 512 /* Variable */, decl.flags, context.getParent(), decl.getSpan()); + var valueDecl = new TypeScript.NormalPullDecl(decl.name, decl.getDisplayName(), 512 /* Variable */, decl.flags, context.getParent()); decl.setValueDecl(valueDecl); context.semanticInfoChain.setASTForDecl(valueDecl, moduleNameAST); } @@ -50225,7 +51644,11 @@ var TypeScript; if (containsExecutableCode(moduleDecl.moduleElements)) { return true; } - } else if (member.kind() !== 128 /* InterfaceDeclaration */ && member.kind() !== 133 /* ImportDeclaration */) { + } else if (member.kind() === 133 /* ImportDeclaration */) { + if (TypeScript.hasModifier(member.modifiers, 1 /* Exported */)) { + return true; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */) { return true; } } @@ -50235,7 +51658,6 @@ var TypeScript; function preCollectClassDecls(classDecl, context) { var declFlags = 0 /* None */; - var constructorDeclKind = 512 /* Variable */; if ((TypeScript.hasModifier(classDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(classDecl, context)) && !containingModuleHasExportAssignment(classDecl)) { declFlags |= 1 /* Exported */; @@ -50245,12 +51667,11 @@ var TypeScript; declFlags |= 8 /* Ambient */; } - var span = TypeScript.TextSpan.fromBounds(classDecl.start(), classDecl.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 8 /* Class */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 8 /* Class */, declFlags, parent); - var constructorDecl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), constructorDeclKind, declFlags | 16384 /* ClassConstructorVariable */, parent, span); + var constructorDecl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 512 /* Variable */, declFlags | 16384 /* ClassConstructorVariable */, parent); decl.setValueDecl(constructorDecl); @@ -50268,15 +51689,13 @@ var TypeScript; var declFlags = 0 /* None */; - var span = TypeScript.TextSpan.fromBounds(objectType.start(), objectType.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", 8388608 /* ObjectType */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", 8388608 /* ObjectType */, declFlags, parent); context.semanticInfoChain.setDeclForAST(objectType, decl); context.semanticInfoChain.setASTForDecl(decl, objectType); @@ -50290,10 +51709,9 @@ var TypeScript; declFlags |= 1 /* Exported */; } - var span = TypeScript.TextSpan.fromBounds(interfaceDecl.start(), interfaceDecl.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(interfaceDecl.identifier.valueText(), interfaceDecl.identifier.text(), 16 /* Interface */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(interfaceDecl.identifier.valueText(), interfaceDecl.identifier.text(), 16 /* Interface */, declFlags, parent); context.semanticInfoChain.setDeclForAST(interfaceDecl, decl); context.semanticInfoChain.setASTForDecl(decl, interfaceDecl); @@ -50319,15 +51737,13 @@ var TypeScript; declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var span = TypeScript.TextSpan.fromBounds(argDecl.start(), argDecl.end()); - - var decl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 2048 /* Parameter */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 2048 /* Parameter */, declFlags, parent); if (argDecl.equalsValueClause) { parent.flags |= 33554432 /* HasDefaultArgs */; } - if (parent.kind == 32768 /* ConstructorMethod */) { + if (parent.kind === 32768 /* ConstructorMethod */) { decl.setFlag(67108864 /* ConstructorParameter */); } @@ -50335,12 +51751,14 @@ var TypeScript; var isInConstructor = parent.kind === 32768 /* ConstructorMethod */; if (isPublicOrPrivate && isInConstructor) { var parentsParent = context.parentChain[context.parentChain.length - 2]; - var propDecl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 4096 /* Property */, declFlags, parentsParent, span); + + var propDeclFlags = declFlags & ~128 /* Optional */; + var propDecl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 4096 /* Property */, propDeclFlags, parentsParent); propDecl.setValueDecl(decl); decl.setFlag(8388608 /* PropertyParameter */); propDecl.setFlag(8388608 /* PropertyParameter */); - if (parent.kind == 32768 /* ConstructorMethod */) { + if (parent.kind === 32768 /* ConstructorMethod */) { propDecl.setFlag(67108864 /* ConstructorParameter */); } @@ -50358,15 +51776,13 @@ var TypeScript; function preCollectTypeParameterDecl(typeParameterDecl, context) { var declFlags = 0 /* None */; - var span = TypeScript.TextSpan.fromBounds(typeParameterDecl.start(), typeParameterDecl.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(typeParameterDecl.identifier.valueText(), typeParameterDecl.identifier.text(), 8192 /* TypeParameter */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(typeParameterDecl.identifier.valueText(), typeParameterDecl.identifier.text(), 8192 /* TypeParameter */, declFlags, parent); context.semanticInfoChain.setASTForDecl(decl, typeParameterDecl); context.semanticInfoChain.setDeclForAST(typeParameterDecl, decl); } @@ -50380,9 +51796,7 @@ var TypeScript; declFlags |= 128 /* Optional */; } - var span = TypeScript.TextSpan.fromBounds(propertyDecl.start(), propertyDecl.end()); - - var decl = new TypeScript.NormalPullDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(propertyDecl, decl); context.semanticInfoChain.setASTForDecl(decl, propertyDecl); } @@ -50401,10 +51815,9 @@ var TypeScript; declFlags |= 16 /* Static */; } - var span = TypeScript.TextSpan.fromBounds(memberDecl.start(), memberDecl.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(memberDecl.variableDeclarator.propertyName.valueText(), memberDecl.variableDeclarator.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(memberDecl.variableDeclarator.propertyName.valueText(), memberDecl.variableDeclarator.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(memberDecl, decl); context.semanticInfoChain.setDeclForAST(memberDecl.variableDeclarator, decl); context.semanticInfoChain.setASTForDecl(decl, memberDecl); @@ -50414,7 +51827,7 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 512 /* Variable */; - var modifiers = TypeScript.getVariableDeclaratorModifiers(varDecl); + var modifiers = TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl); if ((TypeScript.hasModifier(modifiers, 1 /* Exported */) || isParsingAmbientModule(varDecl, context)) && !containingModuleHasExportAssignment(varDecl)) { declFlags |= 1 /* Exported */; } @@ -50423,15 +51836,13 @@ var TypeScript; declFlags |= 8 /* Ambient */; } - var span = TypeScript.TextSpan.fromBounds(varDecl.start(), varDecl.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(varDecl.propertyName.valueText(), varDecl.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(varDecl.propertyName.valueText(), varDecl.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(varDecl, decl); context.semanticInfoChain.setASTForDecl(decl, varDecl); @@ -50453,15 +51864,13 @@ var TypeScript; var declFlags = 2048 /* Signature */; var declType = 16777216 /* FunctionType */; - var span = TypeScript.TextSpan.fromBounds(functionTypeDeclAST.start(), functionTypeDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(functionTypeDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, functionTypeDeclAST); @@ -50472,15 +51881,13 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 33554432 /* ConstructorType */; - var span = TypeScript.TextSpan.fromBounds(constructorTypeDeclAST.start(), constructorTypeDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(constructorTypeDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, constructorTypeDeclAST); @@ -50503,15 +51910,13 @@ var TypeScript; declFlags |= 2048 /* Signature */; } - var span = TypeScript.TextSpan.fromBounds(funcDeclAST.start(), funcDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(funcDeclAST.identifier.valueText(), funcDeclAST.identifier.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(funcDeclAST.identifier.valueText(), funcDeclAST.identifier.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(funcDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, funcDeclAST); @@ -50526,8 +51931,6 @@ var TypeScript; declFlags |= 8192 /* ArrowFunction */; } - var span = TypeScript.TextSpan.fromBounds(functionExpressionDeclAST.start(), functionExpressionDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { @@ -50536,7 +51939,7 @@ var TypeScript; var name = id ? id.text() : ""; var displayNameText = displayName ? displayName.text() : ""; - var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, parent, span, displayNameText); + var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, parent, displayNameText); context.semanticInfoChain.setDeclForAST(functionExpressionDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, functionExpressionDeclAST); @@ -50552,9 +51955,7 @@ var TypeScript; declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var span = TypeScript.TextSpan.fromBounds(simpleArrow.identifier.start(), simpleArrow.identifier.end()); - - var decl = new TypeScript.NormalPullDecl(simpleArrow.identifier.valueText(), simpleArrow.identifier.text(), 2048 /* Parameter */, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(simpleArrow.identifier.valueText(), simpleArrow.identifier.text(), 2048 /* Parameter */, declFlags, parent); context.semanticInfoChain.setASTForDecl(decl, simpleArrow.identifier); context.semanticInfoChain.setDeclForAST(simpleArrow.identifier, decl); @@ -50581,10 +51982,9 @@ var TypeScript; declFlags |= 2048 /* Signature */; } - var span = TypeScript.TextSpan.fromBounds(funcDecl.start(), funcDecl.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(funcDecl.propertyName.valueText(), funcDecl.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(funcDecl.propertyName.valueText(), funcDecl.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(funcDecl, decl); context.semanticInfoChain.setASTForDecl(decl, funcDecl); @@ -50595,11 +51995,9 @@ var TypeScript; var declFlags = 2048 /* Signature */; var declType = 4194304 /* IndexSignature */; - var span = TypeScript.TextSpan.fromBounds(indexSignatureDeclAST.start(), indexSignatureDeclAST.end()); - var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(indexSignatureDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, indexSignatureDeclAST); @@ -50616,15 +52014,13 @@ var TypeScript; var declFlags = 2048 /* Signature */; var declType = 1048576 /* CallSignature */; - var span = TypeScript.TextSpan.fromBounds(callSignature.start(), callSignature.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(callSignature, decl); context.semanticInfoChain.setASTForDecl(decl, callSignature); @@ -50642,10 +52038,9 @@ var TypeScript; declFlags |= 128 /* Optional */; } - var span = TypeScript.TextSpan.fromBounds(method.start(), method.end()); var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl(method.propertyName.valueText(), method.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(method.propertyName.valueText(), method.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(method, decl); context.semanticInfoChain.setASTForDecl(decl, method); @@ -50656,15 +52051,13 @@ var TypeScript; var declFlags = 2048 /* Signature */; var declType = 2097152 /* ConstructSignature */; - var span = TypeScript.TextSpan.fromBounds(constructSignatureDeclAST.start(), constructSignatureDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(constructSignatureDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, constructSignatureDeclAST); @@ -50679,8 +52072,6 @@ var TypeScript; declFlags |= 2048 /* Signature */; } - var span = TypeScript.TextSpan.fromBounds(constructorDeclAST.start(), constructorDeclAST.end()); - var parent = context.getParent(); if (parent) { @@ -50691,7 +52082,7 @@ var TypeScript; } } - var decl = new TypeScript.NormalPullDecl(parent.name, parent.getDisplayName(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(parent.name, parent.getDisplayName(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(constructorDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, constructorDeclAST); @@ -50712,15 +52103,13 @@ var TypeScript; declFlags |= 4 /* Public */; } - var span = TypeScript.TextSpan.fromBounds(getAccessorDeclAST.start(), getAccessorDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(getAccessorDeclAST.propertyName.valueText(), getAccessorDeclAST.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(getAccessorDeclAST.propertyName.valueText(), getAccessorDeclAST.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(getAccessorDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, getAccessorDeclAST); @@ -50745,15 +52134,13 @@ var TypeScript; declFlags |= 4 /* Public */; } - var span = TypeScript.TextSpan.fromBounds(setAccessorDeclAST.start(), setAccessorDeclAST.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(setAccessorDeclAST.propertyName.valueText(), setAccessorDeclAST.propertyName.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(setAccessorDeclAST.propertyName.valueText(), setAccessorDeclAST.propertyName.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(setAccessorDeclAST, decl); context.semanticInfoChain.setASTForDecl(decl, setAccessorDeclAST); @@ -50764,15 +52151,13 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 268435456 /* CatchBlock */; - var span = TypeScript.TextSpan.fromBounds(ast.start(), ast.end()); - var parent = context.getParent(); if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(ast, decl); context.semanticInfoChain.setASTForDecl(decl, ast); @@ -50781,15 +52166,13 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 1024 /* CatchVariable */; - var span = TypeScript.TextSpan.fromBounds(ast.identifier.start(), ast.identifier.end()); - var parent = context.getParent(); if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { declFlags |= 2097152 /* DeclaredInAWithBlock */; } - var decl = new TypeScript.NormalPullDecl(ast.identifier.valueText(), ast.identifier.text(), declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl(ast.identifier.valueText(), ast.identifier.text(), declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(ast.identifier, decl); context.semanticInfoChain.setASTForDecl(decl, ast.identifier); @@ -50802,11 +52185,9 @@ var TypeScript; var declFlags = 0 /* None */; var declType = 134217728 /* WithBlock */; - var span = TypeScript.TextSpan.fromBounds(ast.start(), ast.end()); - var parent = context.getParent(); - var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent, span); + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); context.semanticInfoChain.setDeclForAST(ast, decl); context.semanticInfoChain.setASTForDecl(decl, ast); @@ -50814,8 +52195,7 @@ var TypeScript; } function preCollectObjectLiteralDecls(ast, context) { - var span = TypeScript.TextSpan.fromBounds(ast.start(), ast.end()); - var decl = new TypeScript.NormalPullDecl("", "", 256 /* ObjectLiteral */, 0 /* None */, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl("", "", 256 /* ObjectLiteral */, 0 /* None */, context.getParent()); context.semanticInfoChain.setDeclForAST(ast, decl); context.semanticInfoChain.setASTForDecl(decl, ast); @@ -50827,7 +52207,7 @@ var TypeScript; var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); var span = TypeScript.TextSpan.fromBounds(propertyAssignment.start(), propertyAssignment.end()); - var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); @@ -50835,9 +52215,8 @@ var TypeScript; function preCollectFunctionPropertyAssignmentDecls(propertyAssignment, context) { var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); - var span = TypeScript.TextSpan.fromBounds(propertyAssignment.start(), propertyAssignment.end()); - var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent(), span); + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); @@ -51043,7 +52422,7 @@ var TypeScript; function computeEnumElementConstantValue(expression, enumMemberDecls, context) { TypeScript.Debug.assert(expression); - if (TypeScript.isIntegerLiteralAST(expression)) { + if (TypeScript.ASTHelpers.isIntegerLiteralAST(expression)) { var token; switch (expression.kind()) { case 164 /* PlusExpression */: @@ -51111,12 +52490,13 @@ var TypeScript; function PullSymbolBinder(semanticInfoChain) { this.semanticInfoChain = semanticInfoChain; this.declsBeingBound = []; + this.inBindingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); } PullSymbolBinder.prototype.getParent = function (decl, returnInstanceType) { if (typeof returnInstanceType === "undefined") { returnInstanceType = false; } var parentDecl = decl.getParentDecl(); - if (parentDecl.kind == 1 /* Script */) { + if (parentDecl.kind === 1 /* Script */) { return null; } @@ -51129,9 +52509,9 @@ var TypeScript; parent = parentDecl.getSymbol(); if (parent) { var parentDeclKind = parentDecl.kind; - if (parentDeclKind == 262144 /* GetAccessor */) { + if (parentDeclKind === 262144 /* GetAccessor */) { parent = parent.getGetter(); - } else if (parentDeclKind == 524288 /* SetAccessor */) { + } else if (parentDeclKind === 524288 /* SetAccessor */) { parent = parent.getSetter(); } } @@ -51175,7 +52555,7 @@ var TypeScript; PullSymbolBinder.prototype.getExistingSymbol = function (decl, searchKind, parent) { var lookingForValue = (searchKind & 68147712 /* SomeValue */) !== 0; - var lookingForType = (searchKind & 58728539 /* SomeType */) !== 0; + var lookingForType = (searchKind & 58728795 /* SomeType */) !== 0; var lookingForContainer = (searchKind & 164 /* SomeContainer */) !== 0; var name = decl.name; if (parent) { @@ -51232,7 +52612,7 @@ var TypeScript; var isExported = (decl.flags & 1 /* Exported */) !== 0; var prevDecls = prevSymbol.getDeclarations(); var prevIsExported = (prevDecls[prevDecls.length - 1].flags & 1 /* Exported */) !== 0; - if ((isExported !== prevIsExported) && !prevSymbol.isSignature() && (decl.kind & 7340032 /* SomeSignature */) == 0) { + if ((isExported !== prevIsExported) && !prevSymbol.isSignature() && (decl.kind & 7340032 /* SomeSignature */) === 0) { if (reportError) { var ast = this.semanticInfoChain.getASTForDecl(decl); this.semanticInfoChain.addDiagnosticFromAST(ast, TypeScript.DiagnosticCode.All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported, [decl.getDisplayName()]); @@ -51243,6 +52623,16 @@ var TypeScript; return true; }; + PullSymbolBinder.prototype.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList = function (signature, currentSignatures) { + var signatureDecl = signature.getDeclarations()[0]; + TypeScript.Debug.assert(signatureDecl); + var enclosingDecl = signatureDecl.getParentDecl(); + var indexToInsert = TypeScript.ArrayUtilities.indexOf(currentSignatures, function (someSignature) { + return someSignature.getDeclarations()[0].getParentDecl() !== enclosingDecl; + }); + return indexToInsert < 0 ? currentSignatures.length : indexToInsert; + }; + PullSymbolBinder.prototype.bindEnumDeclarationToPullSymbol = function (enumContainerDecl) { var enumName = enumContainerDecl.name; @@ -51260,7 +52650,6 @@ var TypeScript; var enumAST = this.semanticInfoChain.getASTForDecl(enumContainerDecl); var isExported = enumContainerDecl.flags & 1 /* Exported */; - var isInitializedModule = (enumContainerDecl.flags & 102400 /* SomeInitializedModule */) != 0; var createdNewSymbol = false; @@ -51268,9 +52657,7 @@ var TypeScript; if (enumContainerSymbol) { if (enumContainerSymbol.kind !== enumDeclKind) { - if (isInitializedModule) { - this.semanticInfoChain.addDiagnosticFromAST(enumAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [enumContainerDecl.getDisplayName()]); - } + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(enumAST.identifier, enumContainerDecl.getDisplayName(), enumContainerSymbol.getDeclarations()[0].ast()); enumContainerSymbol = null; } else if (!this.checkThatExportsMatch(enumContainerDecl, enumContainerSymbol)) { enumContainerSymbol = null; @@ -51294,7 +52681,7 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(enumAST.identifier, enumContainerSymbol); this.semanticInfoChain.setSymbolForAST(enumAST, enumContainerSymbol); - if (!enumInstanceSymbol && isInitializedModule) { + if (!enumInstanceSymbol) { var variableSymbol = null; if (parentInstanceSymbol) { if (isExported) { @@ -51327,11 +52714,11 @@ var TypeScript; var augmentedDecl = null; for (var i = 0; i < siblingDecls.length; i++) { - if (siblingDecls[i] == enumContainerDecl) { + if (siblingDecls[i] === enumContainerDecl) { break; } - if ((siblingDecls[i].name == enumName) && (siblingDecls[i].kind & 68147712 /* SomeValue */)) { + if ((siblingDecls[i].name === enumName) && (siblingDecls[i].kind & 68147712 /* SomeValue */)) { augmentedDecl = siblingDecls[i]; break; } @@ -51371,20 +52758,6 @@ var TypeScript; } } - var moduleDeclarations = enumContainerSymbol.getDeclarations(); - - if (moduleDeclarations.length > 1 && enumAST.enumElements.nonSeparatorCount() > 0) { - var multipleEnums = TypeScript.ArrayUtilities.where(moduleDeclarations, function (d) { - return d.kind === 64 /* Enum */; - }).length > 1; - if (multipleEnums) { - var firstVariable = enumAST.enumElements.nonSeparatorAt(0); - if (!firstVariable.equalsValueClause) { - this.semanticInfoChain.addDiagnosticFromAST(firstVariable, TypeScript.DiagnosticCode.Enums_with_multiple_declarations_must_provide_an_initializer_for_the_first_enum_element, null); - } - } - } - if (createdNewSymbol && parent) { if (enumContainerDecl.flags & 1 /* Exported */) { parent.addEnclosedMemberType(enumContainerSymbol); @@ -51393,65 +52766,111 @@ var TypeScript; } } - this.bindEnumIndexerDeclsToPullSymbols(enumContainerDecl, enumContainerSymbol); - + if (createdNewSymbol) { + this.bindEnumIndexerDeclsToPullSymbols(enumContainerSymbol); + } var valueDecl = enumContainerDecl.getValueDecl(); if (valueDecl) { valueDecl.ensureSymbolIsBound(); } - - var otherDecls = this.findDeclsInContext(enumContainerDecl, enumContainerDecl.kind, true); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } }; - PullSymbolBinder.prototype.bindEnumIndexerDeclsToPullSymbols = function (enumContainerDecl, enumContainerSymbol) { - var indexSigDecl = enumContainerDecl.getChildDecls().filter(function (decl) { - return decl.kind == 4194304 /* IndexSignature */; - })[0]; - var indexParamDecl = indexSigDecl.getChildDecls()[0]; - - var syntheticIndexerParameterSymbol = new TypeScript.PullSymbol(indexParamDecl.name, 2048 /* Parameter */); + PullSymbolBinder.prototype.bindEnumIndexerDeclsToPullSymbols = function (enumContainerSymbol) { + var enumContainerInstanceTypeSymbol = enumContainerSymbol.getInstanceSymbol().type; + var syntheticIndexerParameterSymbol = new TypeScript.PullSymbol("x", 2048 /* Parameter */); syntheticIndexerParameterSymbol.type = this.semanticInfoChain.numberTypeSymbol; syntheticIndexerParameterSymbol.setResolved(); + syntheticIndexerParameterSymbol.setIsSynthesized(); var syntheticIndexerSignatureSymbol = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); syntheticIndexerSignatureSymbol.addParameter(syntheticIndexerParameterSymbol); syntheticIndexerSignatureSymbol.returnType = this.semanticInfoChain.stringTypeSymbol; syntheticIndexerSignatureSymbol.setResolved(); + syntheticIndexerSignatureSymbol.setIsSynthesized(); - var enumContainerInstanceTypeSymbol = enumContainerSymbol.getInstanceSymbol().type; enumContainerInstanceTypeSymbol.addIndexSignature(syntheticIndexerSignatureSymbol); + }; - indexSigDecl.setSignatureSymbol(syntheticIndexerSignatureSymbol); - indexParamDecl.setSymbol(syntheticIndexerParameterSymbol); + PullSymbolBinder.prototype.findExistingVariableSymbolForModuleValueDecl = function (decl) { + var isExported = TypeScript.hasFlag(decl.flags, 1 /* Exported */); + var modName = decl.name; + var parentInstanceSymbol = this.getParent(decl, true); + var parentDecl = decl.getParentDecl(); - syntheticIndexerSignatureSymbol.addDeclaration(indexSigDecl); - syntheticIndexerParameterSymbol.addDeclaration(indexParamDecl); + var variableSymbol = null; + + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + var isExportedOrHasTheSameParent = isExported || (parentDecl === variableSymbolParentDecl); + + var canReuseVariableSymbol = isExportedOrHasTheSameParent && this.checkThatExportsMatch(decl, variableSymbol, false); + + if (!canReuseVariableSymbol) { + variableSymbol = null; + } + } + } + } else if (!isExported) { + var siblingDecls = parentDecl.getChildDecls(); + + for (var i = 0; i < siblingDecls.length; i++) { + var sibling = siblingDecls[i]; + + var siblingIsSomeValue = TypeScript.hasFlag(sibling.kind, 68147712 /* SomeValue */); + var siblingIsFunctionOrHasImplictVarFlag = TypeScript.hasFlag(sibling.kind, 1032192 /* SomeFunction */) || TypeScript.hasFlag(sibling.flags, 118784 /* ImplicitVariable */); + + var isSiblingAnAugmentableVariable = sibling !== decl && sibling !== decl.getValueDecl() && sibling.name === modName && siblingIsSomeValue && siblingIsFunctionOrHasImplictVarFlag; + + if (isSiblingAnAugmentableVariable) { + if (sibling.hasSymbol()) { + variableSymbol = sibling.getSymbol(); + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + + break; + } + } + } + } + return variableSymbol; }; PullSymbolBinder.prototype.bindModuleDeclarationToPullSymbol = function (moduleContainerDecl) { var modName = moduleContainerDecl.name; var moduleContainerTypeSymbol = null; - var moduleInstanceSymbol = null; - var moduleInstanceTypeSymbol = null; - var moduleKind = moduleContainerDecl.kind; var parent = this.getParent(moduleContainerDecl); var parentInstanceSymbol = this.getParent(moduleContainerDecl, true); var parentDecl = moduleContainerDecl.getParentDecl(); var moduleNameAST = this.semanticInfoChain.getASTForDecl(moduleContainerDecl); - var moduleDeclAST = TypeScript.getEnclosingModuleDeclaration(moduleNameAST); + var moduleDeclAST = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(moduleNameAST); if (!moduleDeclAST) { - TypeScript.Debug.assert(moduleContainerDecl.kind === 32 /* DynamicModule */); + TypeScript.Debug.assert(moduleKind === 32 /* DynamicModule */); TypeScript.Debug.assert(moduleNameAST.kind() === 120 /* SourceUnit */); moduleDeclAST = moduleNameAST; @@ -51459,9 +52878,9 @@ var TypeScript; var isExported = TypeScript.hasFlag(moduleContainerDecl.flags, 1 /* Exported */); var searchKind = 164 /* SomeContainer */; - var isInitializedModule = (moduleContainerDecl.flags & 102400 /* SomeInitializedModule */) != 0; + var isInitializedModule = (moduleContainerDecl.flags & 102400 /* SomeInitializedModule */) !== 0; - if (parent && moduleKind == 32 /* DynamicModule */) { + if (parent && moduleKind === 32 /* DynamicModule */) { this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_must_be_defined_in_global_context, null); } @@ -51472,20 +52891,18 @@ var TypeScript; if (moduleContainerTypeSymbol) { if (moduleContainerTypeSymbol.kind !== moduleKind) { if (isInitializedModule) { - this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [moduleContainerDecl.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(moduleNameAST, moduleContainerDecl.getDisplayName(), moduleContainerTypeSymbol.getDeclarations()[0].ast()); } moduleContainerTypeSymbol = null; - } else if (moduleKind == 32 /* DynamicModule */) { + } else if (moduleKind === 32 /* DynamicModule */) { this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_be_reopened); } else if (!this.checkThatExportsMatch(moduleContainerDecl, moduleContainerTypeSymbol)) { moduleContainerTypeSymbol = null; } } - if (moduleContainerTypeSymbol) { - moduleInstanceSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); - } else { + if (!moduleContainerTypeSymbol) { moduleContainerTypeSymbol = new TypeScript.PullContainerSymbol(modName, moduleKind); createdNewSymbol = true; @@ -51500,74 +52917,7 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(moduleNameAST, moduleContainerTypeSymbol); this.semanticInfoChain.setSymbolForAST(moduleDeclAST, moduleContainerTypeSymbol); - if (!moduleInstanceSymbol && isInitializedModule) { - var variableSymbol = null; - if (parentInstanceSymbol) { - if (isExported) { - variableSymbol = parentInstanceSymbol.findMember(modName, false); - - if (!variableSymbol) { - variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); - } - } else { - variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); - - if (!variableSymbol) { - variableSymbol = parentInstanceSymbol.findMember(modName, false); - } - } - - if (variableSymbol) { - var declarations = variableSymbol.getDeclarations(); - - if (declarations.length) { - var variableSymbolParentDecl = declarations[0].getParentDecl(); - - if (parentDecl !== variableSymbolParentDecl) { - variableSymbol = null; - } - } - } - } else if (!isExported) { - var siblingDecls = parentDecl.getChildDecls(); - - for (var i = 0; i < siblingDecls.length; i++) { - var sibling = siblingDecls[i]; - if (sibling !== moduleContainerDecl && sibling.name === modName && TypeScript.hasFlag(sibling.kind, 68147712 /* SomeValue */)) { - if (sibling.hasSymbol()) { - variableSymbol = sibling.getSymbol(); - if (variableSymbol.isContainer()) { - variableSymbol = variableSymbol.getInstanceSymbol(); - } else if (variableSymbol && variableSymbol.isType()) { - variableSymbol = variableSymbol.getConstructorMethod(); - } - - break; - } - } - } - } - - if (variableSymbol) { - moduleInstanceSymbol = variableSymbol; - moduleInstanceTypeSymbol = variableSymbol.type; - } else { - moduleInstanceSymbol = new TypeScript.PullSymbol(modName, 512 /* Variable */); - } - - moduleContainerTypeSymbol.setInstanceSymbol(moduleInstanceSymbol); - - if (!moduleInstanceTypeSymbol) { - moduleInstanceTypeSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); - moduleInstanceSymbol.type = moduleInstanceTypeSymbol; - } - - moduleInstanceTypeSymbol.addDeclaration(moduleContainerDecl); - - if (!moduleInstanceTypeSymbol.getAssociatedContainerType()) { - moduleInstanceTypeSymbol.setAssociatedContainerType(moduleContainerTypeSymbol); - } - } + var currentModuleValueDecl = moduleContainerDecl.getValueDecl(); var moduleDeclarations = moduleContainerTypeSymbol.getDeclarations(); @@ -51581,24 +52931,29 @@ var TypeScript; } } - var valueDecl = moduleContainerDecl.getValueDecl(); + if (currentModuleValueDecl) { + currentModuleValueDecl.ensureSymbolIsBound(); - if (valueDecl) { - valueDecl.ensureSymbolIsBound(); - - if (!valueDecl.hasSymbol()) { - valueDecl.setSymbol(moduleInstanceSymbol); - if (!moduleInstanceSymbol.hasDeclaration(valueDecl)) { - moduleInstanceSymbol.addDeclaration(valueDecl); + var instanceSymbol = null; + var instanceTypeSymbol = null; + if (currentModuleValueDecl.hasSymbol()) { + instanceSymbol = currentModuleValueDecl.getSymbol(); + } else { + instanceSymbol = new TypeScript.PullSymbol(modName, 512 /* Variable */); + currentModuleValueDecl.setSymbol(instanceSymbol); + if (!instanceSymbol.hasDeclaration(currentModuleValueDecl)) { + instanceSymbol.addDeclaration(currentModuleValueDecl); } } - } - var otherDecls = this.findDeclsInContext(moduleContainerDecl, moduleContainerDecl.kind, true); + if (!instanceSymbol.type) { + instanceSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); + moduleContainerTypeSymbol.setInstanceSymbol(instanceSymbol); + + if (!instanceSymbol.type.getAssociatedContainerType()) { + instanceSymbol.type.setAssociatedContainerType(moduleContainerTypeSymbol); } } }; @@ -51621,7 +52976,7 @@ var TypeScript; } if (importSymbol) { - this.semanticInfoChain.addDiagnosticFromAST(importDeclAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [importDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(importDeclAST, importDeclaration.getDisplayName(), importSymbol.getDeclarations()[0].ast()); importSymbol = null; } @@ -51647,6 +53002,28 @@ var TypeScript; } }; + PullSymbolBinder.prototype.ensurePriorDeclarationsAreBound = function (container, currentDecl) { + if (!container) { + return; + } + + var parentDecls = container.getDeclarations(); + for (var i = 0; i < parentDecls.length; ++i) { + var parentDecl = parentDecls[i]; + var childDecls = parentDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl === currentDecl) { + return; + } + + if (childDecl.name === currentDecl.name) { + childDecl.ensureSymbolIsBound(); + } + } + } + }; + PullSymbolBinder.prototype.bindClassDeclarationToPullSymbol = function (classDecl) { var className = classDecl.name; var classSymbol = null; @@ -51657,19 +53034,20 @@ var TypeScript; var classAST = this.semanticInfoChain.getASTForDecl(classDecl); var parent = this.getParent(classDecl); + + this.ensurePriorDeclarationsAreBound(parent, classDecl); + var parentDecl = classDecl.getParentDecl(); var isExported = classDecl.flags & 1 /* Exported */; var isGeneric = false; - classSymbol = this.getExistingSymbol(classDecl, 58728539 /* SomeType */, parent); + classSymbol = this.getExistingSymbol(classDecl, 58728795 /* SomeType */, parent); if (classSymbol && classSymbol.kind === 16 /* Interface */) { - this.semanticInfoChain.addDiagnosticFromAST(classAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [classDecl.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(classAST.identifier, classDecl.getDisplayName(), classSymbol.getDeclarations()[0].ast()); classSymbol = null; } - var decls; - classSymbol = new TypeScript.PullTypeSymbol(className, 8 /* Class */); if (!parent) { @@ -51691,6 +53069,23 @@ var TypeScript; } } + var typeParameterDecls = classDecl.getTypeParameters(); + + for (var i = 0; i < typeParameterDecls.length; i++) { + var typeParameterSymbol = classSymbol.findTypeParameter(typeParameterDecls[i].name); + + if (typeParameterSymbol) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterSymbol.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameterSymbol.getName()]); + } + + typeParameterSymbol = new TypeScript.PullTypeParameterSymbol(typeParameterDecls[i].name); + + classSymbol.addTypeParameter(typeParameterSymbol); + typeParameterSymbol.addDeclaration(typeParameterDecls[i]); + typeParameterDecls[i].setSymbol(typeParameterSymbol); + } + constructorSymbol = classSymbol.getConstructorMethod(); constructorTypeSymbol = constructorSymbol ? constructorSymbol.type : null; @@ -51726,32 +53121,13 @@ var TypeScript; constructorTypeSymbol.setAssociatedContainerType(classSymbol); - var typeParameters = classDecl.getTypeParameters(); - var typeParameter; - - for (var i = 0; i < typeParameters.length; i++) { - typeParameter = classSymbol.findTypeParameter(typeParameters[i].name); - - if (typeParameter != null) { - var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); - this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); - } - - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, false); - - classSymbol.addTypeParameter(typeParameter); - constructorTypeSymbol.addConstructorTypeParameter(typeParameter); - typeParameter.addDeclaration(typeParameters[i]); - typeParameters[i].setSymbol(typeParameter); - } - var valueDecl = classDecl.getValueDecl(); if (valueDecl) { valueDecl.ensureSymbolIsBound(); } - this.bindStaticPrototypePropertyOfClass(classSymbol, constructorTypeSymbol); + this.bindStaticPrototypePropertyOfClass(classAST, classSymbol, constructorTypeSymbol); }; PullSymbolBinder.prototype.bindInterfaceDeclarationToPullSymbol = function (interfaceDecl) { @@ -51764,11 +53140,11 @@ var TypeScript; var acceptableSharedKind = 16 /* Interface */; - interfaceSymbol = this.getExistingSymbol(interfaceDecl, 58728539 /* SomeType */, parent); + interfaceSymbol = this.getExistingSymbol(interfaceDecl, 58728795 /* SomeType */, parent); if (interfaceSymbol) { if (!(interfaceSymbol.kind & acceptableSharedKind)) { - this.semanticInfoChain.addDiagnosticFromAST(interfaceAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [interfaceDecl.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(interfaceAST.identifier, interfaceDecl.getDisplayName(), interfaceSymbol.getDeclarations()[0].ast()); interfaceSymbol = null; } else if (!this.checkThatExportsMatch(interfaceDecl, interfaceSymbol)) { interfaceSymbol = null; @@ -51805,7 +53181,7 @@ var TypeScript; typeParameter = interfaceSymbol.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, false); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); interfaceSymbol.addTypeParameter(typeParameter); } else { @@ -51826,14 +53202,6 @@ var TypeScript; typeParameter.addDeclaration(typeParameters[i]); typeParameters[i].setSymbol(typeParameter); } - - var otherDecls = this.findDeclsInContext(interfaceDecl, interfaceDecl.kind, true); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } }; PullSymbolBinder.prototype.bindObjectTypeDeclarationToPullSymbol = function (objectDecl) { @@ -51874,9 +53242,7 @@ var TypeScript; signature.addDeclaration(constructorTypeDeclaration); constructorTypeDeclaration.setSignatureSymbol(signature); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(funcDecl.parameterList), constructorTypeSymbol, signature); - - constructorTypeSymbol.addConstructSignature(signature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), constructorTypeSymbol, signature); var typeParameters = constructorTypeDeclaration.getTypeParameters(); var typeParameter; @@ -51885,9 +53251,9 @@ var TypeScript; typeParameter = constructorTypeSymbol.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, false); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); - constructorTypeSymbol.addConstructorTypeParameter(typeParameter); + signature.addTypeParameter(typeParameter); } else { var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); @@ -51896,12 +53262,15 @@ var TypeScript; typeParameter.addDeclaration(typeParameters[i]); typeParameters[i].setSymbol(typeParameter); } + + constructorTypeSymbol.appendConstructSignature(signature); }; PullSymbolBinder.prototype.bindVariableDeclarationToPullSymbol = function (variableDeclaration) { var declFlags = variableDeclaration.flags; var declKind = variableDeclaration.kind; var varDeclAST = this.semanticInfoChain.getASTForDecl(variableDeclaration); + var nameAST = varDeclAST.kind() === 131 /* ClassDeclaration */ ? varDeclAST.identifier : varDeclAST.kind() === 225 /* VariableDeclarator */ ? varDeclAST.propertyName : varDeclAST.kind() === 132 /* EnumDeclaration */ ? varDeclAST.identifier : varDeclAST; var isExported = (declFlags & 1 /* Exported */) !== 0; @@ -51916,12 +53285,15 @@ var TypeScript; var parentDecl = variableDeclaration.getParentDecl(); var isImplicit = (declFlags & 118784 /* ImplicitVariable */) !== 0; - var isModuleValue = (declFlags & (32768 /* InitializedModule */)) != 0; - var isEnumValue = (declFlags & 4096 /* Enum */) != 0; - var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) != 0; - + var isModuleValue = (declFlags & (32768 /* InitializedModule */)) !== 0; + var isEnumValue = (declFlags & 4096 /* Enum */) !== 0; + var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) !== 0; variableSymbol = this.getExistingSymbol(variableDeclaration, 68147712 /* SomeValue */, parent); + if (!variableSymbol && isModuleValue) { + variableSymbol = this.findExistingVariableSymbolForModuleValueDecl(variableDeclaration.getContainerDecl()); + } + if (variableSymbol && !variableSymbol.isType()) { parentHadSymbol = true; } @@ -51937,28 +53309,29 @@ var TypeScript; var prevIsClassConstructorVariable = variableSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */); var prevIsModuleValue = variableSymbol.allDeclsHaveFlag(32768 /* InitializedModule */); var prevIsImplicit = variableSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */); - var prevIsFunction = prevKind == 16384 /* Function */; + var prevIsFunction = TypeScript.ArrayUtilities.any(variableSymbol.getDeclarations(), function (decl) { + return decl.kind === 16384 /* Function */; + }); var prevIsAmbient = variableSymbol.allDeclsHaveFlag(8 /* Ambient */); - var isAmbientOrPrevIsAmbient = prevIsAmbient || (variableDeclaration.flags & 8 /* Ambient */) != 0; + var isAmbientOrPrevIsAmbient = prevIsAmbient || (variableDeclaration.flags & 8 /* Ambient */) !== 0; var prevDecl = variableSymbol.getDeclarations()[0]; var prevParentDecl = prevDecl.getParentDecl(); - var bothAreGlobal = parentDecl && (parentDecl.kind == 1 /* Script */) && (prevParentDecl.kind == 1 /* Script */); - var shareParent = bothAreGlobal || prevDecl.getParentDecl() == variableDeclaration.getParentDecl(); - var prevIsParam = shareParent && prevKind == 2048 /* Parameter */ && declKind == 512 /* Variable */; + var bothAreGlobal = parentDecl && (parentDecl.kind === 1 /* Script */) && (prevParentDecl.kind === 1 /* Script */); + var shareParent = bothAreGlobal || prevDecl.getParentDecl() === variableDeclaration.getParentDecl(); + var prevIsParam = shareParent && prevKind === 2048 /* Parameter */ && declKind == 512 /* Variable */; var acceptableRedeclaration = prevIsParam || (isImplicit && ((!isEnumValue && !isClassConstructorVariable && prevIsFunction) || ((isModuleValue || isEnumValue) && (prevIsModuleValue || prevIsEnum)) || (isClassConstructorVariable && prevIsModuleValue && isAmbientOrPrevIsAmbient) || (isModuleValue && prevIsClassConstructorVariable))); if (acceptableRedeclaration && (prevIsClassConstructorVariable || prevIsFunction) && !isAmbientOrPrevIsAmbient) { - if (prevDecl.fileName() != variableDeclaration.fileName()) { - this.semanticInfoChain.addDiagnostic(TypeScript.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2, [declName, declName, prevDecl.fileName()])); + if (prevDecl.fileName() !== variableDeclaration.fileName()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2, [declName, declName, prevDecl.fileName()])); variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); } } if (!acceptableRedeclaration || prevIsParam) { - if (!prevIsParam && (isImplicit || prevIsImplicit || (prevKind & 1032192 /* SomeFunction */) !== 0) || !shareParent) { - var diagnostic = TypeScript.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Duplicate_identifier_0, [variableDeclaration.getDisplayName()]); - this.semanticInfoChain.addDiagnostic(diagnostic); + if (!prevIsParam && (isImplicit || prevIsImplicit || TypeScript.hasFlag(prevKind, 1032192 /* SomeFunction */)) || !shareParent) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(nameAST, variableDeclaration.getDisplayName(), variableSymbol.getDeclarations()[0].ast()); variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); } else { this.checkThatExportsMatch(variableDeclaration, variableSymbol); @@ -51983,7 +53356,7 @@ var TypeScript; variableSymbol.addDeclaration(variableDeclaration); variableDeclaration.setSymbol(variableSymbol); - this.semanticInfoChain.setSymbolForAST(varDeclAST.propertyName, variableSymbol); + this.semanticInfoChain.setSymbolForAST(nameAST, variableSymbol); this.semanticInfoChain.setSymbolForAST(varDeclAST, variableSymbol); } else if (!parentHadSymbol) { if (isClassConstructorVariable) { @@ -52001,22 +53374,10 @@ var TypeScript; } if (!classTypeSymbol) { - var parentDecl = variableDeclaration.getParentDecl(); - - if (parentDecl) { - var childDecls = parentDecl.searchChildDecls(declName, 58728539 /* SomeType */); - - if (childDecls.length) { - for (var i = 0; i < childDecls.length; i++) { - if (childDecls[i].getValueDecl() === variableDeclaration) { - classTypeSymbol = childDecls[i].getSymbol(); - } - } - } - } - + var containerDecl = variableDeclaration.getContainerDecl(); + classTypeSymbol = containerDecl.getSymbol(); if (!classTypeSymbol) { - classTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 58728539 /* SomeType */, variableDeclaration); + classTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 58728795 /* SomeType */, variableDeclaration); } } @@ -52060,20 +53421,8 @@ var TypeScript; } if (!moduleContainerTypeSymbol) { - var parentDecl = variableDeclaration.getParentDecl(); - - if (parentDecl) { - var searchKind = (declFlags & (32768 /* InitializedModule */ | 65536 /* InitializedDynamicModule */)) ? 164 /* SomeContainer */ : 64 /* Enum */; - var childDecls = parentDecl.searchChildDecls(declName, searchKind); - - if (childDecls.length) { - for (var i = 0; i < childDecls.length; i++) { - if (childDecls[i].getValueDecl() === variableDeclaration) { - moduleContainerTypeSymbol = childDecls[i].getSymbol(); - } - } - } - } + var containerDecl = variableDeclaration.getContainerDecl(); + moduleContainerTypeSymbol = containerDecl.getSymbol(); if (!moduleContainerTypeSymbol) { moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 164 /* SomeContainer */, variableDeclaration); @@ -52089,6 +53438,10 @@ var TypeScript; if (moduleContainerTypeSymbol) { variableSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + variableSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } if (!variableSymbol.hasDeclaration(variableDeclaration)) { variableSymbol.addDeclaration(variableDeclaration); @@ -52105,6 +53458,11 @@ var TypeScript; variableDeclaration.setSymbol(variableSymbol); } + var containerDecl = variableDeclaration.getContainerDecl(); + if (variableSymbol && variableSymbol.type && containerDecl && !variableSymbol.type.hasDeclaration(containerDecl)) { + variableSymbol.type.addDeclaration(containerDecl); + } + if (parent && !parentHadSymbol) { if (declFlags & 1 /* Exported */) { parent.addMember(variableSymbol); @@ -52112,14 +53470,6 @@ var TypeScript; parent.addEnclosedNonMember(variableSymbol); } } - - var otherDecls = this.findDeclsInContext(variableDeclaration, variableDeclaration.kind, false); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } }; PullSymbolBinder.prototype.bindCatchVariableToPullSymbol = function (variableDeclaration) { @@ -52153,7 +53503,7 @@ var TypeScript; var propertySymbol = parent.findMember(declName, false); if (propertySymbol) { - this.semanticInfoChain.addDiagnostic(TypeScript.diagnosticFromDecl(propertyDeclaration, TypeScript.DiagnosticCode.Duplicate_identifier_0, [propertyDeclaration.getDisplayName()])); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(propDeclAST.propertyName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); } if (propertySymbol) { @@ -52208,7 +53558,7 @@ var TypeScript; propertySymbol = parent.findMember(declName, false); if (propertySymbol) { - this.semanticInfoChain.addDiagnostic(TypeScript.diagnosticFromDecl(propertyDeclaration, TypeScript.DiagnosticCode.Duplicate_identifier_0, [propertyDeclaration.getDisplayName()])); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(astName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); } if (propertySymbol) { @@ -52253,28 +53603,33 @@ var TypeScript; parameterSymbol.isVarArg = true; } - if (decl.flags & 128 /* Optional */) { - parameterSymbol.isOptional = true; - } - if (params[id.valueText()]) { this.semanticInfoChain.addDiagnosticFromAST(argDecl, TypeScript.DiagnosticCode.Duplicate_identifier_0, [id.text()]); } else { params[id.valueText()] = true; } + if (decl) { + var isParameterOptional = false; + if (isProperty) { decl.ensureSymbolIsBound(); var valDecl = decl.getValueDecl(); if (valDecl) { + isParameterOptional = TypeScript.hasFlag(valDecl.flags, 128 /* Optional */); + valDecl.setSymbol(parameterSymbol); parameterSymbol.addDeclaration(valDecl); } } else { + isParameterOptional = TypeScript.hasFlag(decl.flags, 128 /* Optional */); + parameterSymbol.addDeclaration(decl); decl.setSymbol(parameterSymbol); } + + parameterSymbol.isOptional = isParameterOptional; } signatureSymbol.addParameter(parameterSymbol, parameterSymbol.isOptional); @@ -52298,6 +53653,7 @@ var TypeScript; var isSignature = (declFlags & 2048 /* Signature */) !== 0; var parent = this.getParent(functionDeclaration, true); + var parentDecl = functionDeclaration.getParentDecl(); var parentHadSymbol = false; @@ -52307,11 +53663,21 @@ var TypeScript; functionSymbol = this.getExistingSymbol(functionDeclaration, 68147712 /* SomeValue */, parent); if (functionSymbol) { - var previousIsAmbient = functionSymbol.allDeclsHaveFlag(8 /* Ambient */); - var isAmbientOrPreviousIsAmbient = previousIsAmbient || functionDeclaration.flags & 8 /* Ambient */; - var acceptableRedeclaration = functionSymbol.kind === 16384 /* Function */ && (isSignature || functionSymbol.allDeclsHaveFlag(2048 /* Signature */)) || functionSymbol.allDeclsHaveFlag(32768 /* InitializedModule */) && isAmbientOrPreviousIsAmbient; + var acceptableRedeclaration; + + if (functionSymbol.kind === 16384 /* Function */) { + acceptableRedeclaration = isSignature || functionSymbol.allDeclsHaveFlag(2048 /* Signature */); + } else { + var isCurrentDeclAmbient = TypeScript.hasFlag(functionDeclaration.flags, 8 /* Ambient */); + acceptableRedeclaration = TypeScript.ArrayUtilities.all(functionSymbol.getDeclarations(), function (decl) { + var isInitializedModuleOrAmbientDecl = TypeScript.hasFlag(decl.flags, 32768 /* InitializedModule */) && (isCurrentDeclAmbient || TypeScript.hasFlag(decl.flags, 8 /* Ambient */)); + var isSignature = TypeScript.hasFlag(decl.flags, 2048 /* Signature */); + return isInitializedModuleOrAmbientDecl || isSignature; + }); + } + if (!acceptableRedeclaration) { - this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [functionDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.identifier, functionDeclaration.getDisplayName(), functionSymbol.getDeclarations()[0].ast()); functionSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(funcName); } } @@ -52346,7 +53712,7 @@ var TypeScript; } } - var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); signature.addDeclaration(functionDeclaration); functionDeclaration.setSignatureSymbol(signature); @@ -52356,7 +53722,7 @@ var TypeScript; } var funcDecl = this.semanticInfoChain.getASTForDecl(functionDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(funcDecl.callSignature.parameterList), functionTypeSymbol, signature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), functionTypeSymbol, signature); var typeParameters = functionDeclaration.getTypeParameters(); var typeParameter; @@ -52365,7 +53731,7 @@ var TypeScript; typeParameter = signature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); signature.addTypeParameter(typeParameter); } else { @@ -52377,15 +53743,7 @@ var TypeScript; typeParameters[i].setSymbol(typeParameter); } - functionTypeSymbol.addCallSignature(signature); - - var otherDecls = this.findDeclsInContext(functionDeclaration, functionDeclaration.kind, false); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } + functionTypeSymbol.appendCallSignature(signature); }; PullSymbolBinder.prototype.bindFunctionExpressionToPullSymbol = function (functionExpressionDeclaration) { @@ -52393,10 +53751,10 @@ var TypeScript; var declFlags = functionExpressionDeclaration.flags; var ast = this.semanticInfoChain.getASTForDecl(functionExpressionDeclaration); - var parameters = ast.kind() === 219 /* SimpleArrowFunctionExpression */ ? TypeScript.Parameters.fromIdentifier(ast.identifier) : TypeScript.Parameters.fromParameterList(TypeScript.getParameterList(ast)); + var parameters = ast.kind() === 219 /* SimpleArrowFunctionExpression */ ? TypeScript.ASTHelpers.parametersFromIdentifier(ast.identifier) : TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(ast)); var funcExpAST = ast; - var functionName = declKind == 131072 /* FunctionExpression */ ? functionExpressionDeclaration.getFunctionExpressionName() : functionExpressionDeclaration.name; + var functionName = declKind === 131072 /* FunctionExpression */ ? functionExpressionDeclaration.getFunctionExpressionName() : functionExpressionDeclaration.name; var functionSymbol = new TypeScript.PullSymbol(functionName, declKind); var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); functionTypeSymbol.setFunctionSymbol(functionSymbol); @@ -52414,7 +53772,7 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(funcExpAST, functionSymbol); - var signature = new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, true); if (parameters.lastParameterIsRest()) { signature.hasVarArgs = true; @@ -52427,7 +53785,7 @@ var TypeScript; typeParameter = signature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); signature.addTypeParameter(typeParameter); } else { @@ -52444,7 +53802,7 @@ var TypeScript; this.bindParameterSymbols(funcExpAST, parameters, functionTypeSymbol, signature); - functionTypeSymbol.addCallSignature(signature); + functionTypeSymbol.appendCallSignature(signature); }; PullSymbolBinder.prototype.bindFunctionTypeDeclarationToPullSymbol = function (functionTypeDeclaration) { @@ -52459,7 +53817,7 @@ var TypeScript; this.semanticInfoChain.setSymbolForAST(funcTypeAST, functionTypeSymbol); var isSignature = (declFlags & 2048 /* Signature */) !== 0; - var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); if (TypeScript.lastParameterIsRest(funcTypeAST.parameterList)) { signature.hasVarArgs = true; @@ -52472,7 +53830,7 @@ var TypeScript; typeParameter = signature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); signature.addTypeParameter(typeParameter); } else { @@ -52487,9 +53845,9 @@ var TypeScript; signature.addDeclaration(functionTypeDeclaration); functionTypeDeclaration.setSignatureSymbol(signature); - this.bindParameterSymbols(funcTypeAST, TypeScript.Parameters.fromParameterList(funcTypeAST.parameterList), functionTypeSymbol, signature); + this.bindParameterSymbols(funcTypeAST, TypeScript.ASTHelpers.parametersFromParameterList(funcTypeAST.parameterList), functionTypeSymbol, signature); - functionTypeSymbol.addCallSignature(signature); + functionTypeSymbol.appendCallSignature(signature); }; PullSymbolBinder.prototype.bindMethodDeclarationToPullSymbol = function (methodDeclaration) { @@ -52518,7 +53876,7 @@ var TypeScript; methodSymbol = parent.findMember(methodName, false); if (methodSymbol && (methodSymbol.kind !== 65536 /* Method */ || (!isSignature && !methodSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { - this.semanticInfoChain.addDiagnosticFromAST(methodAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [methodDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(methodAST, methodDeclaration.getDisplayName(), methodSymbol.getDeclarations()[0].ast()); methodSymbol = null; } @@ -52558,9 +53916,9 @@ var TypeScript; var sigKind = 1048576 /* CallSignature */; - var signature = isSignature ? new TypeScript.PullSignatureSymbol(sigKind) : new TypeScript.PullDefinitionSignatureSymbol(sigKind); + var signature = new TypeScript.PullSignatureSymbol(sigKind, !isSignature); - var parameterList = TypeScript.getParameterList(methodAST); + var parameterList = TypeScript.ASTHelpers.getParameterList(methodAST); if (TypeScript.lastParameterIsRest(parameterList)) { signature.hasVarArgs = true; } @@ -52577,7 +53935,7 @@ var TypeScript; typeParameter = signature.findTypeParameter(typeParameterName); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName); signature.addTypeParameter(typeParameter); } else { this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); @@ -52591,29 +53949,22 @@ var TypeScript; methodDeclaration.setSignatureSymbol(signature); var funcDecl = this.semanticInfoChain.getASTForDecl(methodDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(TypeScript.getParameterList(funcDecl)), methodTypeSymbol, signature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), methodTypeSymbol, signature); - methodTypeSymbol.addCallSignature(signature); - - var otherDecls = this.findDeclsInContext(methodDeclaration, methodDeclaration.kind, false); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(signature, methodTypeSymbol.getOwnCallSignatures()); + methodTypeSymbol.insertCallSignatureAtIndex(signature, signatureIndex); }; - PullSymbolBinder.prototype.bindStaticPrototypePropertyOfClass = function (classTypeSymbol, constructorTypeSymbol) { + PullSymbolBinder.prototype.bindStaticPrototypePropertyOfClass = function (classAST, classTypeSymbol, constructorTypeSymbol) { var prototypeStr = "prototype"; var prototypeSymbol = constructorTypeSymbol.findMember(prototypeStr, false); if (prototypeSymbol && !prototypeSymbol.getIsSynthesized()) { - this.semanticInfoChain.addDiagnostic(TypeScript.diagnosticFromDecl(prototypeSymbol.getDeclarations()[0], TypeScript.DiagnosticCode.Duplicate_identifier_0, [prototypeSymbol.getDisplayName()])); + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(prototypeSymbol.getDeclarations()[0], TypeScript.DiagnosticCode.Duplicate_identifier_0, [prototypeSymbol.getDisplayName()])); } if (!prototypeSymbol || !prototypeSymbol.getIsSynthesized()) { - var prototypeDecl = new TypeScript.PullSynthesizedDecl(prototypeStr, prototypeStr, 4096 /* Property */, 4 /* Public */ | 16 /* Static */, constructorTypeSymbol.getDeclarations()[0], classTypeSymbol.getDeclarations()[0].getSpan(), this.semanticInfoChain); + var prototypeDecl = new TypeScript.PullSynthesizedDecl(prototypeStr, prototypeStr, 4096 /* Property */, 4 /* Public */ | 16 /* Static */, constructorTypeSymbol.getDeclarations()[0], this.semanticInfoChain); prototypeSymbol = new TypeScript.PullSymbol(prototypeStr, 4096 /* Property */); prototypeSymbol.setIsSynthesized(); @@ -52679,36 +54030,20 @@ var TypeScript; constructorSymbol.setIsSynthesized(false); this.semanticInfoChain.setSymbolForAST(constructorAST, constructorSymbol); - var constructSignature = isSignature ? new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */) : new TypeScript.PullDefinitionSignatureSymbol(2097152 /* ConstructSignature */); - + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */, !isSignature); constructSignature.returnType = parent; + constructSignature.addTypeParametersFromReturnType(); constructSignature.addDeclaration(constructorDeclaration); constructorDeclaration.setSignatureSymbol(constructSignature); - this.bindParameterSymbols(constructorAST, TypeScript.Parameters.fromParameterList(constructorAST.parameterList), constructorTypeSymbol, constructSignature); + this.bindParameterSymbols(constructorAST, TypeScript.ASTHelpers.parametersFromParameterList(constructorAST.callSignature.parameterList), constructorTypeSymbol, constructSignature); - var typeParameters = constructorTypeSymbol.getTypeParameters(); - - for (var i = 0; i < typeParameters.length; i++) { - constructSignature.addTypeParameter(typeParameters[i]); - } - - if (TypeScript.lastParameterIsRest(constructorAST.parameterList)) { + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { constructSignature.hasVarArgs = true; } - constructorTypeSymbol.addConstructSignature(constructSignature); - - var otherDecls = this.findDeclsInContext(constructorDeclaration, constructorDeclaration.kind, false); - - if (otherDecls && otherDecls.length) { - for (var i = 0; i < otherDecls.length; i++) { - otherDecls[i].ensureSymbolIsBound(); - } - } - - this.bindStaticPrototypePropertyOfClass(parent, constructorTypeSymbol); + constructorTypeSymbol.appendConstructSignature(constructSignature); }; PullSymbolBinder.prototype.bindConstructSignatureDeclarationToPullSymbol = function (constructSignatureDeclaration) { @@ -52728,7 +54063,7 @@ var TypeScript; typeParameter = constructSignature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); constructSignature.addTypeParameter(typeParameter); } else { @@ -52744,11 +54079,12 @@ var TypeScript; constructSignatureDeclaration.setSignatureSymbol(constructSignature); var funcDecl = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(TypeScript.getParameterList(funcDecl)), null, constructSignature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), null, constructSignature); this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration), constructSignature); - parent.addConstructSignature(constructSignature); + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(constructSignature, parent.getOwnConstructSignatures()); + parent.insertConstructSignatureAtIndex(constructSignature, signatureIndex); }; PullSymbolBinder.prototype.bindCallSignatureDeclarationToPullSymbol = function (callSignatureDeclaration) { @@ -52768,7 +54104,7 @@ var TypeScript; typeParameter = callSignature.findTypeParameter(typeParameters[i].name); if (!typeParameter) { - typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name, true); + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); callSignature.addTypeParameter(typeParameter); } else { @@ -52784,11 +54120,12 @@ var TypeScript; callSignatureDeclaration.setSignatureSymbol(callSignature); var funcDecl = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameterList(funcDecl.parameterList), null, callSignature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), null, callSignature); this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(callSignatureDeclaration), callSignature); - parent.addCallSignature(callSignature); + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(callSignature, parent.getOwnCallSignatures()); + parent.insertCallSignatureAtIndex(callSignature, signatureIndex); }; PullSymbolBinder.prototype.bindIndexSignatureDeclarationToPullSymbol = function (indexSignatureDeclaration) { @@ -52798,7 +54135,7 @@ var TypeScript; indexSignatureDeclaration.setSignatureSymbol(indexSignature); var funcDecl = this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration); - this.bindParameterSymbols(funcDecl, TypeScript.Parameters.fromParameter(funcDecl.parameter), null, indexSignature); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter), null, indexSignature); this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration), indexSignature); @@ -52838,7 +54175,7 @@ var TypeScript; if (accessorSymbol) { if (!accessorSymbol.isAccessor()) { - this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [getAccessorDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, getAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); accessorSymbol = null; } else { getterSymbol = accessorSymbol.getGetter(); @@ -52885,14 +54222,14 @@ var TypeScript; parent.addMember(accessorSymbol); } - var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); signature.addDeclaration(getAccessorDeclaration); getAccessorDeclaration.setSignatureSymbol(signature); - this.bindParameterSymbols(funcDeclAST, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), getterTypeSymbol, signature); + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), getterTypeSymbol, signature); - getterTypeSymbol.addCallSignature(signature); + getterTypeSymbol.appendCallSignature(signature); }; PullSymbolBinder.prototype.bindSetAccessorDeclarationToPullSymbol = function (setAccessorDeclaration) { @@ -52926,7 +54263,7 @@ var TypeScript; if (accessorSymbol) { if (!accessorSymbol.isAccessor()) { - this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [setAccessorDeclaration.getDisplayName()]); + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, setAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); accessorSymbol = null; } else { setterSymbol = accessorSymbol.getSetter(); @@ -52973,25 +54310,63 @@ var TypeScript; parent.addMember(accessorSymbol); } - var signature = isSignature ? new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */) : new TypeScript.PullDefinitionSignatureSymbol(1048576 /* CallSignature */); + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); signature.addDeclaration(setAccessorDeclaration); setAccessorDeclaration.setSignatureSymbol(signature); - this.bindParameterSymbols(funcDeclAST, TypeScript.Parameters.fromParameterList(funcDeclAST.parameterList), setterTypeSymbol, signature); + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), setterTypeSymbol, signature); - setterTypeSymbol.addCallSignature(signature); + setterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.getDeclsToBind = function (decl) { + var decls; + switch (decl.kind) { + case 64 /* Enum */: + case 32 /* DynamicModule */: + case 4 /* Container */: + case 16 /* Interface */: + decls = this.findDeclsInContext(decl, decl.kind, true); + break; + + case 512 /* Variable */: + case 16384 /* Function */: + case 65536 /* Method */: + case 32768 /* ConstructorMethod */: + decls = this.findDeclsInContext(decl, decl.kind, false); + break; + + default: + decls = [decl]; + } + TypeScript.Debug.assert(decls && decls.length > 0); + TypeScript.Debug.assert(TypeScript.ArrayUtilities.contains(decls, decl)); + return decls; + }; + + PullSymbolBinder.prototype.shouldBindDeclaration = function (decl) { + return !decl.hasBeenBound() && this.declsBeingBound.indexOf(decl.declID) < 0; }; PullSymbolBinder.prototype.bindDeclToPullSymbol = function (decl) { - if (decl.hasBeenBound()) { - return; + if (this.shouldBindDeclaration(decl)) { + this.bindAllDeclsToPullSymbol(decl); } + }; - if (this.declsBeingBound.indexOf(decl.declID) >= 0) { - return; + PullSymbolBinder.prototype.bindAllDeclsToPullSymbol = function (askedDecl) { + var allDecls = this.getDeclsToBind(askedDecl); + for (var i = 0; i < allDecls.length; i++) { + var decl = allDecls[i]; + + if (this.shouldBindDeclaration(decl)) { + this.bindSingleDeclToPullSymbol(decl); + } } + }; + PullSymbolBinder.prototype.bindSingleDeclToPullSymbol = function (decl) { this.declsBeingBound.push(decl.declID); switch (decl.kind) { @@ -53110,6 +54485,25 @@ var TypeScript; var TypeScript; (function (TypeScript) { (function (PullHelpers) { + function diagnosticFromDecl(decl, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + var ast = decl.ast(); + return decl.semanticInfoChain.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations); + } + PullHelpers.diagnosticFromDecl = diagnosticFromDecl; + + function resolveDeclaredSymbolToUseType(symbol) { + if (symbol.isSignature()) { + if (!symbol.returnType) { + symbol._resolveDeclaredSymbol(); + } + } else if (!symbol.type) { + symbol._resolveDeclaredSymbol(); + } + } + PullHelpers.resolveDeclaredSymbolToUseType = resolveDeclaredSymbolToUseType; + function getSignatureForFuncDecl(functionDecl) { var funcDecl = functionDecl.ast(); var funcSymbol = functionDecl.getSymbol(); @@ -53180,7 +54574,7 @@ var TypeScript; PullHelpers.symbolIsEnum = symbolIsEnum; function symbolIsModule(symbol) { - return symbol && (symbol.kind == 4 /* Container */ || isOneDeclarationOfKind(symbol, 4 /* Container */)); + return symbol && (symbol.kind === 4 /* Container */ || isOneDeclarationOfKind(symbol, 4 /* Container */)); } PullHelpers.symbolIsModule = symbolIsModule; @@ -53209,7 +54603,7 @@ var TypeScript; b = b.referencedTypeSymbol; } - return a == b; + return a === b; } PullHelpers.typeSymbolsAreIdentical = typeSymbolsAreIdentical; @@ -53217,7 +54611,7 @@ var TypeScript; var rootType = type.getRootSymbol(); while (true) { - if (type == rootType) { + if (type === rootType) { return type; } @@ -53235,7 +54629,7 @@ var TypeScript; return true; } - if (containerKind == 33554432 /* ConstructorType */ && !symbol.anyDeclHasFlag(16 /* Static */)) { + if (containerKind === 33554432 /* ConstructorType */ && !symbol.anyDeclHasFlag(16 /* Static */ | 1 /* Exported */)) { return true; } } @@ -53243,9 +54637,300 @@ var TypeScript; return false; } PullHelpers.isSymbolLocal = isSymbolLocal; + + function isExportedSymbolInClodule(symbol) { + var container = symbol.getContainer(); + return container && container.kind === 33554432 /* ConstructorType */ && symbolIsModule(container) && symbol.anyDeclHasFlag(1 /* Exported */); + } + PullHelpers.isExportedSymbolInClodule = isExportedSymbolInClodule; + + + + function walkSignatureSymbol(signatureSymbol, walker) { + var continueWalk = true; + var parameters = signatureSymbol.parameters; + if (parameters) { + for (var i = 0; continueWalk && i < parameters.length; i++) { + continueWalk = walker.signatureParameterWalk(parameters[i]); + } + } + + if (continueWalk) { + continueWalk = walker.signatureReturnTypeWalk(signatureSymbol.returnType); + } + + return continueWalk; + } + + function walkPullTypeSymbolStructure(typeSymbol, walker) { + var continueWalk = true; + + var members = typeSymbol.getMembers(); + for (var i = 0; continueWalk && i < members.length; i++) { + continueWalk = walker.memberSymbolWalk(members[i]); + } + + if (continueWalk) { + var callSigantures = typeSymbol.getCallSignatures(); + for (var i = 0; continueWalk && i < callSigantures.length; i++) { + continueWalk = walker.callSignatureWalk(callSigantures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(callSigantures[i], walker); + } + } + } + + if (continueWalk) { + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; continueWalk && i < constructSignatures.length; i++) { + continueWalk = walker.constructSignatureWalk(constructSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(constructSignatures[i], walker); + } + } + } + + if (continueWalk) { + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; continueWalk && i < indexSignatures.length; i++) { + continueWalk = walker.indexSignatureWalk(indexSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(indexSignatures[i], walker); + } + } + } + } + PullHelpers.walkPullTypeSymbolStructure = walkPullTypeSymbolStructure; + + var OtherPullDeclsWalker = (function () { + function OtherPullDeclsWalker() { + this.currentlyWalkingOtherDecls = []; + } + OtherPullDeclsWalker.prototype.walkOtherPullDecls = function (currentDecl, otherDecls, callBack) { + if (otherDecls) { + var isAlreadyWalkingOtherDecl = TypeScript.ArrayUtilities.any(this.currentlyWalkingOtherDecls, function (inWalkingOtherDecl) { + return TypeScript.ArrayUtilities.contains(otherDecls, inWalkingOtherDecl); + }); + + if (!isAlreadyWalkingOtherDecl) { + this.currentlyWalkingOtherDecls.push(currentDecl); + for (var i = 0; i < otherDecls.length; i++) { + if (otherDecls[i] !== currentDecl) { + callBack(otherDecls[i]); + } + } + var currentlyWalkingOtherDeclsDecl = this.currentlyWalkingOtherDecls.pop(); + TypeScript.Debug.assert(currentlyWalkingOtherDeclsDecl == currentDecl); + } + } + }; + return OtherPullDeclsWalker; + })(); + PullHelpers.OtherPullDeclsWalker = OtherPullDeclsWalker; })(TypeScript.PullHelpers || (TypeScript.PullHelpers = {})); var PullHelpers = TypeScript.PullHelpers; })(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var WrapsTypeParameterCache = (function () { + function WrapsTypeParameterCache() { + this._wrapsTypeParameterCache = TypeScript.BitVector.getBitVector(true); + } + WrapsTypeParameterCache.prototype.getWrapsTypeParameter = function (typeParameterArgumentMap) { + var mapHasTypeParameterNotCached = false; + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + var cachedValue = this._wrapsTypeParameterCache.valueAt(typeParameterID); + if (cachedValue) { + return typeParameterID; + } + mapHasTypeParameterNotCached = mapHasTypeParameterNotCached || cachedValue === undefined; + } + } + + if (!mapHasTypeParameterNotCached) { + return 0; + } + + return undefined; + }; + + WrapsTypeParameterCache.prototype.setWrapsTypeParameter = function (typeParameterArgumentMap, wrappingTypeParameterID) { + if (wrappingTypeParameterID) { + this._wrapsTypeParameterCache.setValueAt(wrappingTypeParameterID, true); + } else { + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + this._wrapsTypeParameterCache.setValueAt(typeParameterID, false); + } + } + } + }; + return WrapsTypeParameterCache; + })(); + TypeScript.WrapsTypeParameterCache = WrapsTypeParameterCache; + + (function (PullInstantiationHelpers) { + var MutableTypeArgumentMap = (function () { + function MutableTypeArgumentMap(typeParameterArgumentMap) { + this.typeParameterArgumentMap = typeParameterArgumentMap; + this.createdDuplicateTypeArgumentMap = false; + } + MutableTypeArgumentMap.prototype.ensureTypeArgumentCopy = function () { + if (!this.createdDuplicateTypeArgumentMap) { + var passedInTypeArgumentMap = this.typeParameterArgumentMap; + this.typeParameterArgumentMap = []; + for (var typeParameterID in passedInTypeArgumentMap) { + if (passedInTypeArgumentMap.hasOwnProperty(typeParameterID)) { + this.typeParameterArgumentMap[typeParameterID] = passedInTypeArgumentMap[typeParameterID]; + } + } + this.createdDuplicateTypeArgumentMap = true; + } + }; + return MutableTypeArgumentMap; + })(); + PullInstantiationHelpers.MutableTypeArgumentMap = MutableTypeArgumentMap; + + function instantiateTypeArgument(resolver, symbol, mutableTypeParameterMap) { + if (symbol.getIsSpecialized()) { + var rootTypeArgumentMap = symbol.getTypeParameterArgumentMap(); + var newTypeArgumentMap = []; + var allowedTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + var typeArg = rootTypeArgumentMap[typeParameterID]; + if (typeArg) { + newTypeArgumentMap[typeParameterID] = resolver.instantiateType(typeArg, mutableTypeParameterMap.typeParameterArgumentMap); + } + } + + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + if (newTypeArgumentMap[typeParameterID] && mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] != newTypeArgumentMap[typeParameterID]) { + mutableTypeParameterMap.ensureTypeArgumentCopy(); + mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] = newTypeArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.instantiateTypeArgument = instantiateTypeArgument; + + function cleanUpTypeArgumentMap(symbol, mutableTypeArgumentMap) { + var allowedToReferenceTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var typeParameterID in mutableTypeArgumentMap.typeParameterArgumentMap) { + if (mutableTypeArgumentMap.typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + if (!TypeScript.ArrayUtilities.any(allowedToReferenceTypeParameters, function (typeParameter) { + return typeParameter.pullSymbolID == typeParameterID; + })) { + mutableTypeArgumentMap.ensureTypeArgumentCopy(); + delete mutableTypeArgumentMap.typeParameterArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.cleanUpTypeArgumentMap = cleanUpTypeArgumentMap; + + function getAllowedToReferenceTypeParametersFromDecl(decl) { + var allowedToReferenceTypeParameters = []; + + var allowedToUseDeclTypeParameters = false; + var getTypeParametersFromParentDecl = false; + + switch (decl.kind) { + case 65536 /* Method */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + allowedToUseDeclTypeParameters = true; + break; + } + + case 16777216 /* FunctionType */: + case 33554432 /* ConstructorType */: + case 2097152 /* ConstructSignature */: + case 1048576 /* CallSignature */: + case 131072 /* FunctionExpression */: + case 16384 /* Function */: + allowedToUseDeclTypeParameters = true; + getTypeParametersFromParentDecl = true; + break; + + case 4096 /* Property */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + break; + } + + case 2048 /* Parameter */: + case 262144 /* GetAccessor */: + case 524288 /* SetAccessor */: + case 32768 /* ConstructorMethod */: + case 4194304 /* IndexSignature */: + case 8388608 /* ObjectType */: + case 256 /* ObjectLiteral */: + case 8192 /* TypeParameter */: + getTypeParametersFromParentDecl = true; + break; + + case 8 /* Class */: + case 16 /* Interface */: + allowedToUseDeclTypeParameters = true; + break; + } + + if (getTypeParametersFromParentDecl) { + allowedToReferenceTypeParameters = allowedToReferenceTypeParameters.concat(getAllowedToReferenceTypeParametersFromDecl(decl.getParentDecl())); + } + + if (allowedToUseDeclTypeParameters) { + var typeParameterDecls = decl.getTypeParameters(); + for (var i = 0; i < typeParameterDecls.length; i++) { + allowedToReferenceTypeParameters.push(typeParameterDecls[i].getSymbol()); + } + } + + return allowedToReferenceTypeParameters; + } + PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl = getAllowedToReferenceTypeParametersFromDecl; + + function createTypeParameterArgumentMap(typeParameters, typeArguments) { + return updateTypeParameterArgumentMap(typeParameters, typeArguments, {}); + } + PullInstantiationHelpers.createTypeParameterArgumentMap = createTypeParameterArgumentMap; + + function updateTypeParameterArgumentMap(typeParameters, typeArguments, typeParameterArgumentMap) { + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].getRootSymbol().pullSymbolID] = typeArguments[i]; + } + return typeParameterArgumentMap; + } + PullInstantiationHelpers.updateTypeParameterArgumentMap = updateTypeParameterArgumentMap; + + function updateMutableTypeParameterArgumentMap(typeParameters, typeArguments, mutableMap) { + for (var i = 0; i < typeParameters.length; i++) { + var typeParameterId = typeParameters[i].getRootSymbol().pullSymbolID; + if (mutableMap.typeParameterArgumentMap[typeParameterId] !== typeArguments[i]) { + mutableMap.ensureTypeArgumentCopy(); + mutableMap.typeParameterArgumentMap[typeParameterId] = typeArguments[i]; + } + } + } + PullInstantiationHelpers.updateMutableTypeParameterArgumentMap = updateMutableTypeParameterArgumentMap; + + function twoTypesAreInstantiationsOfSameNamedGenericType(type1, type2) { + var type1IsGeneric = type1.isGeneric() && type1.getTypeArguments() !== null; + var type2IsGeneric = type2.isGeneric() && type2.getTypeArguments() !== null; + + if (type1IsGeneric && type2IsGeneric) { + var type1Root = TypeScript.PullHelpers.getRootType(type1); + var type2Root = TypeScript.PullHelpers.getRootType(type2); + return type1Root === type2Root; + } + + return false; + } + PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType = twoTypesAreInstantiationsOfSameNamedGenericType; + })(TypeScript.PullInstantiationHelpers || (TypeScript.PullInstantiationHelpers = {})); + var PullInstantiationHelpers = TypeScript.PullInstantiationHelpers; +})(TypeScript || (TypeScript = {})); if (Error) Error.stackTraceLimit = 1000; @@ -53286,10 +54971,19 @@ var TypeScript; TypeScript.ioHostCreateDirectoryStructureTime = 0; TypeScript.ioHostWriteFileTime = 0; + (function (EmitOutputResult) { + EmitOutputResult[EmitOutputResult["Succeeded"] = 0] = "Succeeded"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfSyntaxErrors"] = 1] = "FailedBecauseOfSyntaxErrors"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfCompilerOptionsErrors"] = 2] = "FailedBecauseOfCompilerOptionsErrors"; + EmitOutputResult[EmitOutputResult["FailedToGenerateDeclarationsBecauseOfSemanticErrors"] = 3] = "FailedToGenerateDeclarationsBecauseOfSemanticErrors"; + })(TypeScript.EmitOutputResult || (TypeScript.EmitOutputResult = {})); + var EmitOutputResult = TypeScript.EmitOutputResult; + var EmitOutput = (function () { - function EmitOutput() { + function EmitOutput(emitOutputResult) { + if (typeof emitOutputResult === "undefined") { emitOutputResult = 0 /* Succeeded */; } this.outputFiles = []; - this.diagnostics = []; + this.emitOutputResult = emitOutputResult; } return EmitOutput; })(); @@ -53391,17 +55085,6 @@ var TypeScript; this.semanticInfoChain.removeDocument(fileName); }; - TypeScriptCompiler.prototype._isDynamicModuleCompilation = function () { - var fileNames = this.fileNames(); - for (var i = 0, n = fileNames.length; i < n; i++) { - var document = this.getDocument(fileNames[i]); - if (!document.isDeclareFile() && document.isExternalModule()) { - return true; - } - } - return false; - }; - TypeScriptCompiler.prototype.mapOutputFileName = function (document, emitOptions, extensionChanger) { if (document.emitToOwnOutputFile()) { var updatedFileName = document.fileName; @@ -53501,7 +55184,7 @@ var TypeScript; var emitOptions = new TypeScript.EmitOptions(this, resolvePath); if (emitOptions.diagnostic()) { - emitOutput.diagnostics.push(emitOptions.diagnostic()); + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; return emitOutput; } @@ -53533,7 +55216,7 @@ var TypeScript; var emitOptions = new TypeScript.EmitOptions(this, resolvePath); if (emitOptions.diagnostic()) { - emitOutput.diagnostics.push(emitOptions.diagnostic()); + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; return emitOutput; } @@ -53549,6 +55232,12 @@ var TypeScript; } }; + TypeScriptCompiler.prototype.canEmitDeclarations = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var document = this.getDocument(fileName); + return this._shouldEmitDeclarations(document); + }; + TypeScriptCompiler.mapToFileNameExtension = function (extension, fileName, wholeFileNameReplaced) { if (wholeFileNameReplaced) { return fileName; @@ -53609,7 +55298,7 @@ var TypeScript; var emitOptions = new TypeScript.EmitOptions(this, resolvePath); if (emitOptions.diagnostic()) { - emitOutput.diagnostics.push(emitOptions.diagnostic()); + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; return emitOutput; } @@ -53640,7 +55329,7 @@ var TypeScript; var emitOptions = new TypeScript.EmitOptions(this, resolvePath); if (emitOptions.diagnostic()) { - emitOutput.diagnostics.push(emitOptions.diagnostic()); + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; return emitOutput; } @@ -53715,6 +55404,15 @@ var TypeScript; return errors; }; + TypeScriptCompiler.prototype.getCompilerOptionsDiagnostics = function () { + var emitOptions = new TypeScript.EmitOptions(this, null); + var emitDiagnostic = emitOptions.diagnostic(); + if (emitDiagnostic) { + return [emitDiagnostic]; + } + return TypeScript.sentinelEmptyArray; + }; + TypeScriptCompiler.prototype.resolveAllFiles = function () { var fileNames = this.fileNames(); for (var i = 0, n = fileNames.length; i < n; i++) { @@ -53791,8 +55489,6 @@ var TypeScript; var contextualType = null; if ((i + 2 < n) && callExpression.argumentList === path[i + 1] && callExpression.argumentList.arguments === path[i + 2]) { - var arguments = callExpression.argumentList.arguments; - var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); if (isNew) { resolver.resolveObjectCreationExpression(callExpression, resolutionContext, callResolutionResults); @@ -53822,7 +55518,7 @@ var TypeScript; } } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); } break; @@ -53835,7 +55531,7 @@ var TypeScript; contextualType = currentContextualType.getElementType(); } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); } break; @@ -53862,7 +55558,7 @@ var TypeScript; } } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); } } @@ -53881,7 +55577,25 @@ var TypeScript; } } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 220 /* CastExpression */: + var castExpression = current; + if (!(i + 1 < n && path[i + 1] === castExpression.type)) { + if (propagateContextualTypes) { + var contextualType = null; + var typeSymbol = resolver.resolveAST(castExpression, inContextuallyTypedAssignment, resolutionContext).type; + + if (typeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = typeSymbol; + } + + resolutionContext.pushNewContextualType(contextualType); + } } break; @@ -53892,7 +55606,7 @@ var TypeScript; var contextualType = null; if (enclosingDecl && (enclosingDecl.kind & 1032192 /* SomeFunction */)) { - var typeAnnotation = TypeScript.getType(enclosingDeclAST); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); if (typeAnnotation) { var returnTypeSymbol = resolver.resolveTypeReference(typeAnnotation, resolutionContext); if (returnTypeSymbol) { @@ -53902,7 +55616,8 @@ var TypeScript; } else { var currentContextualType = resolutionContext.getContextualType(); if (currentContextualType && currentContextualType.isFunction()) { - var currentContextualTypeSignatureSymbol = currentContextualType.getDeclarations()[0].getSignatureSymbol(); + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; if (currentContextualTypeReturnTypeSymbol) { inContextuallyTypedAssignment = true; @@ -53912,7 +55627,7 @@ var TypeScript; } } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); } break; @@ -53927,6 +55642,10 @@ var TypeScript; case 163 /* WithStatement */: inWithBlock = true; break; + + case 146 /* Block */: + inContextuallyTypedAssignment = false; + break; } var decl = this.semanticInfoChain.getDeclForAST(current); @@ -53968,7 +55687,7 @@ var TypeScript; contextualType = varSymbol.type; } - resolutionContext.pushContextualType(contextualType, false, null); + resolutionContext.pushNewContextualType(contextualType); if (init) { resolver.resolveAST(init, inContextuallyTypedAssignment, resolutionContext); @@ -53999,7 +55718,7 @@ var TypeScript; var symbol = resolver.resolveAST(ast, context.inContextuallyTypedAssignment, context.resolutionContext); if (!symbol) { - TypeScript.Debug.assert(ast.kind() == 120 /* SourceUnit */, "No symbol was found for ast and ast was not source unit. Ast Kind: " + TypeScript.SyntaxKind[ast.kind()]); + TypeScript.Debug.assert(ast.kind() === 120 /* SourceUnit */, "No symbol was found for ast and ast was not source unit. Ast Kind: " + TypeScript.SyntaxKind[ast.kind()]); return null; } @@ -54140,6 +55859,32 @@ var TypeScript; TypeScriptCompiler.prototype.topLevelDecl = function (fileName) { return this.semanticInfoChain.topLevelDecl(fileName); }; + + TypeScriptCompiler.getLocationText = function (location) { + return location.fileName() + "(" + (location.line() + 1) + "," + (location.character() + 1) + ")"; + }; + + TypeScriptCompiler.getFullDiagnosticText = function (diagnostic) { + var result = ""; + if (diagnostic.fileName()) { + result += this.getLocationText(diagnostic) + ": "; + } + + result += diagnostic.message(); + + var additionalLocations = diagnostic.additionalLocations(); + if (additionalLocations.length > 0) { + result += " " + TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Additional_locations, null) + TypeScript.Environment.newLine; + + for (var i = 0, n = additionalLocations.length; i < n; i++) { + result += "\t" + this.getLocationText(additionalLocations[i]) + TypeScript.Environment.newLine; + } + } else { + result += TypeScript.Environment.newLine; + } + + return result; + }; return TypeScriptCompiler; })(); TypeScript.TypeScriptCompiler = TypeScriptCompiler; @@ -54220,11 +55965,11 @@ var TypeScript; case 0 /* Syntax */: case 1 /* Semantics */: - return this.index == this.fileNames.length; + return this.index === this.fileNames.length; case 3 /* Emit */: case 4 /* DeclarationEmit */: - return this.index == (this.fileNames.length + 1); + return this.index === (this.fileNames.length + 1); } return false; @@ -54344,10 +56089,10 @@ var TypeScript; function compareDataObjects(dst, src) { for (var e in dst) { - if (typeof dst[e] == "object") { + if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) return false; - } else if (typeof dst[e] != "function") { + } else if (typeof dst[e] !== "function") { if (dst[e] !== src[e]) return false; } @@ -54373,7 +56118,7 @@ var TypeScript; this.referencedTypeSymbol = referencedTypeSymbol; this.isResolved = true; - TypeScript.Debug.assert(referencedTypeSymbol != null, "Type root symbol may not be null"); + TypeScript.Debug.assert(referencedTypeSymbol !== null, "Type root symbol may not be null"); this.setRootSymbol(referencedTypeSymbol); @@ -54540,11 +56285,17 @@ var TypeScript; return this.referencedTypeSymbol.getTypeArgumentsOrTypeParameters(); }; - PullTypeReferenceSymbol.prototype.addCallSignature = function (callSignature) { - TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addCallSignature"); + PullTypeReferenceSymbol.prototype.appendCallSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendCallSignature"); }; - PullTypeReferenceSymbol.prototype.addConstructSignature = function (constructSignature) { - TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addConstructSignature"); + PullTypeReferenceSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertCallSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.appendConstructSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendConstructSignature"); + }; + PullTypeReferenceSymbol.prototype.insertConstructSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertConstructSignatureAtIndex"); }; PullTypeReferenceSymbol.prototype.addIndexSignature = function (indexSignature) { TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addIndexSignature"); @@ -54604,11 +56355,6 @@ var TypeScript; return this.referencedTypeSymbol.getTypesThatExplicitlyImplementThisType(); }; - PullTypeReferenceSymbol.prototype.hasBase = function (potentialBase, visited) { - if (typeof visited === "undefined") { visited = []; } - this.ensureReferencedTypeIsResolved(); - return this.referencedTypeSymbol.hasBase(potentialBase, visited); - }; PullTypeReferenceSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { this.ensureReferencedTypeIsResolved(); return this.referencedTypeSymbol.isValidBaseKind(baseType, isExtendedType); @@ -54653,25 +56399,26 @@ var TypeScript; TypeScript.nSpecializationsCreated = 0; TypeScript.nSpecializedSignaturesCreated = 0; + TypeScript.nSpecializedTypeParameterCreated = 0; var PullInstantiatedTypeReferenceSymbol = (function (_super) { __extends(PullInstantiatedTypeReferenceSymbol, _super); - function PullInstantiatedTypeReferenceSymbol(referencedTypeSymbol, _typeParameterArgumentMap) { + function PullInstantiatedTypeReferenceSymbol(referencedTypeSymbol, _typeParameterArgumentMap, isInstanceReferenceType) { _super.call(this, referencedTypeSymbol); this.referencedTypeSymbol = referencedTypeSymbol; this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.isInstanceReferenceType = isInstanceReferenceType; this._instantiatedMembers = null; this._allInstantiatedMemberNameCache = null; this._instantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); this._instantiatedCallSignatures = null; this._instantiatedConstructSignatures = null; this._instantiatedIndexSignatures = null; - this._typeArgumentReferences = null; + this._typeArgumentReferences = undefined; this._instantiatedConstructorMethod = null; this._instantiatedAssociatedContainerType = null; this._isArray = undefined; - this.isInstanceReferenceType = false; - this._generativeTypeClassification = 0 /* Unknown */; + this._generativeTypeClassification = []; TypeScript.nSpecializationsCreated++; } @@ -54680,72 +56427,43 @@ var TypeScript; }; PullInstantiatedTypeReferenceSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { - if (this._generativeTypeClassification == 0 /* Unknown */) { - var typeParameters = enclosingType.getTypeParameters(); - var typeReferenceTypeArguments = this.getRootSymbol().getTypeArguments(); - var referenceTypeArgument = null; - - if (!typeReferenceTypeArguments) { - var typeParametersMap = []; - - for (var i = 0; i < typeParameters.length; i++) { - typeParametersMap[typeParameters[i].pullSymbolID] = typeParameters[i]; - } - - var rootThis = TypeScript.PullHelpers.getRootType(this); - var wrapsSomeTypeParameters = rootThis.wrapsSomeTypeParameter(typeParametersMap); - - if (wrapsSomeTypeParameters && this.wrapsSomeNestedTypeIntoInfiniteExpansion(enclosingType)) { - this._generativeTypeClassification = 3 /* InfinitelyExpanding */; - } else if (wrapsSomeTypeParameters) { - this._generativeTypeClassification = 1 /* Open */; - } else { - this._generativeTypeClassification = 2 /* Closed */; - } - } else { - var i = 0; - - while (i < typeReferenceTypeArguments.length) { - referenceTypeArgument = typeReferenceTypeArguments[i].getRootSymbol(); - - if (referenceTypeArgument.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { - break; - } - - i++; - } - - if (i == typeParameters.length) { - this._generativeTypeClassification = 2 /* Closed */; - } - - if (this._generativeTypeClassification == 0 /* Unknown */) { - var i = 0; - - while ((this._generativeTypeClassification == 0 /* Unknown */) && (i < typeReferenceTypeArguments.length)) { - for (var j = 0; j < typeParameters.length; j++) { - if (typeParameters[j] == typeReferenceTypeArguments[i]) { - this._generativeTypeClassification = 1 /* Open */; - break; - } - } - - i++; - } - - if (this._generativeTypeClassification != 1 /* Open */) { - this._generativeTypeClassification = 3 /* InfinitelyExpanding */; - } - } - } + if (!this.isNamedTypeSymbol()) { + return 0 /* Unknown */; } - return this._generativeTypeClassification; + var generativeTypeClassification = this._generativeTypeClassification[enclosingType.pullSymbolID] || 0 /* Unknown */; + if (generativeTypeClassification === 0 /* Unknown */) { + var typeParameters = enclosingType.getTypeParameters(); + var enclosingTypeParameterMap = []; + for (var i = 0; i < typeParameters.length; i++) { + enclosingTypeParameterMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (typeArguments[i].wrapsSomeTypeParameter(enclosingTypeParameterMap, true)) { + generativeTypeClassification = 1 /* Open */; + break; + } + } + + if (generativeTypeClassification === 1 /* Open */) { + if (this.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType)) { + generativeTypeClassification = 3 /* InfinitelyExpanding */; + } + } else { + generativeTypeClassification = 2 /* Closed */; + } + + this._generativeTypeClassification[enclosingType.pullSymbolID] = generativeTypeClassification; + } + + return generativeTypeClassification; }; PullInstantiatedTypeReferenceSymbol.prototype.isArrayNamedTypeReference = function () { if (this._isArray === undefined) { - this._isArray = this.getRootSymbol().isArrayNamedTypeReference() || (this.getRootSymbol() == this._getResolver().getArrayNamedType()); + this._isArray = this.getRootSymbol().isArrayNamedTypeReference() || (this.getRootSymbol() === this._getResolver().getArrayNamedType()); } return this._isArray; }; @@ -54756,12 +56474,7 @@ var TypeScript; } var typeArguments = this.getTypeArguments(); - - if (typeArguments != null) { - return typeArguments[0]; - } - - return null; + return typeArguments ? typeArguments[0] : null; }; PullInstantiatedTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { @@ -54774,130 +56487,47 @@ var TypeScript; return this.referencedTypeSymbol; }; - PullInstantiatedTypeReferenceSymbol.create = function (resolver, type, typeParameterArgumentMap, instantiateFunctionTypeParameters) { - if (typeof instantiateFunctionTypeParameters === "undefined") { instantiateFunctionTypeParameters = false; } + PullInstantiatedTypeReferenceSymbol.create = function (resolver, type, typeParameterArgumentMap) { TypeScript.Debug.assert(resolver); + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(resolver, type, mutableTypeParameterMap); + var rootType = type.getRootSymbol(); - - var reconstructedTypeArgumentList = []; - var typeArguments = type.getTypeArguments(); - var typeParameters = rootType.getTypeParameters(); - - if (type.getIsSpecialized() && typeArguments && typeArguments.length) { - for (var i = 0; i < typeArguments.length; i++) { - reconstructedTypeArgumentList[reconstructedTypeArgumentList.length] = resolver.instantiateType(typeArguments[i], typeParameterArgumentMap, instantiateFunctionTypeParameters); - } - - for (var i = 0; i < typeArguments.length; i++) { - typeParameterArgumentMap[typeArguments[i].pullSymbolID] = reconstructedTypeArgumentList[i]; - } - } else { - var tyArg = null; - - for (var typeParameterID in typeParameterArgumentMap) { - if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { - tyArg = typeParameterArgumentMap[typeParameterID]; - - if (tyArg) { - reconstructedTypeArgumentList[reconstructedTypeArgumentList.length] = tyArg; - } - } - } + var instantiation = rootType.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiation) { + return instantiation; } - if (!instantiateFunctionTypeParameters) { - var instantiation = rootType.getSpecialization(reconstructedTypeArgumentList); + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(type, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; - if (instantiation) { - return instantiation; - } - } - - var isReferencedType = (type.kind & 8216 /* SomeInstantiatableType */) != 0; - - if (isReferencedType) { - if (typeParameters && reconstructedTypeArgumentList) { - if (typeParameters.length == reconstructedTypeArgumentList.length) { - for (var i = 0; i < typeParameters.length; i++) { - if (!TypeScript.PullHelpers.typeSymbolsAreIdentical(typeParameters[i], reconstructedTypeArgumentList[i])) { - isReferencedType = false; - break; - } - } - - if (isReferencedType) { - typeParameterArgumentMap = []; - } - } else { - isReferencedType = false; - } - } - } - - var instantiateRoot = isReferencedType; - - if (type.isTypeReference() && type.isGeneric()) { - var initializationMap = []; - - for (var typeParameterID in typeParameterArgumentMap) { - if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { - initializationMap[typeParameterID] = typeParameterArgumentMap[typeParameterID]; + var isInstanceReferenceType = (type.kind & 8216 /* SomeInstantiatableType */) != 0; + var resolvedTypeParameterArgumentMap = typeParameterArgumentMap; + if (isInstanceReferenceType) { + var typeParameters = rootType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + if (!TypeScript.PullHelpers.typeSymbolsAreIdentical(typeParameters[i], typeParameterArgumentMap[typeParameters[i].pullSymbolID])) { + isInstanceReferenceType = false; + break; } } - var oldMap = typeParameterArgumentMap; - - var outerTypeMap = type._typeParameterArgumentMap; - var innerSubstitution = null; - var outerSubstitution = null; - var canRelatePreInstantiatedTypeParametersToRootTypeParameters = true; - - for (var typeParameterID in outerTypeMap) { - if (outerTypeMap.hasOwnProperty(typeParameterID)) { - outerSubstitution = outerTypeMap[typeParameterID]; - innerSubstitution = typeParameterArgumentMap[outerSubstitution.pullSymbolID]; - - if (innerSubstitution && (!outerSubstitution.isTypeParameter() || !outerTypeMap[innerSubstitution.pullSymbolID] || !outerTypeMap[outerTypeMap[typeParameterID].pullSymbolID] || (outerTypeMap[outerTypeMap[typeParameterID].pullSymbolID] == outerSubstitution))) { - initializationMap[typeParameterID] = typeParameterArgumentMap[outerTypeMap[typeParameterID].pullSymbolID]; - - if (!outerSubstitution.isTypeParameter()) { - canRelatePreInstantiatedTypeParametersToRootTypeParameters = false; - } - } else { - canRelatePreInstantiatedTypeParametersToRootTypeParameters = false; - } - } - } - - if (canRelatePreInstantiatedTypeParametersToRootTypeParameters && typeParameters.length) { + if (isInstanceReferenceType) { typeParameterArgumentMap = []; - - for (var i = 0; i < typeParameters.length; i++) { - typeParameterArgumentMap[typeParameters[i].pullSymbolID] = initializationMap[typeParameters[i].pullSymbolID]; - } - - instantiateRoot = true; - } else { - typeParameterArgumentMap = initializationMap; } } - instantiation = new PullInstantiatedTypeReferenceSymbol(instantiateRoot ? rootType : type, typeParameterArgumentMap); + instantiation = new PullInstantiatedTypeReferenceSymbol(rootType, typeParameterArgumentMap, isInstanceReferenceType); - if (!instantiateFunctionTypeParameters) { - rootType.addSpecialization(instantiation, reconstructedTypeArgumentList); - } - - if (isReferencedType) { - instantiation.isInstanceReferenceType = true; - } + rootType.addSpecialization(instantiation, resolvedTypeParameterArgumentMap); return instantiation; }; PullInstantiatedTypeReferenceSymbol.prototype.isGeneric = function () { - return !!this.referencedTypeSymbol.getTypeParameters().length; + return this.getRootSymbol().isGeneric(); }; PullInstantiatedTypeReferenceSymbol.prototype.getTypeParameterArgumentMap = function () { @@ -54909,7 +56539,7 @@ var TypeScript; return this.getTypeParameters(); } - if (!this._typeArgumentReferences) { + if (this._typeArgumentReferences === undefined) { var typeParameters = this.referencedTypeSymbol.getTypeParameters(); if (typeParameters.length) { @@ -54929,6 +56559,8 @@ var TypeScript; } this._typeArgumentReferences = typeArguments; + } else { + this._typeArgumentReferences = null; } } @@ -54939,6 +56571,21 @@ var TypeScript; return this.getTypeArguments(); }; + PullInstantiatedTypeReferenceSymbol.prototype.populateInstantiatedMemberFromReferencedMember = function (referencedMember) { + var instantiatedMember; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(referencedMember); + + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + instantiatedMember = referencedMember; + } else { + instantiatedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + instantiatedMember.setRootSymbol(referencedMember); + instantiatedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + instantiatedMember.isOptional = referencedMember.isOptional; + } + this._instantiatedMemberNameCache[instantiatedMember.name] = instantiatedMember; + }; + PullInstantiatedTypeReferenceSymbol.prototype.getMembers = function () { this.ensureReferencedTypeIsResolved(); @@ -54959,21 +56606,10 @@ var TypeScript; this._getResolver().resolveDeclaredSymbol(referencedMember); if (!this._instantiatedMemberNameCache[referencedMember.name]) { - if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { - instantiatedMember = referencedMember; - } else { - instantiatedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); - instantiatedMember.setRootSymbol(referencedMember); - instantiatedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); - instantiatedMember.isOptional = referencedMember.isOptional; - } - - this._instantiatedMemberNameCache[instantiatedMember.name] = instantiatedMember; - } else { - instantiatedMember = this._instantiatedMemberNameCache[referencedMember.name]; + this.populateInstantiatedMemberFromReferencedMember(referencedMember); } - this._instantiatedMembers[this._instantiatedMembers.length] = instantiatedMember; + this._instantiatedMembers[this._instantiatedMembers.length] = this._instantiatedMemberNameCache[referencedMember.name]; } } @@ -54994,16 +56630,8 @@ var TypeScript; var referencedMemberSymbol = this.referencedTypeSymbol.findMember(name, lookInParent); if (referencedMemberSymbol) { - memberSymbol = new TypeScript.PullSymbol(referencedMemberSymbol.name, referencedMemberSymbol.kind); - memberSymbol.setRootSymbol(referencedMemberSymbol); - - this._getResolver().resolveDeclaredSymbol(referencedMemberSymbol); - - memberSymbol.type = this._getResolver().instantiateType(referencedMemberSymbol.type, this._typeParameterArgumentMap); - - memberSymbol.isOptional = referencedMemberSymbol.isOptional; - - this._instantiatedMemberNameCache[memberSymbol.name] = memberSymbol; + this.populateInstantiatedMemberFromReferencedMember(referencedMemberSymbol); + memberSymbol = this._instantiatedMemberNameCache[name]; } else { memberSymbol = null; } @@ -55070,6 +56698,9 @@ var TypeScript; if (!this._instantiatedConstructorMethod) { var referencedConstructorMethod = this.referencedTypeSymbol.getConstructorMethod(); this._instantiatedConstructorMethod = new TypeScript.PullSymbol(referencedConstructorMethod.name, referencedConstructorMethod.kind); + this._instantiatedConstructorMethod.setRootSymbol(referencedConstructorMethod); + this._instantiatedConstructorMethod.setResolved(); + this._instantiatedConstructorMethod.type = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedConstructorMethod.type, this._typeParameterArgumentMap); } @@ -55175,14 +56806,79 @@ var TypeScript; return this._instantiatedIndexSignatures; }; - - PullInstantiatedTypeReferenceSymbol.prototype.hasBase = function (potentialBase, visited) { - if (typeof visited === "undefined") { visited = []; } - return this.referencedTypeSymbol.hasBase(potentialBase, visited); - }; return PullInstantiatedTypeReferenceSymbol; })(PullTypeReferenceSymbol); TypeScript.PullInstantiatedTypeReferenceSymbol = PullInstantiatedTypeReferenceSymbol; + + var PullInstantiatedSignatureSymbol = (function (_super) { + __extends(PullInstantiatedSignatureSymbol, _super); + function PullInstantiatedSignatureSymbol(rootSignature, _typeParameterArgumentMap) { + _super.call(this, rootSignature.kind, rootSignature.isDefinition()); + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.setRootSymbol(rootSignature); + TypeScript.nSpecializedSignaturesCreated++; + + rootSignature.addSpecialization(this, _typeParameterArgumentMap); + } + PullInstantiatedSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedSignatureSymbol.prototype.getIsSpecialized = function () { + return true; + }; + + PullInstantiatedSignatureSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + + PullInstantiatedSignatureSymbol.prototype.getTypeParameters = function () { + var _this = this; + if (!this._typeParameters) { + var rootSymbol = this.getRootSymbol(); + var typeParameters = rootSymbol.getTypeParameters(); + var hasInstantiatedTypeParametersOfThisSignature = TypeScript.ArrayUtilities.all(typeParameters, function (typeParameter) { + return _this._typeParameterArgumentMap[typeParameter.pullSymbolID] !== undefined; + }); + + if (!hasInstantiatedTypeParametersOfThisSignature && typeParameters.length) { + this._typeParameters = []; + for (var i = 0; i < typeParameters.length; i++) { + this._typeParameters[this._typeParameters.length] = this._getResolver().instantiateTypeParameter(typeParameters[i], this._typeParameterArgumentMap); + } + } else { + this._typeParameters = TypeScript.sentinelEmptyArray; + } + } + + return this._typeParameters; + }; + + PullInstantiatedSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + var rootSymbol = this.getRootSymbol(); + return rootSymbol.getAllowedToReferenceTypeParameters(); + }; + return PullInstantiatedSignatureSymbol; + })(TypeScript.PullSignatureSymbol); + TypeScript.PullInstantiatedSignatureSymbol = PullInstantiatedSignatureSymbol; + + var PullInstantiatedTypeParameterSymbol = (function (_super) { + __extends(PullInstantiatedTypeParameterSymbol, _super); + function PullInstantiatedTypeParameterSymbol(rootTypeParameter, constraintType) { + _super.call(this, rootTypeParameter.name); + TypeScript.nSpecializedTypeParameterCreated++; + + this.setRootSymbol(rootTypeParameter); + this.setConstraint(constraintType); + + rootTypeParameter.addSpecialization(this, [constraintType]); + } + PullInstantiatedTypeParameterSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + return PullInstantiatedTypeParameterSymbol; + })(TypeScript.PullTypeParameterSymbol); + TypeScript.PullInstantiatedTypeParameterSymbol = PullInstantiatedTypeParameterSymbol; })(TypeScript || (TypeScript = {})); var TypeScript; (function (TypeScript) { @@ -55421,8 +57117,8 @@ var TypeScript; TypeScript.Debug.assert(start === 0); var bod = this.visitSyntaxList(node.moduleElements); - - var result = new TypeScript.SourceUnit(bod, this.fileName); + var comments = this.convertTokenLeadingComments(node.endOfFileToken, TypeScript.Syntax.childOffset(node, node.endOfFileToken)); + var result = new TypeScript.SourceUnit(bod, comments, this.fileName); this.setSpanExplicit(result, start, start + node.fullWidth()); return result; @@ -55999,17 +57695,17 @@ var TypeScript; this.movePast(node.openParenToken); - var arguments = this.visitSeparatedSyntaxList(node.arguments); + var _arguments = this.visitSeparatedSyntaxList(node.arguments); if (node.arguments.fullWidth() === 0 && node.closeParenToken.fullWidth() === 0) { var openParenTokenEnd = start + node.openParenToken.leadingTriviaWidth() + node.openParenToken.width(); - this.setSpanExplicit(arguments, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); + this.setSpanExplicit(_arguments, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); } var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); this.movePast(node.closeParenToken); - var result = new TypeScript.ArgumentList(typeArguments, arguments, closeParenToken); + var result = new TypeScript.ArgumentList(typeArguments, _arguments, closeParenToken); this.setSpan(result, start, node); return result; @@ -56230,14 +57926,14 @@ var TypeScript; SyntaxTreeToAstVisitor.prototype.visitConstructorDeclaration = function (node) { var start = this.position; - this.moveTo(node, node.parameterList); - var parameters = this.visitParameterList(node.parameterList); + this.moveTo(node, node.callSignature); + var callSignature = this.visitCallSignature(node.callSignature); var block = node.block ? node.block.accept(this) : null; this.movePast(node.semicolonToken); - var result = new TypeScript.ConstructorDeclaration(parameters, block); + var result = new TypeScript.ConstructorDeclaration(callSignature, block); this.setCommentsAndSpan(result, start, node); return result; @@ -57648,6 +59344,10 @@ var TypeScript; return commentArrayStructuralEquals(this.preComments(), ast.preComments(), includingPosition) && commentArrayStructuralEquals(this.postComments(), ast.postComments(), includingPosition); }; + + AST.prototype.isExpression = function () { + return false; + }; return AST; })(); TypeScript.AST = AST; @@ -57749,9 +59449,10 @@ var TypeScript; var SourceUnit = (function (_super) { __extends(SourceUnit, _super); - function SourceUnit(moduleElements, _fileName) { + function SourceUnit(moduleElements, endOfFileTokenLeadingComments, _fileName) { _super.call(this); this.moduleElements = moduleElements; + this.endOfFileTokenLeadingComments = endOfFileTokenLeadingComments; this._fileName = _fileName; moduleElements && (moduleElements.parent = this); } @@ -57800,6 +59501,10 @@ var TypeScript; Identifier.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; }; + + Identifier.prototype.isExpression = function () { + return true; + }; return Identifier; })(AST); TypeScript.Identifier = Identifier; @@ -57827,6 +59532,10 @@ var TypeScript; LiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition); }; + + LiteralExpression.prototype.isExpression = function () { + return true; + }; return LiteralExpression; })(AST); TypeScript.LiteralExpression = LiteralExpression; @@ -57853,6 +59562,10 @@ var TypeScript; ThisExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition); }; + + ThisExpression.prototype.isExpression = function () { + return true; + }; return ThisExpression; })(AST); TypeScript.ThisExpression = ThisExpression; @@ -57879,6 +59592,10 @@ var TypeScript; SuperExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition); }; + + SuperExpression.prototype.isExpression = function () { + return true; + }; return SuperExpression; })(AST); TypeScript.SuperExpression = SuperExpression; @@ -57908,6 +59625,10 @@ var TypeScript; NumericLiteral.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && (this._value === ast._value || (isNaN(this._value) && isNaN(ast._value))) && this._text === ast._text; }; + + NumericLiteral.prototype.isExpression = function () { + return true; + }; return NumericLiteral; })(AST); TypeScript.NumericLiteral = NumericLiteral; @@ -57930,6 +59651,10 @@ var TypeScript; RegularExpressionLiteral.prototype.kind = function () { return 12 /* RegularExpressionLiteral */; }; + + RegularExpressionLiteral.prototype.isExpression = function () { + return true; + }; return RegularExpressionLiteral; })(AST); TypeScript.RegularExpressionLiteral = RegularExpressionLiteral; @@ -57956,6 +59681,10 @@ var TypeScript; StringLiteral.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; }; + + StringLiteral.prototype.isExpression = function () { + return true; + }; return StringLiteral; })(AST); TypeScript.StringLiteral = StringLiteral; @@ -58279,6 +60008,10 @@ var TypeScript; PrefixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); }; + + PrefixUnaryExpression.prototype.isExpression = function () { + return true; + }; return PrefixUnaryExpression; })(AST); TypeScript.PrefixUnaryExpression = PrefixUnaryExpression; @@ -58297,6 +60030,10 @@ var TypeScript; ArrayLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expressions, ast.expressions, includingPosition); }; + + ArrayLiteralExpression.prototype.isExpression = function () { + return true; + }; return ArrayLiteralExpression; })(AST); TypeScript.ArrayLiteralExpression = ArrayLiteralExpression; @@ -58313,6 +60050,10 @@ var TypeScript; OmittedExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition); }; + + OmittedExpression.prototype.isExpression = function () { + return true; + }; return OmittedExpression; })(AST); TypeScript.OmittedExpression = OmittedExpression; @@ -58332,6 +60073,10 @@ var TypeScript; ParenthesizedExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + ParenthesizedExpression.prototype.isExpression = function () { + return true; + }; return ParenthesizedExpression; })(AST); TypeScript.ParenthesizedExpression = ParenthesizedExpression; @@ -58350,6 +60095,10 @@ var TypeScript; SimpleArrowFunctionExpression.prototype.kind = function () { return 219 /* SimpleArrowFunctionExpression */; }; + + SimpleArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; return SimpleArrowFunctionExpression; })(AST); TypeScript.SimpleArrowFunctionExpression = SimpleArrowFunctionExpression; @@ -58368,6 +60117,10 @@ var TypeScript; ParenthesizedArrowFunctionExpression.prototype.kind = function () { return 218 /* ParenthesizedArrowFunctionExpression */; }; + + ParenthesizedArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; return ParenthesizedArrowFunctionExpression; })(AST); TypeScript.ParenthesizedArrowFunctionExpression = ParenthesizedArrowFunctionExpression; @@ -58588,6 +60341,10 @@ var TypeScript; MemberAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); }; + + MemberAccessExpression.prototype.isExpression = function () { + return true; + }; return MemberAccessExpression; })(AST); TypeScript.MemberAccessExpression = MemberAccessExpression; @@ -58607,6 +60364,10 @@ var TypeScript; PostfixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); }; + + PostfixUnaryExpression.prototype.isExpression = function () { + return true; + }; return PostfixUnaryExpression; })(AST); TypeScript.PostfixUnaryExpression = PostfixUnaryExpression; @@ -58627,6 +60388,10 @@ var TypeScript; ElementAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentExpression, ast.argumentExpression, includingPosition); }; + + ElementAccessExpression.prototype.isExpression = function () { + return true; + }; return ElementAccessExpression; })(AST); TypeScript.ElementAccessExpression = ElementAccessExpression; @@ -58647,19 +60412,24 @@ var TypeScript; InvocationExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); }; + + InvocationExpression.prototype.isExpression = function () { + return true; + }; return InvocationExpression; })(AST); TypeScript.InvocationExpression = InvocationExpression; var ArgumentList = (function (_super) { __extends(ArgumentList, _super); - function ArgumentList(typeArgumentList, arguments, closeParenToken) { + function ArgumentList(typeArgumentList, _arguments, closeParenToken) { _super.call(this); this.typeArgumentList = typeArgumentList; - this.arguments = arguments; this.closeParenToken = closeParenToken; + this.arguments = _arguments; + typeArgumentList && (typeArgumentList.parent = this); - arguments && (arguments.parent = this); + _arguments && (_arguments.parent = this); } ArgumentList.prototype.kind = function () { return 226 /* ArgumentList */; @@ -58685,6 +60455,10 @@ var TypeScript; BinaryExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); }; + + BinaryExpression.prototype.isExpression = function () { + return true; + }; return BinaryExpression; })(AST); TypeScript.BinaryExpression = BinaryExpression; @@ -58707,6 +60481,10 @@ var TypeScript; ConditionalExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.whenTrue, ast.whenTrue, includingPosition) && structuralEquals(this.whenFalse, ast.whenFalse, includingPosition); }; + + ConditionalExpression.prototype.isExpression = function () { + return true; + }; return ConditionalExpression; })(AST); TypeScript.ConditionalExpression = ConditionalExpression; @@ -58887,11 +60665,11 @@ var TypeScript; var ConstructorDeclaration = (function (_super) { __extends(ConstructorDeclaration, _super); - function ConstructorDeclaration(parameterList, block) { + function ConstructorDeclaration(callSignature, block) { _super.call(this); - this.parameterList = parameterList; + this.callSignature = callSignature; this.block = block; - parameterList && (parameterList.parent = this); + callSignature && (callSignature.parent = this); block && (block.parent = this); } ConstructorDeclaration.prototype.kind = function () { @@ -59041,6 +60819,10 @@ var TypeScript; ObjectCreationExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); }; + + ObjectCreationExpression.prototype.isExpression = function () { + return true; + }; return ObjectCreationExpression; })(AST); TypeScript.ObjectCreationExpression = ObjectCreationExpression; @@ -59277,6 +61059,10 @@ var TypeScript; CastExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + CastExpression.prototype.isExpression = function () { + return true; + }; return CastExpression; })(AST); TypeScript.CastExpression = CastExpression; @@ -59295,6 +61081,10 @@ var TypeScript; ObjectLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.propertyAssignments, ast.propertyAssignments, includingPosition); }; + + ObjectLiteralExpression.prototype.isExpression = function () { + return true; + }; return ObjectLiteralExpression; })(AST); TypeScript.ObjectLiteralExpression = ObjectLiteralExpression; @@ -59347,6 +61137,10 @@ var TypeScript; FunctionExpression.prototype.kind = function () { return 222 /* FunctionExpression */; }; + + FunctionExpression.prototype.isExpression = function () { + return true; + }; return FunctionExpression; })(AST); TypeScript.FunctionExpression = FunctionExpression; @@ -59484,6 +61278,10 @@ var TypeScript; TypeOfExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + TypeOfExpression.prototype.isExpression = function () { + return true; + }; return TypeOfExpression; })(AST); TypeScript.TypeOfExpression = TypeOfExpression; @@ -59502,6 +61300,10 @@ var TypeScript; DeleteExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + DeleteExpression.prototype.isExpression = function () { + return true; + }; return DeleteExpression; })(AST); TypeScript.DeleteExpression = DeleteExpression; @@ -59520,6 +61322,10 @@ var TypeScript; VoidExpression.prototype.structuralEquals = function (ast, includingPosition) { return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); }; + + VoidExpression.prototype.isExpression = function () { + return true; + }; return VoidExpression; })(AST); TypeScript.VoidExpression = VoidExpression; @@ -59571,15 +61377,4 @@ var TypeScript; return Comment; })(); TypeScript.Comment = Comment; - - function diagnosticFromDecl(decl, diagnosticKey, arguments) { - if (typeof arguments === "undefined") { arguments = null; } - var span = decl.getSpan(); - return new TypeScript.Diagnostic(decl.fileName(), decl.semanticInfoChain().lineMap(decl.fileName()), span.start(), span.length(), diagnosticKey, arguments); - } - TypeScript.diagnosticFromDecl = diagnosticFromDecl; - - function min(a, b) { - return a <= b ? a : b; - } })(TypeScript || (TypeScript = {})); diff --git a/_infrastructure/tests/typings/bluebird/bluebird.d.ts b/_infrastructure/tests/typings/bluebird/bluebird.d.ts new file mode 100644 index 0000000000..45db9d86a3 --- /dev/null +++ b/_infrastructure/tests/typings/bluebird/bluebird.d.ts @@ -0,0 +1,656 @@ +// Type definitions for bluebird 1.0.0 +// Project: https://github.com/petkaantonov/bluebird +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts +// By: Campredon + +// Warning: recommended to use `tsc > v1.0.0` (critical bugs in generic code: +// - https://github.com/borisyankov/DefinitelyTyped/issues/1563 +// - https://github.com/borisyankov/DefinitelyTyped/tree/def/bluebird + +// Note: replicate changes to all overloads in both definition and test file +// Note: keep both static and instance members inline (so similar) + +// TODO fix remaining TODO annotations in both definition and test + +// TODO verify support to have no return statement in handlers to get a Promise (more overloads?) + +declare class Promise implements Promise.Thenable { + /** + * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. + */ + constructor(callback: (resolve: (thenable: Promise.Thenable) => void, reject: (error: any) => void) => void); + constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void); + + /** + * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + */ + then(onFulfill: (value: R) => Promise.Thenable, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + then(onFulfill: (value: R) => Promise.Thenable, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise; + then(onFulfill: (value: R) => U, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + then(onFulfill?: (value: R) => U, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise; + + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(onReject?: (error: any) => Promise.Thenable): Promise; + caught(onReject?: (error: any) => Promise.Thenable): Promise; + + catch(onReject?: (error: any) => U): Promise; + caught(onReject?: (error: any) => U): Promise; + + /** + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; + + catch(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; + + catch(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; + caught(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; + + catch(ErrorClass: Function, onReject: (error: any) => U): Promise; + caught(ErrorClass: Function, onReject: (error: any) => U): Promise; + + /** + * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. + */ + error(onReject: (reason: any) => Promise.Thenable): Promise; + error(onReject: (reason: any) => U): Promise; + + /** + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * + * Alias `.lastly();` for compatibility with earlier ECMAScript version. + */ + finally(handler: (value: R) => Promise.Thenable): Promise; + finally(handler: (value: R) => R): Promise; + finally(handler: (value: R) => void): Promise; + + lastly(handler: (value: R) => Promise.Thenable): Promise; + lastly(handler: (value: R) => R): Promise; + + /** + * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + */ + bind(thisArg: any): Promise; + + /** + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + */ + done(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + done(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; + done(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + done(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; + + /** + * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. + */ + progressed(handler: (note: any) => any): Promise; + + /** + * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + delay(ms: number): Promise; + + /** + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. + * + * You may specify a custom error message with the `message` parameter. + */ + timeout(ms: number, message?: string): Promise; + + /** + * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. + * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. + */ + nodeify(callback: (err: any, value?: R) => void): Promise; + nodeify(...sink: any[]): void; + + /** + * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. + */ + cancellable(): Promise; + + /** + * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. + * + * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. + * + * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. + * + * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. + */ + // TODO what to do with this? + cancel(): Promise; + + /** + * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. + */ + fork(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + fork(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; + fork(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + fork(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; + + /** + * Create an uncancellable promise based on this promise. + */ + uncancellable(): Promise; + + /** + * See if this promise can be cancelled. + */ + isCancellable(): boolean; + + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; + + /** + * See if this `promise` has been rejected. + */ + isRejected(): boolean; + + /** + * See if this `promise` is still defer. + */ + isPending(): boolean; + + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; + + /** + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. + */ + inspect(): Promise.Inspection; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName].call(obj, arg...); + * }); + * + */ + call(propertyName: string, ...args: any[]): Promise; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName]; + * }); + * + */ + // TODO find way to fix get() + // get(propertyName: string): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * return value; + * }); + * + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` + * + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. + */ + return(value: U): Promise; + thenReturn(value: U): Promise; + return(): Promise; + thenReturn(): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * throw reason; + * }); + * + * Same limitations apply as with `.return()`. + * + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. + */ + throw(reason: Error): Promise; + thenThrow(reason: Error): Promise; + + /** + * Convert to String. + */ + toString(): string; + + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): Object; + + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + // TODO how to model instance.spread()? like Q? + spread(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable): Promise; + spread(onFulfill: Function, onReject?: (reason: any) => U): Promise; + /* + // TODO or something like this? + spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => Promise.Thenable): Promise; + spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => U): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; + */ + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + all(): Promise; + + /** + * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO how to model instance.props()? + props(): Promise; + + /** + * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + settle(): Promise[]>; + + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + any(): Promise; + + /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + some(count: number): Promise; + + /** + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + race(): Promise; + + /** + * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + map(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable): Promise; + map(mapper: (item: Q, index: number, arrayLength: number) => U): Promise; + + /** + * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + /** + * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + filter(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable): Promise; + filter(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise; +} + +declare module Promise { + + export interface Thenable { + then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled: (value: R) => Thenable, onRejected?: (error: any) => U): Thenable; + then(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable; + } + + export interface Resolver { + /** + * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. + */ + resolve(value: R): void; + + /** + * Reject the underlying promise with `reason` as the rejection reason. + */ + reject(reason: any): void; + + /** + * Progress the underlying promise with `value` as the progression value. + */ + progress(value: any): void; + + /** + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. + * + * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. + */ + // TODO specify resolver callback + callback: Function; + } + + export interface Inspection { + /** + * See if the underlying promise was fulfilled at the creation time of this inspection object. + */ + isFulfilled(): boolean; + + /** + * See if the underlying promise was rejected at the creation time of this inspection object. + */ + isRejected(): boolean; + + /** + * See if the underlying promise was defer at the creation time of this inspection object. + */ + isPending(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. + * + * throws `TypeError` + */ + value(): R; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. + * + * throws `TypeError` + */ + error(): any; + } + + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + // TODO find way to enable try() without tsc borking + // see also: https://typescript.codeplex.com/workitem/2194 + /* + export function try(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; + export function try(fn: () => R, args?: any[], ctx?: any): Promise; + */ + + export function attempt(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; + export function attempt(fn: () => R, args?: any[], ctx?: any): Promise; + + /** + * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + export function method(fn: Function): Function; + + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + export function resolve(value: Promise.Thenable): Promise; + export function resolve(value: R): Promise; + + /** + * Create a promise that is rejected with the given `reason`. + */ + export function reject(reason: any): Promise; + + /** + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). + */ + export function defer(): Promise.Resolver; + + /** + * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + */ + export function cast(value: Promise.Thenable): Promise; + export function cast(value: R): Promise; + + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + export function bind(thisArg: any): Promise; + + /** + * See if `value` is a trusted Promise. + */ + export function is(value: any): boolean; + + /** + * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + */ + export function longStackTraces(): void; + + /** + * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. + */ + // TODO enable more overloads + export function delay(value: Promise.Thenable, ms: number): Promise; + export function delay(value: R, ms: number): Promise; + export function delay(ms: number): Promise; + + /** + * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + // TODO how to model promisify? + export function promisify(nodeFunction: Function, receiver?: any): Function; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + // TODO how to model promisifyAll? + export function promisifyAll(target: Object): Object; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix coroutine GeneratorFunction + export function coroutine(generatorFunction: Function): Function; + + /** + * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix spawn GeneratorFunction + export function spawn(generatorFunction: Function): Promise; + + /** + * This is relevant to browser environments with no module loader. + * + * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. + */ + export function noConflict(): typeof Promise; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + export function onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + // TODO enable more overloads + // promise of array with promises of value + export function all(values: Thenable[]>): Promise; + // promise of array with values + export function all(values: Thenable): Promise; + // array with promises of value + export function all(values: Thenable[]): Promise; + // array with values + export function all(values: R[]): Promise; + + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + // TODO verify this is correct + // trusted promise for object + export function props(object: Promise): Promise; + // object + export function props(object: Object): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. + * + * *original: The array is not modified. The input array sparsity is retained in the resulting array.* + */ + // promise of array with promises of value + export function settle(values: Thenable[]>): Promise[]>; + // promise of array with values + export function settle(values: Thenable): Promise[]>; + // array with promises of value + export function settle(values: Thenable[]): Promise[]>; + // array with values + export function settle(values: R[]): Promise[]>; + + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + // promise of array with promises of value + export function any(values: Thenable[]>): Promise; + // promise of array with values + export function any(values: Thenable): Promise; + // array with promises of value + export function any(values: Thenable[]): Promise; + // array with values + export function any(values: R[]): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + // promise of array with promises of value + export function race(values: Thenable[]>): Promise; + // promise of array with values + export function race(values: Thenable): Promise; + // array with promises of value + export function race(values: Thenable[]): Promise; + // array with values + export function race(values: R[]): Promise; + + /** + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + export function some(values: Thenable[]>, count: number): Promise; + // promise of array with values + export function some(values: Thenable, count: number): Promise; + // array with promises of value + export function some(values: Thenable[], count: number): Promise; + // array with values + export function some(values: R[], count: number): Promise; + + /** + * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. + */ + // variadic array with promises of value + export function join(...values: Thenable[]): Promise; + // variadic array with values + export function join(...values: R[]): Promise; + + /** + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + export function map(values: Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Thenable): Promise; + export function map(values: Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise; + + // promise of array with values + export function map(values: Thenable, mapper: (item: R, index: number, arrayLength: number) => Thenable): Promise; + export function map(values: Thenable, mapper: (item: R, index: number, arrayLength: number) => U): Promise; + + // array with promises of value + export function map(values: Thenable[], mapper: (item: R, index: number, arrayLength: number) => Thenable): Promise; + export function map(values: Thenable[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; + + // array with values + export function map(values: R[], mapper: (item: R, index: number, arrayLength: number) => Thenable): Promise; + export function map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; + + /** + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + // promise of array with promises of value + export function reduce(values: Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable, initialValue?: U): Promise; + export function reduce(values: Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + // promise of array with values + export function reduce(values: Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable, initialValue?: U): Promise; + export function reduce(values: Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + // array with promises of value + export function reduce(values: Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable, initialValue?: U): Promise; + export function reduce(values: Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + // array with values + export function reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable, initialValue?: U): Promise; + export function reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + /** + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + // promise of array with promises of value + export function filter(values: Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Thenable): Promise; + export function filter(values: Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + + // promise of array with values + export function filter(values: Thenable, filterer: (item: R, index: number, arrayLength: number) => Thenable): Promise; + export function filter(values: Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + + // array with promises of value + export function filter(values: Thenable[], filterer: (item: R, index: number, arrayLength: number) => Thenable): Promise; + export function filter(values: Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + + // array with values + export function filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => Thenable): Promise; + export function filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; +} + +declare module 'bluebird' { +export = Promise; +} diff --git a/_infrastructure/tests/typings/lazy.js/lazy.js.d.ts b/_infrastructure/tests/typings/lazy.js/lazy.js.d.ts new file mode 100644 index 0000000000..b2909dfceb --- /dev/null +++ b/_infrastructure/tests/typings/lazy.js/lazy.js.d.ts @@ -0,0 +1,252 @@ +// Type definitions for Lazy.js 0.3.2 +// Project: https://github.com/dtao/lazy.js/ +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module LazyJS { + + interface LazyStatic { + + (value: T[]):ArrayLikeSequence; + (value: any[]):ArrayLikeSequence; + (value: Object):ObjectLikeSequence; + (value: Object):ObjectLikeSequence; + (value: string):StringLikeSequence; + + strict():LazyStatic; + + generate(generatorFn: GeneratorCallback, length?: number):GeneratedSequence; + + range(to: number):GeneratedSequence; + range(from: number, to: number, step?: number):GeneratedSequence; + + repeat(value: T, count?: number):GeneratedSequence; + + on(eventType: string):Sequence; + + readFile(path: string):StringLikeSequence; + makeHttpRequest(path: string):StringLikeSequence; + } + + interface ArrayLike { + length:number; + [index:number]:T; + } + + interface Callback { + ():void; + } + + interface ErrorCallback { + (error: any):void; + } + + interface ValueCallback { + (value: T):void; + } + + interface GetKeyCallback { + (value: T):string; + } + + interface TestCallback { + (value: T):boolean; + } + + interface MapCallback { + (value: T):U; + } + + interface MapStringCallback { + (value: string):string; + } + + interface NumberCallback { + (value: T):number; + } + + interface MemoCallback { + (memo: U, value: T):U; + } + + interface GeneratorCallback { + (index: number):T; + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + interface Iterator { + new (sequence: Sequence):Iterator; + current():T; + moveNext():boolean; + } + + interface GeneratedSequence extends Sequence { + new(generatorFn: GeneratorCallback, length: number):GeneratedSequence; + length():number; + } + + interface AsyncSequence extends SequenceBase { + each(callback: ValueCallback):AsyncHandle; + } + + interface AsyncHandle { + cancel():void; + onComplete(callback: Callback):void; + onError(callback: ErrorCallback):void; + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + module Sequence { + function define(methodName: string[], overrides: Object): Function; + } + + interface Sequence extends SequenceBase { + each(eachFn: ValueCallback):Sequence; + } + + interface SequenceBase extends SequenceBaser { + first():any; + first(count: number):Sequence; + indexOf(value: any, startIndex?: number):Sequence; + + last():any; + last(count: number):Sequence; + lastIndexOf(value: any):Sequence; + + reverse():Sequence; + } + + interface SequenceBaser { + // TODO improve define() (needs ugly overload) + async(interval: number):AsyncSequence; + chunk(size: number):Sequence; + compact():Sequence; + concat(var_args: T[]):Sequence; + consecutive(length: number):Sequence; + contains(value: T):boolean; + countBy(keyFn: GetKeyCallback): ObjectLikeSequence; + countBy(propertyName: string): ObjectLikeSequence; + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): Sequence; + findWhere(properties: Object): Sequence; + + flatten(): Sequence; + groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; + initial(count?: number): Sequence; + intersection(var_args: T[]): Sequence; + invoke(methodName: string): Sequence; + isEmpty(): boolean; + join(delimiter?: string): string; + map(mapFn: MapCallback): Sequence; + + max(valueFn?: NumberCallback): T; + min(valueFn?: NumberCallback): T; + pluck(propertyName: string): Sequence; + reduce(aggregatorFn: MemoCallback, memo?: U): U; + reduceRight(aggregatorFn: MemoCallback, memo: U): U; + reject(predicateFn: TestCallback): Sequence; + rest(count?: number): Sequence; + shuffle(): Sequence; + some(predicateFn?: TestCallback): boolean; + sortBy(sortFn: NumberCallback): Sequence; + sortedIndex(value: T): Sequence; + sum(valueFn?: NumberCallback): Sequence; + takeWhile(predicateFn: TestCallback): Sequence; + union(var_args: T[]): Sequence; + uniq(): Sequence; + where(properties: Object): Sequence; + without(var_args: T[]): Sequence; + zip(var_args: T[]): Sequence; + + toArray(): T[]; + toObject(): Object; + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + module ArrayLikeSequence { + function define(methodName: string[], overrides: Object): Function; + } + + interface ArrayLikeSequence extends Sequence { + // define()X; + concat(): ArrayLikeSequence; + first(count?: number): ArrayLikeSequence; + get(index: number): T; + length(): number; + map(mapFn: MapCallback): ArrayLikeSequence; + pop(): ArrayLikeSequence; + rest(count?: number): ArrayLikeSequence; + reverse(): ArrayLikeSequence; + shift(): ArrayLikeSequence; + slice(begin: number, end?: number): ArrayLikeSequence; + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + module ObjectLikeSequence { + function define(methodName: string[], overrides: Object): Function; + } + + interface ObjectLikeSequence extends Sequence { + assign(other: Object): ObjectLikeSequence; + // throws error + //async(): X; + defaults(defaults: Object): ObjectLikeSequence; + functions(): Sequence; + get(property: string): ObjectLikeSequence; + invert(): ObjectLikeSequence; + keys(): Sequence; + omit(properties: string[]): ObjectLikeSequence; + pairs(): Sequence; + pick(properties: string[]): ObjectLikeSequence; + toArray(): T[]; + toObject(): Object; + values(): Sequence; + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + module StringLikeSequence { + function define(methodName: string[], overrides: Object): Function; + } + + interface StringLikeSequence extends SequenceBaser { + charAt(index: number): string; + charCodeAt(index: number): number; + contains(value: string): boolean; + endsWith(suffix: string): boolean; + + first(): string; + first(count: number): StringLikeSequence; + + indexOf(substring: string, startIndex?: number): number; + + last(): string; + last(count: number): StringLikeSequence; + + lastIndexOf(substring: string, startIndex?: number): number; + mapString(mapFn: MapStringCallback): StringLikeSequence; + match(pattern: RegExp): StringLikeSequence; + reverse(): StringLikeSequence; + + split(delimiter: string): StringLikeSequence; + split(delimiter: RegExp): StringLikeSequence; + + startsWith(prefix: string): boolean; + substring(start: number, stop?: number): StringLikeSequence; + toLowerCase(): StringLikeSequence; + toUpperCase(): StringLikeSequence; + } +} + +declare var Lazy: LazyJS.LazyStatic; + +declare module 'lazy.js' { +export = Lazy; +} + diff --git a/_infrastructure/tests/typings/node/node.d.ts b/_infrastructure/tests/typings/node/node.d.ts new file mode 100644 index 0000000000..dca0164b08 --- /dev/null +++ b/_infrastructure/tests/typings/node/node.d.ts @@ -0,0 +1,1258 @@ +// Type definitions for Node.js v0.10.1 +// Project: http://nodejs.org/ +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/************************************************ +* * +* Node.js v0.10.1 API * +* * +************************************************/ + +/************************************************ +* * +* GLOBAL * +* * +************************************************/ +declare var process: NodeProcess; +declare var global: any; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void , ms: number , ...args: any[]): NodeTimer; +declare function clearTimeout(timeoutId: NodeTimer): void; +declare function setInterval(callback: (...args: any[]) => void , ms: number , ...args: any[]): NodeTimer; +declare function clearInterval(intervalId: NodeTimer): void; +declare function setImmediate(callback: (...args: any[]) => void , ...args: any[]): any; +declare function clearImmediate(immediateId: any): void; + +declare var require: { + (id: string): any; + resolve(id:string): string; + cache: any; + extensions: any; + main: any; +} + +declare var module: { + exports: any; + require(id: string): any; + id: string; + filename: string; + loaded: boolean; + parent: any; + children: any[]; +} + +// Same as module.exports +declare var exports: any; +declare var SlowBuffer: { + new (str: string, encoding?: string): NodeBuffer; + new (size: number): NodeBuffer; + new (array: any[]): NodeBuffer; + prototype: NodeBuffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; +}; +declare var Buffer: { + new (str: string, encoding?: string): NodeBuffer; + new (size: number): NodeBuffer; + new (array: any[]): NodeBuffer; + prototype: NodeBuffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; +} + +/************************************************ +* * +* INTERFACES * +* * +************************************************/ + +interface ErrnoException extends Error { + errno?: any; + code?: string; + path?: string; + syscall?: string; +} + +interface NodeEventEmitter { + addListener(event: string, listener: Function): NodeEventEmitter; + on(event: string, listener: Function): NodeEventEmitter; + once(event: string, listener: Function): NodeEventEmitter; + removeListener(event: string, listener: Function): NodeEventEmitter; + removeAllListeners(event?: string): NodeEventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; +} + +interface ReadableStream extends NodeEventEmitter { + readable: boolean; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: NodeBuffer): void; + wrap(oldStream: ReadableStream): ReadableStream; +} + +interface WritableStream extends NodeEventEmitter { + writable: boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; +} + +interface ReadWriteStream extends ReadableStream, WritableStream { } + +interface NodeProcess extends NodeEventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: { http_parser: string; node: string; v8: string; ares: string; uv: string; zlib: string; openssl: string; }; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string): void; + pid: number; + title: string; + arch: string; + platform: string; + memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; + nextTick(callback: Function): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?:number[]): number[]; + + // Worker + send?(message: any, sendHandle?: any): void; +} + +// Buffer class +interface NodeBuffer { + [index: number]: number; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + length: number; + copy(targetBuffer: NodeBuffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): NodeBuffer; + readUInt8(offset: number, noAsset?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + writeUInt8(value: number, offset: number, noAssert?: boolean): void; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; + writeInt8(value: number, offset: number, noAssert?: boolean): void; + writeInt16LE(value: number, offset: number, noAssert?: boolean): void; + writeInt16BE(value: number, offset: number, noAssert?: boolean): void; + writeInt32LE(value: number, offset: number, noAssert?: boolean): void; + writeInt32BE(value: number, offset: number, noAssert?: boolean): void; + writeFloatLE(value: number, offset: number, noAssert?: boolean): void; + writeFloatBE(value: number, offset: number, noAssert?: boolean): void; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; + fill(value: any, offset?: number, end?: number): void; +} + +interface NodeTimer { + ref() : void; + unref() : void; +} + +/************************************************ +* * +* MODULES * +* * +************************************************/ +declare module "querystring" { + export function stringify(obj: any, sep?: string, eq?: string): string; + export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; + export function escape(): any; + export function unescape(): any; +} + +declare module "events" { + export class EventEmitter implements NodeEventEmitter { + static listenerCount(emitter: EventEmitter, event: string): number; + + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } +} + +declare module "http" { + import events = require("events"); + import net = require("net"); + import stream = require("stream"); + + export interface Server extends NodeEventEmitter { + listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; + listen(path: string, callback?: Function): void; + listen(handle: any, listeningListener?: Function): void; + close(cb?: any): void; + maxHeadersCount: number; + } + export interface ServerRequest extends NodeEventEmitter, ReadableStream { + method: string; + url: string; + headers: any; + trailers: string; + httpVersion: string; + setEncoding(encoding?: string): void; + pause(): void; + resume(): void; + connection: net.NodeSocket; + } + export interface ServerResponse extends NodeEventEmitter, WritableStream { + // Extended base methods + write(buffer: NodeBuffer): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + writeContinue(): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; + writeHead(statusCode: number, headers?: any): void; + statusCode: number; + setHeader(name: string, value: string): void; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface ClientRequest extends NodeEventEmitter, WritableStream { + // Extended base methods + write(buffer: NodeBuffer): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: Function): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + // Extended base methods + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface ClientResponse extends NodeEventEmitter, ReadableStream { + statusCode: number; + httpVersion: string; + headers: any; + trailers: any; + setEncoding(encoding?: string): void; + pause(): void; + resume(): void; + } + export interface Agent { maxSockets: number; sockets: any; requests: any; } + + export var STATUS_CODES: any; + export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: any, callback?: Function): ClientRequest; + export function get(options: any, callback?: Function): ClientRequest; + export var globalAgent: Agent; +} + +declare module "cluster" { + import child = require("child_process"); + import events = require("events"); + + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } + + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): void; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + } + + export var settings: ClusterSettings; + export var isMaster: boolean; + export var isWorker: boolean; + export function setupMaster(settings?: ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; + export var worker: Worker; + export var workers: Worker[]; + + // Event emitter + export function addListener(event: string, listener: Function): void; + export function on(event: string, listener: Function): any; + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListeners(event?: string): void; + export function setMaxListeners(n: number): void; + export function listeners(event: string): Function[]; + export function emit(event: string, ...args: any[]): boolean; +} + +declare module "zlib" { + import stream = require("stream"); + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } + + export interface Gzip extends ReadWriteStream { } + export interface Gunzip extends ReadWriteStream { } + export interface Deflate extends ReadWriteStream { } + export interface Inflate extends ReadWriteStream { } + export interface DeflateRaw extends ReadWriteStream { } + export interface InflateRaw extends ReadWriteStream { } + export interface Unzip extends ReadWriteStream { } + + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; + + export function deflate(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + export function gzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + export function gunzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + export function inflate(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + export function unzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; +} + +declare module "os" { + export function tmpDir(): string; + export function hostname(): string; + export function type(): string; + export function platform(): string; + export function arch(): string; + export function release(): string; + export function uptime(): number; + export function loadavg(): number[]; + export function totalmem(): number; + export function freemem(): number; + export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; + export function networkInterfaces(): any; + export var EOL: string; +} + +declare module "https" { + import tls = require("tls"); + import events = require("events"); + import http = require("http"); + + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string) => any; + } + + export interface RequestOptions { + host?: string; + hostname?: string; + port?: number; + path?: string; + method?: string; + headers?: any; + auth?: string; + agent?: any; + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + } + + export interface NodeAgent { + maxSockets: number; + sockets: any; + requests: any; + } + export var Agent: { + new (options?: RequestOptions): NodeAgent; + }; + export interface Server extends tls.Server { } + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; + export var globalAgent: NodeAgent; +} + +declare module "punycode" { + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): string; + encode(codePoints: number[]): string; + } + export var version: any; +} + +declare module "repl" { + import stream = require("stream"); + import events = require("events"); + + export interface ReplOptions { + prompt?: string; + input?: ReadableStream; + output?: WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + } + export function start(options: ReplOptions): NodeEventEmitter; +} + +declare module "readline" { + import events = require("events"); + import stream = require("stream"); + + export interface ReadLine extends NodeEventEmitter { + setPrompt(prompt: string, length: number): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: Function): void; + pause(): void; + resume(): void; + close(): void; + write(data: any, key?: any): void; + } + export interface ReadLineOptions { + input: ReadableStream; + output: WritableStream; + completer?: Function; + terminal?: boolean; + } + export function createInterface(options: ReadLineOptions): ReadLine; +} + +declare module "vm" { + export interface Context { } + export interface Script { + runInThisContext(): void; + runInNewContext(sandbox?: Context): void; + } + export function runInThisContext(code: string, filename?: string): void; + export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; + export function runInContext(code: string, context: Context, filename?: string): void; + export function createContext(initSandbox?: Context): Context; + export function createScript(code: string, filename?: string): Script; +} + +declare module "child_process" { + import events = require("events"); + import stream = require("stream"); + + export interface ChildProcess extends NodeEventEmitter { + stdin: WritableStream; + stdout: ReadableStream; + stderr: ReadableStream; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle: any): void; + disconnect(): void; + } + + export function spawn(command: string, args?: string[], options?: { + cwd?: string; + stdio?: any; + custom?: any; + env?: any; + detached?: boolean; + }): ChildProcess; + export function exec(command: string, options: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; + export function exec(command: string, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; + export function execFile(file: string, args: string[], options: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: string; + killSignal?: string; + }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; + export function fork(modulePath: string, args?: string[], options?: { + cwd?: string; + env?: any; + encoding?: string; + }): ChildProcess; +} + +declare module "url" { + export interface Url { + href: string; + protocol: string; + auth: string; + hostname: string; + port: string; + host: string; + pathname: string; + search: string; + query: string; + slashes: boolean; + } + + export interface UrlOptions { + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: any; + } + + export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; + export function format(url: UrlOptions): string; + export function resolve(from: string, to: string): string; +} + +declare module "dns" { + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; +} + +declare module "net" { + import stream = require("stream"); + + export interface NodeSocket extends ReadWriteStream { + // Extended base methods + write(buffer: NodeBuffer): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): void; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + pause(): void; + resume(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + remoteAddress: string; + remotePort: number; + bytesRead: number; + bytesWritten: number; + + // Extended base methods + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + + export var Socket: { + new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): NodeSocket; + }; + + export interface Server extends NodeSocket { + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; + listen(path: string, listeningListener?: Function): void; + listen(handle: any, listeningListener?: Function): void; + close(callback?: Function): void; + address(): { port: number; family: string; address: string; }; + maxConnections: number; + connections: number; + } + export function createServer(connectionListener?: (socket: NodeSocket) =>void ): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: NodeSocket) =>void ): Server; + export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): NodeSocket; + export function connect(port: number, host?: string, connectionListener?: Function): NodeSocket; + export function connect(path: string, connectionListener?: Function): NodeSocket; + export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): NodeSocket; + export function createConnection(port: number, host?: string, connectionListener?: Function): NodeSocket; + export function createConnection(path: string, connectionListener?: Function): NodeSocket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; +} + +declare module "dgram" { + import events = require("events"); + + export function createSocket(type: string, callback?: Function): Socket; + + interface Socket extends NodeEventEmitter { + send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; + bind(port: number, address?: string): void; + close(): void; + address: { address: string; family: string; port: number; }; + setBroadcast(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + } +} + +declare module "fs" { + import stream = require("stream"); + + interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; + } + + interface FSWatcher extends NodeEventEmitter { + close(): void; + } + + export interface ReadStream extends ReadableStream { } + export interface WriteStream extends WritableStream { } + + export function rename(oldPath: string, newPath: string, callback?: (err?: ErrnoException) => void): void; + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string, callback?: (err?: ErrnoException) => void): void; + export function truncate(path: string, len: number, callback?: (err?: ErrnoException) => void): void; + export function truncateSync(path: string, len?: number): void; + export function ftruncate(fd: number, callback?: (err?: ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: ErrnoException) => void): void; + export function ftruncateSync(fd: number, len?: number): void; + export function chown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; + export function chownSync(path: string, uid: number, gid: number): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; + export function fchownSync(fd: number, uid: number, gid: number): void; + export function lchown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; + export function lchownSync(path: string, uid: number, gid: number): void; + export function chmod(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; + export function chmod(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; + export function chmodSync(path: string, mode: number): void; + export function chmodSync(path: string, mode: string): void; + export function fchmod(fd: number, mode: number, callback?: (err?: ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: ErrnoException) => void): void; + export function fchmodSync(fd: number, mode: number): void; + export function fchmodSync(fd: number, mode: string): void; + export function lchmod(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; + export function lchmod(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; + export function lchmodSync(path: string, mode: number): void; + export function lchmodSync(path: string, mode: string): void; + export function stat(path: string, callback?: (err: ErrnoException, stats: Stats) => any): void; + export function lstat(path: string, callback?: (err: ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: ErrnoException, stats: Stats) => any): void; + export function statSync(path: string): Stats; + export function lstatSync(path: string): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string, dstpath: string, callback?: (err?: ErrnoException) => void): void; + export function linkSync(srcpath: string, dstpath: string): void; + export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: ErrnoException) => void): void; + export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; + export function readlink(path: string, callback?: (err: ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string): string; + export function realpath(path: string, callback?: (err: ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string, cache: {[path: string]: string}, callback: (err: ErrnoException, resolvedPath: string) =>any): void; + export function realpathSync(path: string, cache?: {[path: string]: string}): void; + export function unlink(path: string, callback?: (err?: ErrnoException) => void): void; + export function unlinkSync(path: string): void; + export function rmdir(path: string, callback?: (err?: ErrnoException) => void): void; + export function rmdirSync(path: string): void; + export function mkdir(path: string, callback?: (err?: ErrnoException) => void): void; + export function mkdir(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; + export function mkdir(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; + export function mkdirSync(path: string, mode?: number): void; + export function mkdirSync(path: string, mode?: string): void; + export function readdir(path: string, callback?: (err: ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string): string[]; + export function close(fd: number, callback?: (err?: ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string, flags: string, callback?: (err: ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: number, callback?: (err: ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: string, callback?: (err: ErrnoException, fd: number) => any): void; + export function openSync(path: string, flags: string, mode?: number): number; + export function openSync(path: string, flags: string, mode?: string): number; + export function utimes(path: string, atime: number, mtime: number, callback?: (err?: ErrnoException) => void): void; + export function utimesSync(path: string, atime: number, mtime: number): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: ErrnoException) => void): void; + export function futimesSync(fd: number, atime: number, mtime: number): void; + export function fsync(fd: number, callback?: (err?: ErrnoException) => void): void; + export function fsyncSync(fd: number): void; + export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, written: number, buffer: NodeBuffer) => void): void; + export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; + export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, bytesRead: number, buffer: NodeBuffer) => void): void; + export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; + export function readFile(filename: string, options: { encoding?: string; flag?: string; }, callback: (err: ErrnoException, data: any) => void): void; + export function readFile(filename: string, callback: (err: ErrnoException, data: NodeBuffer) => void ): void; + export function readFileSync(filename: string, options?: { flag?: string; }): NodeBuffer; + export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + export function writeFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; + export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; + export function exists(path: string, callback?: (exists: boolean) => void): void; + export function existsSync(path: string): boolean; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: string; + mode?: number; + bufferSize?: number; + }): ReadStream; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: string; + mode?: string; + bufferSize?: number; + }): ReadStream; + export function createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + string?: string; + }): WriteStream; +} + +declare module "path" { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; +} + +declare module "string_decoder" { + export interface NodeStringDecoder { + write(buffer: NodeBuffer): string; + detectIncompleteChar(buffer: NodeBuffer): number; + } + export var StringDecoder: { + new (encoding: string): NodeStringDecoder; + }; +} + +declare module "tls" { + import crypto = require("crypto"); + import net = require("net"); + import stream = require("stream"); + + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; + + export interface TlsOptions { + pfx?: any; //string or buffer + key?: any; //string or buffer + passphrase?: string; + cert?: any; + ca?: any; //string or buffer + crl?: any; //string or string array + ciphers?: string; + honorCipherOrder?: any; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; //array or Buffer; + SNICallback?: (servername: string) => any; + } + + export interface ConnectionOptions { + host?: string; + port?: number; + socket?: net.NodeSocket; + pfx?: any; //string | Buffer + key?: any; //string | Buffer + passphrase?: string; + cert?: any; //string | Buffer + ca?: any; //Array of string | Buffer + rejectUnauthorized?: boolean; + NPNProtocols?: any; //Array of string | Buffer + servername?: string; + } + + export interface Server extends net.Server { + // Extended base methods + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; + listen(path: string, listeningListener?: Function): void; + listen(handle: any, listeningListener?: Function): void; + + listen(port: number, host?: string, callback?: Function): void; + close(): void; + address(): { port: number; family: string; address: string; }; + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + maxConnections: number; + connections: number; + } + + export interface ClearTextStream extends ReadWriteStream { + authorized: boolean; + authorizationError: Error; + getPeerCertificate(): any; + getCipher: { + name: string; + version: string; + }; + address: { + port: number; + family: string; + address: string; + }; + remoteAddress: string; + remotePort: number; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; + export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; +} + +declare module "crypto" { + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: any; //string | string array + crl: any; //string | string array + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string): Hash; + export function createHmac(algorithm: string, key: string): Hmac; + interface Hash { + update(data: any, input_encoding?: string): Hash; + digest(encoding?: string): string; + } + interface Hmac { + update(data: any): void; + digest(encoding?: string): void; + } + export function createCipher(algorithm: string, password: any): Cipher; + export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; + interface Cipher { + update(data: any, input_encoding?: string, output_encoding?: string): string; + final(output_encoding?: string): string; + setAutoPadding(auto_padding: boolean): void; + createDecipher(algorithm: string, password: any): Decipher; + createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + } + interface Decipher { + update(data: any, input_encoding?: string, output_encoding?: string): void; + final(output_encoding?: string): string; + setAutoPadding(auto_padding: boolean): void; + } + export function createSign(algorithm: string): Signer; + interface Signer { + update(data: any): void; + sign(private_key: string, output_format: string): string; + } + export function createVerify(algorith: string): Verify; + interface Verify { + update(data: any): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + export function createDiffieHellman(prime_length: number): DiffieHellman; + export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; + interface DiffieHellman { + generateKeys(encoding?: string): string; + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + getPrime(encoding?: string): string; + getGenerator(encoding: string): string; + getPublicKey(encoding?: string): string; + getPrivateKey(encoding?: string): string; + setPublicKey(public_key: string, encoding?: string): void; + setPrivateKey(public_key: string, encoding?: string): void; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; + export function randomBytes(size: number): NodeBuffer; + export function randomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; + export function pseudoRandomBytes(size: number): NodeBuffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; +} + +declare module "stream" { + import events = require("events"); + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + } + + export class Readable extends events.EventEmitter implements ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: NodeBuffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + push(chunk: any, encoding?: string): boolean; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + } + + export class Writable extends events.EventEmitter implements WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(data: NodeBuffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements ReadWriteStream { + writable: boolean; + constructor(opts?: DuplexOptions); + _write(data: NodeBuffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions {} + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: NodeBuffer, encoding: string, callback: Function): void; + _transform(chunk: string, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: NodeBuffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform {} +} + +declare module "util" { + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; + } + + export function format(format: any, ...param: any[]): string; + export function debug(string: string): void; + export function error(...param: any[]): void; + export function puts(...param: any[]): void; + export function print(...param: any[]): void; + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export function isArray(object: any): boolean; + export function isRegExp(object: any): boolean; + export function isDate(object: any): boolean; + export function isError(object: any): boolean; + export function inherits(constructor: any, superConstructor: any): void; +} + +declare module "assert" { + function internal (value: any, message?: string): void; + module internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + + constructor(options?: {message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function}); + } + + export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + } + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + } + + export function ifError(value: any): void; + } + + export = internal; +} + +declare module "tty" { + import net = require("net"); + + export function isatty(fd: number): boolean; + export interface ReadStream extends net.NodeSocket { + isRaw: boolean; + setRawMode(mode: boolean): void; + } + export interface WriteStream extends net.NodeSocket { + columns: number; + rows: number; + } +} + +declare module "domain" { + import events = require("events"); + + export class Domain extends events.EventEmitter { + run(fn: Function): void; + add(emitter: NodeEventEmitter): void; + remove(emitter: NodeEventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + + addListener(event: string, listener: Function): Domain; + on(event: string, listener: Function): Domain; + once(event: string, listener: Function): Domain; + removeListener(event: string, listener: Function): Domain; + removeAllListeners(event?: string): Domain; + } + + export function create(): Domain; +} diff --git a/_infrastructure/tests/typings/optimist/optimist.d.ts b/_infrastructure/tests/typings/optimist/optimist.d.ts new file mode 100644 index 0000000000..d79dcfaf0e --- /dev/null +++ b/_infrastructure/tests/typings/optimist/optimist.d.ts @@ -0,0 +1,48 @@ +// https://github.com/substack/node-optimist +// sourced from https://github.com/soywiz/typescript-node-definitions/blob/master/optimist.d.ts +// rehacked by @Bartvds + +declare module Optimist { + export interface Argv { + _: string[]; + } + export interface Optimist { + default(name: string, value: any): Optimist; + default(args: any): Optimist; + + boolean(name: string): Optimist; + boolean(names: string[]): Optimist; + + string(name: string): Optimist; + string(names: string[]): Optimist; + + wrap(columns): Optimist; + + help(): Optimist; + showHelp(fn?: Function): Optimist; + + usage(message: string): Optimist; + + demand(key: string): Optimist; + demand(key: number): Optimist; + demand(key: string[]): Optimist; + + alias(key: string, alias: string): Optimist; + + describe(key: string, desc: string): Optimist; + + options(key: string, opt: any): Optimist; + + check(fn: Function); + + parse(args: string[]): Optimist; + + argv: Argv; + } +} +interface Optimist extends Optimist.Optimist { + (args: string[]): Optimist.Optimist; +} +declare module 'optimist' { + export = Optimist; +} diff --git a/_infrastructure/tests/typings/tsd.d.ts b/_infrastructure/tests/typings/tsd.d.ts new file mode 100644 index 0000000000..371833438e --- /dev/null +++ b/_infrastructure/tests/typings/tsd.d.ts @@ -0,0 +1,4 @@ +/// +/// +/// +/// diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts index 6004030eaf..9b29ef98f7 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -1,4 +1,9 @@ -/// AmCharts object (it's not a class) is create automatically when amcharts.js or amstock.js file is included in a web page. +// Type definitions for amCharts +// Project: http://www.amcharts.com/ +// Definitions by: aleksey-bykov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// AmCharts object (it's not a class) is create automatically when amcharts.js or amstock.js file is included in a web page. declare module AmCharts { /** Set it to true if you have base href set for your page. This will fix rendering problems in Firefox caused by base href. */ @@ -2340,4 +2345,4 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val /** Removes event listener from chart object. */ removeListener(chart: AmChart, type: string, handler: any); } -} \ No newline at end of file +} diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts new file mode 100644 index 0000000000..2c8e72f07d --- /dev/null +++ b/angular-protractor/angular-protractor-tests.ts @@ -0,0 +1,242 @@ +/// + +function TestWebDriverExports() { + var abstractBuilder: protractor.AbstractBuilder = new protractor.AbstractBuilder(); + var baseAbstractBuilder: webdriver.AbstractBuilder = abstractBuilder; + + var button: protractor.Button = new protractor.Button(); + var baseButton: webdriver.Button = button; + + var key: string = protractor.Key.ADD; + var chord: string = protractor.Key.chord(protractor.Key.NUMPAD0, protractor.Key.NUMPAD1); + + var driver: protractor.WebDriver = new protractor.Builder(). + withCapabilities(protractor.Capabilities.chrome()). + build(); + var baseDriver: webdriver.WebDriver = driver; + + var action: protractor.ActionSequence = new protractor.ActionSequence(driver); + var baseAction: webdriver.ActionSequence = action; + + var alert: protractor.Alert = new protractor.Alert(driver, 'Message'); + var baseAlert: webdriver.Alert = alert; + + var unhandledAlertError: protractor.UnhandledAlertError = new protractor.UnhandledAlertError('Message', alert); + var baseUnhandledAlertError: webdriver.UnhandledAlertError = unhandledAlertError; + + var browser: string = protractor.Browser.ANDROID; + + var builder: protractor.Builder = new protractor.Builder(); + var baseBuilder: webdriver.Builder = builder; + + var capability: string = protractor.Capability.BROWSER_NAME; + + var capabilities: protractor.Capabilities = protractor.Capabilities.chrome(); + var baseCapabilities: webdriver.Capabilities = capabilities; + + var commandName: string = protractor.CommandName.CLICK_ELEMENT; + + var command: protractor.Command = new protractor.Command(protractor.CommandName.CLICK); + var baseCommand: webdriver.Command = command; + + var eventEmitter: protractor.EventEmitter = new protractor.EventEmitter(); + var baseEventEmitter: webdriver.EventEmitter = eventEmitter; + + var firefoxDomExecutor: protractor.FirefoxDomExecutor = new protractor.FirefoxDomExecutor(); + var baseFirefoxDomExecutor: webdriver.FirefoxDomExecutor = firefoxDomExecutor; + + var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); + var baseWebElement: webdriver.WebElement = webElement; + + var locator: protractor.Locator = new protractor.Locator('id', 'ABC'); + var baseLocator: webdriver.Locator = locator; + + var session: protractor.Session = new protractor.Session('ABC', webdriver.Capabilities.android()); + var baseSession: webdriver.Session = session; + + locator = protractor.By.name('name'); + + // logging module + + var levelName: string = protractor.logging.LevelName.ALL; + var loggingType: string = protractor.logging.Type.CLIENT; + + var level: webdriver.logging.Level = protractor.logging.Level.ALL; + + var entry: protractor.logging.Entry = new protractor.logging.Entry(protractor.logging.Level.ALL, 'Message'); + var baseEntry: webdriver.logging.Entry = entry; + + level = protractor.logging.getLevel('DEBUG'); + + protractor.logging.Preferences = { a: 123 }; + + // promise module + + var promise: protractor.promise.Promise = new protractor.promise.Promise(); + var basePromise: webdriver.promise.Promise = promise; + + var deferred: protractor.promise.Deferred = new protractor.promise.Deferred(); + var baseDeferred: webdriver.promise.Deferred = deferred; + + var flow: protractor.promise.ControlFlow = new protractor.promise.ControlFlow(); + var baseFlow: webdriver.promise.ControlFlow = flow; + + protractor.promise.asap(promise, function(value: any){ return true; }); + protractor.promise.asap(promise, function(value: any){}, function(err: any) { return 'ABC'; }); + + promise = protractor.promise.checkedNodeCall(function(err: any, value: any) { return 123; }); + + flow = protractor.promise.controlFlow(); + + promise = protractor.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { }); + + deferred = protractor.promise.defer(function() {}); + deferred = protractor.promise.defer(function(reason?: any) {}); + + promise = protractor.promise.delayed(123); + + promise = protractor.promise.fulfilled(); + promise = protractor.promise.fulfilled({a: 123}); + + promise = protractor.promise.fullyResolved({a: 123}); + + var isPromise: boolean = protractor.promise.isPromise('ABC'); + + promise = protractor.promise.rejected({a: 123}); + + protractor.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + promise = protractor.promise.when(promise, function(value: any) { return 123; }, function(err: Error) { return 123; }); + + // error module + + var errorCode: number = protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE; + var error: protractor.error.Error = new protractor.error.Error(protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE); + var baseError: webdriver.error.Error = error; + + // process module + + var isNative: boolean = protractor.process.isNative(); + var value: string; + + value = protractor.process.getEnv('name'); + value = protractor.process.getEnv('name', 'default'); + + protractor.process.setEnv('name', 'value'); + protractor.process.setEnv('name', 123); + +} + +function TestProtractor() { + var ptor: protractor.Protractor; + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + ptor = new protractor.Protractor(driver); + ptor = new protractor.Protractor(driver, 'baseUrl'); + ptor = new protractor.Protractor(driver, 'baseUrl', 'rootElement'); + ptor = protractor.getInstance(); + protractor.setInstance(ptor); + + ptor = protractor.wrapDriver(driver); + ptor = protractor.wrapDriver(driver, 'baseUrl'); + ptor = protractor.wrapDriver(driver, 'baseUrl', 'rootElement'); + + ptor = browser; + + driver = ptor.driver; + var baseUrl: string = ptor.baseUrl; + var rootEl: string = ptor.rootEl; + var ignoreSynchronization: boolean = ptor.ignoreSynchronization; + var params: any = ptor.params; + + ptor.debugger(); + + ptor.clearMockModules(); + ptor.addMockModule('name', 'script'); + ptor.addMockModule('name', function() {}); + ptor.waitForAngular(); + + var elementFinder: protractor.ElementFinder; + + elementFinder = ptor.element(by.id('ABC')); + elementFinder = ptor.$('.class'); + + var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); + + var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); + + var locationAbsUrl: string = ptor.getLocationAbsUrl(); +} + +function TestElement() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.className('class')); +} + +function TestElementFinder() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var promise: webdriver.promise.Promise; + + promise = elementFinder.click(); + promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); + promise = elementFinder.getTagName(); + promise = elementFinder.getCssValue('display'); + promise = elementFinder.getAttribute('atribute'); + promise = elementFinder.getText(); + promise = elementFinder.getSize(); + promise = elementFinder.getLocation(); + promise = elementFinder.isEnabled(); + promise = elementFinder.isSelected(); + promise = elementFinder.submit(); + promise = elementFinder.clear(); + promise = elementFinder.isDisplayed(); + promise = elementFinder.getOuterHtml(); + promise = elementFinder.getInnerHtml(); + promise = elementFinder.isElementPresent(by.id('id')); + promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.findElements(by.className('class')); + promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.$$('.class'); + promise = elementFinder.evaluate('expression'); + promise = elementFinder.isPresent(); + + var webElement: webdriver.WebElement; + + webElement = elementFinder.$('.class'); + webElement = elementFinder.findElement(by.id('id')); + webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); + webElement = elementFinder.find(); +} + +// This function tests the angular specific locator strategies. +function TestLocatorStrategies() { + var ptor: protractor.Protractor = protractor.getInstance(); + var webElement: webdriver.WebElement; + + // Protractor Specific Locators + webElement = ptor.findElement(protractor.By.binding('binding')); + webElement = ptor.findElement(protractor.By.select('select')); + webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); + webElement = ptor.findElement(protractor.By.input('input')); + webElement = ptor.findElement(protractor.By.model('model')); + webElement = ptor.findElement(protractor.By.textarea('textarea')); + webElement = ptor.findElement(protractor.By.repeater('repeater')); +} + +// This function tests the methods that were added to the base WebElement class +function TestWebElements() { + var ptor: protractor.Protractor = protractor.getInstance(); + + var webElement: protractor.WebElement; + var promise: webdriver.promise.Promise; + + webElement = ptor.findElement(by.id('id')).$('.class'); + promise = ptor.findElement(by.id('id')).$$('.class'); + promise = ptor.findElement(by.id('id')).evaluate('something'); + + webElement = webElement.findElement(by.id('id')).$('.class'); + promise = webElement.findElement(by.id('id')).$$('.class'); + promise = webElement.findElement(by.id('id')).evaluate('something'); +} \ No newline at end of file diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts new file mode 100644 index 0000000000..951ba85de9 --- /dev/null +++ b/angular-protractor/angular-protractor.d.ts @@ -0,0 +1,868 @@ +// Type definitions for Angular Protractor 0.17.0 +// Project: https://github.com/angular/protractor +// Definitions by: Bill Armstrong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module protractor { + //region Wrapped webdriver Items + + class AbstractBuilder extends webdriver.AbstractBuilder {} + class ActionSequence extends webdriver.ActionSequence {} + class Alert extends webdriver.Alert {} + class Builder extends webdriver.Builder {} + class Button extends webdriver.Button {} + class Capabilities extends webdriver.Capabilities {} + class Command extends webdriver.Command {} + class EventEmitter extends webdriver.EventEmitter {} + class FirefoxDomExecutor extends webdriver.FirefoxDomExecutor {} + class Locator extends webdriver.Locator {} + class Session extends webdriver.Session {} + class WebDriver extends webdriver.WebDriver {} + class Browser extends webdriver.Browser {} + class Capability extends webdriver.Capability {} + class CommandName extends webdriver.CommandName {} + class Key extends webdriver.Key {} + class UnhandledAlertError extends webdriver.UnhandledAlertError {} + + class WebElement extends webdriver.WebElement { + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + } + + module command { + class Command extends webdriver.Command {} + class CommandName extends webdriver.CommandName {} + } + + module error { + class Error extends webdriver.error.Error {} + class ErrorCode extends webdriver.error.ErrorCode {} + } + + module events { + class EventEmitter extends webdriver.EventEmitter {} + } + + module logging { + var Preferences: any; + + class LevelName extends webdriver.logging.LevelName {} + class Type extends webdriver.logging.Type {} + class Level extends webdriver.logging.Level {} + class Entry extends webdriver.logging.Entry {} + + function getLevel(nameOrValue: string): webdriver.logging.Level; + function getLevel(nameOrValue: number): webdriver.logging.Level; + } + + module promise { + class Promise extends webdriver.promise.Promise {} + class Deferred extends webdriver.promise.Deferred {} + class ControlFlow extends webdriver.promise.ControlFlow {} + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): webdriver.promise.ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: webdriver.promise.ControlFlow) => any): webdriver.promise.Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): webdriver.promise.Promise; + + /** + * Creates a new deferred object. + * @param {Function=} opt_canceller Function to call when cancelling the + * computation of this instance's value. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(opt_canceller?: any): webdriver.promise.Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: any): webdriver.promise.Promise; + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): webdriver.promise.Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: (error: any, value: any) => any): webdriver.promise.Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: any, opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@code webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: (value: any) => any, opt_errback?: (error: any) => any): void; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): webdriver.promise.Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; + + } + + module process { + + /** + * Queries for a named environment variable. + * @param {string} name The name of the environment variable to look up. + * @param {string=} opt_default The default value if the named variable is not + * defined. + * @return {string} The queried environment variable. + */ + function getEnv(name: string, opt_default?: string): string; + + /** + * @return {boolean} Whether the current process is Node's native process + * object. + */ + function isNative(): boolean; + + /** + * Sets an environment value. If the new value is either null or undefined, the + * environment variable will be cleared. + * @param {string} name The value to set. + * @param {*} value The new value; will be coerced to a string. + */ + function setEnv(name: string, value: any): void; + + } + + //endregion + + interface Element { + (locator: webdriver.Locator): ElementFinder; + all(locator: webdriver.Locator): ElementArrayFinder; + } + + interface ElementFinder { + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + *

Note that JS locator searches cannot be restricted to a subtree of the + * DOM. All such searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether an element could be located on the page. + */ + isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that match + * the given search criteria. + *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the elements. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with an + * array of located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + find(): protractor.WebElement; + + isPresent(): webdriver.promise.Promise; + } + + interface ElementArrayFinder{ + count(): webdriver.promise.Promise; + get(index: number): protractor.WebElement; + first(): protractor.WebElement; + last(): protractor.WebElement; + then(fn: (value: any) => any): webdriver.promise.Promise; + } + + interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { + /** + * Add a locator to this instance of ProtractorBy. This locator can then be + * used with element(by.()). + * + * @param {string} name + * @param {function|string} script A script to be run in the context of + * the browser. This script will be passed an array of arguments + * that begins with the element scoping the search, and then + * contains any args passed into the locator. It should return + * an array of elements. + */ + addLocator(name: string, script: any): void; + + /** + * Usage: + * {{status}} + * var status = element(by.binding('{{status}}')); + */ + binding(bindingDescriptor: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.select("user")); + */ + select(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.selectedOption("user")); + */ + selectedOption(model: string): webdriver.Locator; + + /** + * @DEPRECATED - use 'model' instead. + * Usage: + * + * element(by.input('user')); + */ + input(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.model('user')); + */ + model(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.textarea("user")); + */ + textarea(model: string): webdriver.Locator; + + /** + * Usage: + *

+ * {{cat.name}} + * {{cat.age}} + *
+ * + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater("cat in pets").row(2)); + * // Returns the SPAN for the first cat's name. + * var firstCatName = element( + * by.repeater("cat in pets").row(1).column("{{cat.name}}")); + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element( + * by.repeater("cat in pets").column("{{cat.age}}")); + * // Returns a promise that resolves to an array of WebElements containing + * // all rows of the repeater. + * var rows = element(by.repeater("cat in pets")); + */ + repeater(repeatDescriptor: string): webdriver.Locator; + } + + var By: IProtractorLocatorStrategy; + + class Protractor extends webdriver.WebDriver { + + //region Constructors + + /** + * @param {webdriver.WebDriver} webdriver + * @param {string=} opt_baseUrl A base URL to run get requests against. + * @param {string=body} opt_rootElement Selector element that has an ng-app in + * scope. + * @constructor + */ + constructor(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string); + + //endregion + + //region Properties + + /** + * The wrapped webdriver instance. Use this to interact with pages that do + * not contain Angular (such as a log-in screen). + * + * @type {webdriver.WebDriver} + */ + driver: webdriver.WebDriver; + + /** + * All get methods will be resolved against this base URL. Relative URLs are = + * resolved the way anchor tags resolve. + * + * @type {string} + */ + baseUrl: string; + + /** + * The css selector for an element on which to find Angular. This is usually + * 'body' but if your ng-app is on a subsection of the page it may be + * a subelement. + * + * @type {string} + */ + rootEl: string; + + /** + * If true, Protractor will not attempt to synchronize with the page before + * performing actions. This can be harmful because Protractor will not wait + * until $timeouts and $http calls have been processed, which can cause + * tests to become flaky. This should be used only when necessary, such as + * when a page continuously polls an API using $timeout. + * + * @type {boolean} + */ + ignoreSynchronization: boolean; + + /** + * An object that holds custom test parameters. + * + * @type {Object} + */ + params: any; + + //endregion + + //region Methods + + /** + * Helper function for finding elements. + * + * @type {function(webdriver.Locator): ElementFinder} + */ + element(locator: webdriver.Locator): ElementFinder; + + /** + * Helper function for finding elements by css. + * + * @type {function(string): ElementFinder} + */ + $(cssLocator: string): ElementFinder; + + /** + * Helper function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(cssLocator: string): ElementArrayFinder; + + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Wrap a webdriver.WebElement with protractor specific functionality. + * + * @param {webdriver.WebElement} element + * @return {protractor.WebElement} the wrapped web element. + */ + wrapWebElement(element: webdriver.WebElement): protractor.WebElement; + + /** + * Add a module to load before Angular whenever Protractor.get is called. + * Modules will be registered after existing modules already on the page, + * so any module registered here will override preexisting modules with the same + * name. + * + * @param {!string} name The name of the module to load or override. + * @param {!string|Function} script The JavaScript to load the module. + */ + addMockModule(name: string, script: string): void; + addMockModule(name: string, script: any): void; + + /** + * Clear the list of registered mock modules. + */ + clearMockModules(): void; + + /** + * Returns the current absolute url from AngularJS. + */ + getLocationAbsUrl(): string; + + /** + * Pauses the test and injects some helper functions into the browser, so that + * debugging may be done in the browser console. + * + * This should be used under node in debug mode, i.e. with + * protractor debug + * + * While in the debugger, commands can be scheduled through webdriver by + * entering the repl: + * debug> repl + * Press Ctrl + C to leave rdebug repl + * > ptor.findElement(protractor.By.input('user').sendKeys('Laura')); + * > ptor.debugger(); + * debug> c + * + * This will run the sendKeys command as the next task, then re-enter the + * debugger. + */ + debugger(): void; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two statements + * are equivalent: + *

+         * var e1 = driver.findElement(By.id('foo'));
+         * var e2 = driver.findElement({id:'foo'});
+         * 
+ * + *

When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; + + //endregion + } + + /** + * Create a new instance of Protractor by wrapping a webdriver instance. + * + * @param {webdriver.WebDriver} webdriver The configured webdriver instance. + * @param {string=} opt_baseUrl A URL to prepend to relative gets. + * @return {Protractor} + */ + function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; + + /** + * Set a singleton instance of protractor. + * @param {Protractor} ptor + */ + function setInstance(ptor: Protractor): void; + + /** + * Get the singleton instance. + * @return {Protractor} + */ + function getInstance(): Protractor; + +} + +declare var browser: protractor.Protractor; +declare var by: protractor.IProtractorLocatorStrategy; +declare var element: protractor.Element; + +declare module 'protractor' { + export = protractor; +} \ No newline at end of file diff --git a/angular-translate/angular-translate-tests.ts b/angular-translate/angular-translate-tests.ts new file mode 100644 index 0000000000..bea7faa09d --- /dev/null +++ b/angular-translate/angular-translate-tests.ts @@ -0,0 +1,29 @@ +/// + +var app = angular.module('at', ['pascalprecht.translate']); + +app.config(($translateProvider: ng.translate.ITranslateProvider) => { + $translateProvider.translations('en', { + TITLE: 'Hello', + FOO: 'This is a paragraph.', + BUTTON_LANG_EN: 'english', + BUTTON_LANG_DE: 'german' + }); + $translateProvider.translations('de', { + TITLE: 'Hallo', + FOO: 'Dies ist ein Paragraph.', + BUTTON_LANG_EN: 'englisch', + BUTTON_LANG_DE: 'deutsch' + }); + $translateProvider.preferredLanguage('en'); +}); + +interface Scope extends ng.IScope { + changeLanguage(key: any): void; +} + +app.controller('Ctrl', ($scope: Scope, $translate: ng.translate.ITranslateService) => { + $scope['changeLanguage'] = function (key: any) { + $translate.uses(key); + }; +}); diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts new file mode 100644 index 0000000000..106d0ae252 --- /dev/null +++ b/angular-translate/angular-translate.d.ts @@ -0,0 +1,64 @@ +// Type definitions for Angular Translate (pascalprecht.translate module) +// Project: https://github.com/PascalPrecht/angular-translate +// Definitions by: Michel Salib +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module ng.translate { + interface ITranslationTable { + [key: string]: string; + } + + interface IStorage { + get(name: string): string; + set(name: string, value: string): void; + } + + interface ISTaticFilesLoaderOptions { + prefix: string; + suffix: string; + key?: string; + } + + interface ITranslateService { + (key: string, ...params: string[]): string; + fallbackLanguage(): string; + preferredLanguage(): string; + proposedLanguage(): string; + refresh(lankKey: string): ng.IPromise; + storage(): IStorage; + storageKey(): string; + uses(): string; + uses(key: string): ng.IPromise; + } + + interface ITranslateProvider extends ng.IServiceProvider { + translations(key: string, translationTable: ITranslationTable): ITranslateProvider; + addInterpolation(factory: any): ITranslateProvider; + useMessageFormatInterpolation(): ITranslateProvider; + useInterpolation(factory: string): ITranslateProvider; + preferredLanguage(): string; + preferredLanguage(language: string): ITranslateProvider; + translationNotFoundIndicator(indicator: string): ITranslateProvider; + translationNotFoundIndicatorLeft(): string; + translationNotFoundIndicatorLeft(indicator: string): ITranslateProvider; + translationNotFoundIndicatorRight(): string; + translationNotFoundIndicatorRight(indicator: string): ITranslateProvider; + fallbackLanguage(): string; + fallbackLanguage(language: string): ITranslateProvider; + fallbackLanguage(languages: string[]): ITranslateProvider; + uses(): string; + uses(key: string): ITranslateProvider; + useUrlLoader(url: string): ITranslateProvider; + useStaticFilesLoader(options: ISTaticFilesLoaderOptions): ITranslateProvider; + useLoader(loaderFactory: string, options: any): ITranslateProvider; + useLocalStorage(): ITranslateProvider; + useCookieStorage(): ITranslateProvider; + useStorage(storageFactory: any): ITranslateProvider; + storagePrefix(): string; + storagePrefix(prefix: string): ITranslateProvider; + useMissingTranslationHandlerLog(): ITranslateProvider; + useMissingTranslationHandler(factory: string): ITranslateProvider; + } +} diff --git a/angular-ui/angular-ui-router-tests.ts b/angular-ui/angular-ui-router-tests.ts index 38f8b5ca00..5a9c4ad6c3 100644 --- a/angular-ui/angular-ui-router-tests.ts +++ b/angular-ui/angular-ui-router-tests.ts @@ -9,11 +9,23 @@ interface MyAppScope extends ng.IScope { myApp.config(( $stateProvider: ng.ui.IStateProvider, - $urlRouterProvider: ng.ui.IUrlRouterProvider) => { - // - // For any unmatched url, redirect to /state1 - $urlRouterProvider.otherwise("/state1"); - // + $urlRouterProvider: ng.ui.IUrlRouterProvider, + $urlMatcherFactory: ng.ui.IUrlMatcherFactory) => { + + var matcher: ng.ui.IUrlMatcher = $urlMatcherFactory.compile("/foo/:bar?param1"); + + $urlRouterProvider + .when('/test', '/list') + .when('/test', '/list') + .when('/test', '/list') + .when(/\/test\d/, '/list') + .when(/\/test\d/, ($injector: ng.auto.IInjectorService, $location: ng.ILocationService) => '/list') + .when(/\/test\d/,['$injector', '$location', ($injector: ng.auto.IInjectorService, $location: ng.ILocationService) => '/list']) + .when(matcher, '/list') + .when(matcher, ($injector: ng.auto.IInjectorService, $location: ng.ILocationService) => '/list') + .when(matcher, ['$injector', '$location', ($injector: ng.auto.IInjectorService, $location: ng.ILocationService) => '/list']) + .otherwise("/state1"); + // Now set up the states $stateProvider .state('state1', { @@ -58,4 +70,4 @@ myApp.config(( "viewB": { template: "route2.viewB" } } }); -}); \ No newline at end of file +}); diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index bc3e27c2dd..da3d92e5ec 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -42,12 +42,20 @@ declare module ng.ui { } interface IUrlRouterProvider extends IServiceProvider { - when(whenPath: string, toPath: string): IUrlRouterProvider; + when(whenPath: RegExp, handler: Function): IUrlRouterProvider; + when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; when(whenPath: RegExp, toPath: string): IUrlRouterProvider; + when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider; + when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider; when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider; + when(whenPath: string, handler: Function): IUrlRouterProvider; + when(whenPath: string, handler: any[]): IUrlRouterProvider; + when(whenPath: string, toPath: string): IUrlRouterProvider; + otherwise(handler: Function): IUrlRouterProvider; + otherwise(handler: any[]): IUrlRouterProvider; otherwise(path: string): IUrlRouterProvider; - otherwise(path: Function): IUrlRouterProvider; rule(handler: Function): IUrlRouterProvider; + rule(handler: any[]): IUrlRouterProvider; } interface IStateOptions { diff --git a/angularfire/angularfire-tests.ts b/angularfire/angularfire-tests.ts new file mode 100644 index 0000000000..eced9d7fe7 --- /dev/null +++ b/angularfire/angularfire-tests.ts @@ -0,0 +1,83 @@ +/// + +var myapp = angular.module("myapp", ["firebase"]); + +interface AngularFireScope extends ng.IScope { + items: AngularFire; + remoteItems: RemoteItems; +} + +interface RemoteItems { + bar: string; +} + +var url = "https://myapp.firebaseio.com"; + +myapp.controller("MyController", ["$scope", "$firebase", + function($scope: AngularFireScope, $firebase: AngularFireService) { + $scope.items = $firebase(new Firebase(url)); + $scope.items.$add({ foo: "bar" }); + $scope.items.$remove("foo"); + $scope.items.$remove(); + $scope.items.$save(); + var child = $scope.items.$child("foo"); + child.$remove(); + $scope.items.$set({ bar: "baz" }); + var keys = $scope.items.$getIndex(); + keys.forEach(function(key, i) { + console.log(i, ($scope.items)[key]); + }); + $scope.items.$on("loaded", function() { + console.log("Initial data received!"); + }); + $scope.items.$on("change", function() { + console.log("A remote change was applied locally!"); + }); + $scope.items.$off('loaded'); + function stopSync() { + $scope.items.$off(); + } + $scope.items.$bind($scope, "remoteItems"); + $scope.remoteItems.bar = "foo"; + $scope.items.$bind($scope, "remote").then(function(unbind) { + unbind(); + $scope.remoteItems.bar = "foo"; + }); + } +]); + +var foo: AngularFireObject = { + $priority: 0 +}; + +interface AngularFireAuthScope extends ng.IScope { + loginObj: AngularFireAuth; +} + +myapp.controller("MyAuthController", ["$scope", "$firebaseSimpleLogin", + function($scope: AngularFireAuthScope, $firebaseSimpleLogin: AngularFireAuthService) { + var dataRef = new Firebase(url); + $scope.loginObj = $firebaseSimpleLogin(dataRef); + $scope.loginObj.$getCurrentUser().then(_ => { + }); + var email = 'my@email.com'; + var password = 'mypassword'; + $scope.loginObj.$login('password', { + email: email, + password: password + }).then(function(user) { + console.log('Logged in as: ', user.uid); + }, function(error) { + console.error('Login failed: ', error); + }); + $scope.loginObj.$logout(); + $scope.loginObj.$createUser(email, password).then(_ => { + }); + $scope.loginObj.$changePassword(email, password, password).then(_ => { + }); + $scope.loginObj.$removeUser(email, password).then(_ => { + }); + $scope.loginObj.$sendPasswordResetEmail(email).then(_ => { + }); + } +]); \ No newline at end of file diff --git a/angularfire/angularfire.d.ts b/angularfire/angularfire.d.ts new file mode 100644 index 0000000000..3f2b0aa106 --- /dev/null +++ b/angularfire/angularfire.d.ts @@ -0,0 +1,41 @@ +// Type definitions for AngularFire 0.6.0 +// Project: http://angularfire.com +// Definitions by: Dénes Harmath +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +interface AngularFireService { + (firebase: Firebase): AngularFire; +} + +interface AngularFire { + $add(value: any): void; + $remove(key?: string): void; + $save(key?: string): void; + $child(key: string): AngularFire; + $set(value: any): void; + $getIndex(): string[]; + $on(eventType: string, callback: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void; + $off(eventType?: string, callback?: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void; + $bind($scope: ng.IScope, modelName: string): ng.IPromise; +} + +interface AngularFireObject { + $priority: number; +} + +interface AngularFireAuthService { + (firebase: Firebase): AngularFireAuth; +} + +interface AngularFireAuth { + $getCurrentUser(): ng.IPromise; + $login(provider: string, options?: Object): ng.IPromise; + $logout(): void; + $createUser(email: string, password: string, noLogin?: boolean): ng.IPromise; + $changePassword(email: string, oldPassword: string, newPassword: string): ng.IPromise; + $removeUser(email: string, password: string): ng.IPromise; + $sendPasswordResetEmail(email: string): ng.IPromise; +} diff --git a/angularjs/README.md b/angularjs/README.md index 263e046ea1..510f304f55 100644 --- a/angularjs/README.md +++ b/angularjs/README.md @@ -95,7 +95,7 @@ interface ICustomScope extends ng.IScope { title: string; } -function Controller($scope: ng.ICustomScope) { +function Controller($scope: ICustomScope) { $scope.$broadcast('myEvent'); $scope.title = 'Yabadabadu'; } diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts new file mode 100644 index 0000000000..696e6f8349 --- /dev/null +++ b/angularjs/angular-animate.d.ts @@ -0,0 +1,21 @@ +// Type definitions for Angular JS 1.2+ (ngAnimate module) +// Project: http://angularjs.org +// Definitions by: Michel Salib +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +/////////////////////////////////////////////////////////////////////////////// +// ngAnimate module (angular-animate.js) +/////////////////////////////////////////////////////////////////////////////// +declare module ng.animate { + + /////////////////////////////////////////////////////////////////////////// + // AnimateService + // see http://docs.angularjs.org/api/ngAnimate.$animate + /////////////////////////////////////////////////////////////////////////// + interface IAnimateService extends ng.IAnimateService { + enabled(value?: boolean, element?: JQuery): boolean; + } +} diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index f3a8870cdc..0317e17b7a 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -1,5 +1,6 @@ // Type definitions for Angular JS 1.2 (ngResource module) // Project: http://angularjs.org +// Definitions by: Diego Vilar // Definitions: https://github.com/daptiv/DefinitelyTyped /// @@ -18,19 +19,18 @@ declare module ng.resource { // that deeply. /////////////////////////////////////////////////////////////////////////// interface IResourceService { - - , U extends IResourceClass>(url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actionDescriptors?: any): U; - >(url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actionDescriptors?: any): IResourceClass; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ actionDescriptors?: any): IResourceClass>; + (url: string, paramDefaults?: any, + /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } + where deleteDescriptor : IActionDescriptor */ + actionDescriptors?: any): U; + (url: string, paramDefaults?: any, + /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } + where deleteDescriptor : IActionDescriptor */ + actionDescriptors?: any): IResourceClass; } // Just a reference to facilitate describing new actions @@ -50,7 +50,7 @@ declare module ng.resource { // PATCH (in other words, methods with body). Otherwise, it's going // to be considered as parameters to the request. // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465 - interface IResourceClass> { + interface IResourceClass { get(): T; get(dataOrParams: any): T; get(dataOrParams: any, success: Function): T; @@ -78,7 +78,7 @@ declare module ng.resource { delete(params: any, data: any, success?: Function, error?: Function): T; } - interface IResource> { + interface IResource { $get(): T; $get(dataOrParams: any): T; $get(dataOrParams: any, success: Function): T; @@ -104,10 +104,14 @@ declare module ng.resource { $delete(dataOrParams: any, success: Function): T; $delete(success: Function, error?: Function): T; $delete(params: any, data: any, success?: Function, error?: Function): T; + + /** the promise of the original server interaction that created this instance. **/ + $promise : ng.IPromise; + $resolved : boolean; } /** when creating a resource factory via IModule.factory */ - interface IResourceServiceFactoryFunction> { + interface IResourceServiceFactoryFunction { ($resource: ng.resource.IResourceService): IResourceClass; >($resource: ng.resource.IResourceService): U; } @@ -121,3 +125,10 @@ declare module ng { factory(name: string, resourceServiceFactoryFunction: ng.resource.IResourceServiceFactoryFunction): IModule; } } + +interface Array +{ + /** the promise of the original server interaction that created this collection. **/ + $promise : ng.IPromise>; + $resolved : boolean; +} diff --git a/angularjs/angular-scenario.d.ts b/angularjs/angular-scenario.d.ts index abd5709db6..ec3efd9f93 100644 --- a/angularjs/angular-scenario.d.ts +++ b/angularjs/angular-scenario.d.ts @@ -1,8 +1,10 @@ // Type definitions for Angular Scenario Testing -// Project: [http://angularjs.org] -// Definitions by: [RomanoLindano] +// Project: http://angularjs.org +// Definitions by: RomanoLindano // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module ng { export interface IAngularStatic { scenario: any; @@ -100,7 +102,11 @@ declare module angularScenario { export interface Element { count(): Future; click(): any; - query(callback: (selectedDOMElements: any[], callbackWhenDone: (objNull: any, futureValue: any) => any) => any): any; + dblclick(): any; + mouseover(): any; + mousedown(): any; + mouseup(): any; + query(callback: (selectedDOMElements: JQuery, callbackWhenDone: (objNull: any, futureValue: any) => any) => any): any; val(): Future; text(): Future; html(): Future; diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 18f5ccb4ee..4ce3116985 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -1,7 +1,7 @@ /// // issue: https://github.com/borisyankov/DefinitelyTyped/issues/369 -https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js +// https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js /** * @license HTTP Auth Interceptor Module for AngularJS * (c) 2012 Witold Szczerba diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 6a656b00bb..b369a271f8 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -79,7 +79,7 @@ declare module ng { /////////////////////////////////////////////////////////////////////////// interface IModule { animation(name: string, animationFactory: Function): IModule; - animation(name: string, inlineAnnotadedFunction: any[]): IModule; + animation(name: string, inlineAnnotatedFunction: any[]): IModule; animation(object: Object): IModule; /** configure existing services. Use this method to register work which needs to be performed on module loading @@ -88,29 +88,29 @@ declare module ng { /** configure existing services. Use this method to register work which needs to be performed on module loading */ - config(inlineAnnotadedFunction: any[]): IModule; + config(inlineAnnotatedFunction: any[]): IModule; constant(name: string, value: any): IModule; constant(object: Object): IModule; controller(name: string, controllerConstructor: Function): IModule; - controller(name: string, inlineAnnotadedConstructor: any[]): IModule; + controller(name: string, inlineAnnotatedConstructor: any[]): IModule; controller(object : Object): IModule; directive(name: string, directiveFactory: Function): IModule; - directive(name: string, inlineAnnotadedFunction: any[]): IModule; + directive(name: string, inlineAnnotatedFunction: any[]): IModule; directive(object: Object): IModule; factory(name: string, serviceFactoryFunction: Function): IModule; - factory(name: string, inlineAnnotadedFunction: any[]): IModule; + factory(name: string, inlineAnnotatedFunction: any[]): IModule; factory(object: Object): IModule; filter(name: string, filterFactoryFunction: Function): IModule; - filter(name: string, inlineAnnotadedFunction: any[]): IModule; + filter(name: string, inlineAnnotatedFunction: any[]): IModule; filter(object: Object): IModule; provider(name: string, serviceProviderConstructor: Function): IModule; - provider(name: string, inlineAnnotadedConstructor: any[]): IModule; + provider(name: string, inlineAnnotatedConstructor: any[]): IModule; provider(name: string, providerObject: auto.IProvider): IModule; provider(object: Object): IModule; run(initializationFunction: Function): IModule; - run(inlineAnnotadedFunction: any[]): IModule; + run(inlineAnnotatedFunction: any[]): IModule; service(name: string, serviceConstructor: Function): IModule; - service(name: string, inlineAnnotadedConstructor: any[]): IModule; + service(name: string, inlineAnnotatedConstructor: any[]): IModule; service(object: Object): IModule; value(name: string, value: any): IModule; value(object: Object): IModule; @@ -452,6 +452,7 @@ declare module ng { /////////////////////////////////////////////////////////////////////////// interface IQService { all(promises: IPromise[]): IPromise; + all(promises: {[id: string]: IPromise;}): IPromise<{[id: string]: any}>; defer(): IDeferred; reject(reason?: any): IPromise; when(value: T): IPromise; @@ -569,7 +570,7 @@ declare module ng { interface IControllerProvider extends IServiceProvider { register(name: string, controllerConstructor: Function): void; - register(name: string, dependencyAnnotadedConstructor: any[]): void; + register(name: string, dependencyAnnotatedConstructor: any[]): void; } /////////////////////////////////////////////////////////////////////////// @@ -798,10 +799,19 @@ declare module ng { inheritedData(key: string, value: any): JQuery; inheritedData(obj: { [key: string]: any; }): JQuery; inheritedData(key?: string): any; - - } + /////////////////////////////////////////////////////////////////////// + // AnimateService + // see http://docs.angularjs.org/api/ng.$animate + /////////////////////////////////////////////////////////////////////// + interface IAnimateService { + addClass(element: JQuery, className: string, done?: Function): void; + enter(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + leave(element: JQuery, done?: Function): void; + move(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + removeClass(element: JQuery, className: string, done?: Function): void; + } /////////////////////////////////////////////////////////////////////////// // AUTO module (angular.js) @@ -817,10 +827,11 @@ declare module ng { /////////////////////////////////////////////////////////////////////// interface IInjectorService { annotate(fn: Function): string[]; - annotate(inlineAnnotadedFunction: any[]): string[]; - get (name: string): any; + annotate(inlineAnnotatedFunction: any[]): string[]; + get(name: string): any; + has(name: string): boolean; instantiate(typeConstructor: Function, locals?: any): any; - invoke(inlineAnnotadedFunction: any[]): any; + invoke(inlineAnnotatedFunction: any[]): any; invoke(func: Function, context?: any, locals?: any): any; } @@ -837,7 +848,7 @@ declare module ng { decorator(name: string, decorator: Function): void; decorator(name: string, decoratorInline: any[]): void; factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; - factory(name: string, inlineAnnotadedFunction: any[]): ng.IServiceProvider; + factory(name: string, inlineAnnotatedFunction: any[]): ng.IServiceProvider; provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider; service(name: string, constructor: Function): ng.IServiceProvider; diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts index 0c022f7344..3b2b8fc167 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient.d.ts @@ -1,5 +1,5 @@ -// Type definitions for Microsoft.Windows.Azure.MobileService.Web-1.0.0 -// Project: https://.azure-mobile.net/client/MobileServices.Web-1.0.0.min.js +// Type definitions for Microsoft Windows AzureMobile Service 1.0.0 +// Project: http://www.windowsazure.com/en-us/develop/mobile/ // Definitions by: Morosinotto Daniele // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -91,4 +91,8 @@ declare module Microsoft.WindowsAzure { } } +declare module "WindowsAzure" { + export = WindowsAzure; +} + declare var WindowsAzure: Microsoft.WindowsAzure.WindowsAzureStatic; diff --git a/backbone-relational/backbone-relational.d.ts b/backbone-relational/backbone-relational.d.ts index fca37939e0..56dd2e9e83 100644 --- a/backbone-relational/backbone-relational.d.ts +++ b/backbone-relational/backbone-relational.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Backbone 0.8.5 +// Type definitions for Backbone-relational 0.8.5 // Project: http://backbonerelational.org/ // Definitions by: Eirik Hoem // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -165,4 +165,4 @@ declare module Backbone { } -} \ No newline at end of file +} diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index aad4cffde2..256554774a 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -175,6 +175,7 @@ declare module Backbone { sort(options?: Silenceable): Collection; unshift(model: Model, options?: AddOptions): Model; where(properies: any): Model[]; + findWhere(properties: any): Model; _prepareModel(attrs?: any, options?: any): any; _removeReference(model: Model): void; @@ -338,3 +339,7 @@ declare module Backbone { var $: JQueryStatic; } + +declare module "backbone" { + export = Backbone; +} diff --git a/bgiframe/typescript.bgiframe.d.ts b/bgiframe/typescript.bgiframe.d.ts index 1cb3897472..dfe4a7cc75 100644 --- a/bgiframe/typescript.bgiframe.d.ts +++ b/bgiframe/typescript.bgiframe.d.ts @@ -1,4 +1,4 @@ -// Type definitions for typescript.bgiframe 1.0 +// Type definitions for bgiframe 1.0 // Project: https://github.com/sumegizoltan/BgiFrame // Definitions by: Zoltan Sumegi // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -30,4 +30,4 @@ declare module BgiFrame { getIframe(element: HTMLElement): HTMLElement; prop(n: any): string; } -} \ No newline at end of file +} diff --git a/bigscreen/bigscreen-tests.ts b/bigscreen/bigscreen-tests.ts new file mode 100644 index 0000000000..9e0c9fda8c --- /dev/null +++ b/bigscreen/bigscreen-tests.ts @@ -0,0 +1,25 @@ +/// + +import BigScreen = require("bigscreen"); + +BigScreen.onchange = function(element: Element) { + console.log("Full-screen element " + element + " changed."); +} + +BigScreen.onenter = function(element: Element) { + console.log(BigScreen.element + " entered full-screen."); +}; + +BigScreen.onexit = function() { + console.log("Exited full-screen."); +} + +BigScreen.onerror = function(element: Element, reason: string) { + console.log("Error sending " + element + " into full-screen: " + reason); +} + +console.log("full-screen-enabled? " + BigScreen.enabled); + +BigScreen.request(document.documentElement); +BigScreen.exit(); +BigScreen.toggle(document.documentElement); diff --git a/bigscreen/bigscreen.d.ts b/bigscreen/bigscreen.d.ts new file mode 100644 index 0000000000..8bec685ff8 --- /dev/null +++ b/bigscreen/bigscreen.d.ts @@ -0,0 +1,26 @@ +// Type definitions for BigScreen 2.0.4 +// Project: http://brad.is/coding/BigScreen/ +// Definitions by: Douglas Eichelberger +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface BigScreenStatic { + // Properties + element: Element; + enabled: boolean; + + // Methods + exit(): void; + onchange(element: Element): void; + onenter(element: Element): void; + onerror(element: Element, reason: string): void; + onexit(): void; + request(element: Element, onEnter?: (element: Element) => void, onExit?: () => void, onError?: (element: Element, reason: string) => void): void; + toggle(element: Element, onEnter?: (element: Element) => void, onExit?: () => void, onError?: (element: Element, reason: string) => void): void; + videoEnabled(video: HTMLVideoElement): boolean; +} + +declare var bigscreen: BigScreenStatic; + +declare module "bigscreen" { + export = bigscreen; +} diff --git a/bluebird/bluebird-test.ts b/bluebird/bluebird-tests.ts similarity index 83% rename from bluebird/bluebird-test.ts rename to bluebird/bluebird-tests.ts index 92e5e7b6b2..14528b9b57 100644 --- a/bluebird/bluebird-test.ts +++ b/bluebird/bluebird-tests.ts @@ -1,5 +1,7 @@ /// +// Note: try to maintain the ordering and separators + var obj:Object; var bool:boolean; var num:number; @@ -15,32 +17,25 @@ var numArr:string[]; var value:any = null; var reason:any = null; -var Promise:Bluebird.PromiseStatic; +var promise:Promise; +var p:Promise; -var promise:Bluebird.Promise; -var p:Bluebird.Promise; - -var resolver:Bluebird.PromiseResolver; -var inspection:Bluebird.PromiseInspection; -var arrLike:Bluebird.ArrayLike; +var resolver:Promise.Resolver; +var inspection:Promise.Inspection; // - - - - - - - - - - - - - - - - - - - - - - - - var promise = new Promise((resolve:(value:any) => void, reject:(reason:any) => void) => { - if(true) { - resolve(123); - } - else { - reject(new Error('nope')); - } + if(true) { + resolve(123); + } + else { + reject(new Error('nope')); + } }); // - - - - - - - - - - - - - - - - - - - - - - - - -num = arrLike.length; - -// - - - - - - - - - - - - - - - - - - - - - - - - - resolver.resolve(x); resolver.reject(x); @@ -89,12 +84,12 @@ p = promise.caught((reason:any) => { }); p = promise.catch((reason:any) => { - return true; + return true; }, (reason:any) => { }); p = promise.caught((reason:any) => { - return true; + return true; }, (reason:any) => { }); @@ -219,43 +214,40 @@ p = promise.spread((value:any) => { }); p = promise.map((item:any, index:number, arrayLength:number) => { - return x; + return x; }); p = promise.reduce((total:number, memo:any, index:number, arrayLength:number) => { - return memo; + return memo; }); p = promise.reduce((total:number, memo:any, index:number, arrayLength:number) => { - return memo; + return memo; }, x); p = promise.filter((item:any, index?:number, arrayLength?:number) => { - return true; + return true; }); // - - - - - - - - - - - - - - - - - - - - - - - - p = new Promise((resolve:(value:any) => any, reject:(reason:any) => any) => { - if(true) { - resolve(value); - } - else { - reject(new Error('xyz')); - } + if(true) { + resolve(value); + } + else { + reject(new Error('xyz')); + } }); -p = Promise.try(() => {}); -p = Promise.try(() => {}, arr); -p = Promise.try(() => {}, arr, x); -p = Promise.try(() => {}, arrLike); -p = Promise.try(() => {}, arrLike, x); - +/* + p = Promise.try(() => {}); + p = Promise.try(() => {}, arr); + p = Promise.try(() => {}, arr, x); + */ p = Promise.attempt(() => {}); p = Promise.attempt(() => {}, arr); p = Promise.attempt(() => {}, arr, x); -p = Promise.attempt(() => {}, arrLike); -p = Promise.attempt(() => {}, arrLike, x); f = Promise.method(function() { @@ -312,16 +304,16 @@ p = Promise.some(arr, x); p = Promise.join(1, 2, 3); p = Promise.map(arr, (item:any, index:number, arrayLength:number) => { - return x; + return x; }); p = Promise.reduce(arr, (total:number, memo:any, index:number, arrayLength:number) => { - return memo; + return memo; }); p = Promise.reduce(arr, (total:number, memo:any, index:number, arrayLength:number) => { - return memo; + return memo; }, x); p = Promise.filter(arr, (item:any, index?:number, arrayLength?:number) => { - return true; + return true; }); diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index c05f8b02b8..5db21d63ed 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -3,496 +3,499 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module Bluebird { - - interface ArrayLike { - length:number; - } - - interface Promise { - /** - * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. - */ - then(fulfilledHandler?:(value:any) => any, rejectedHandler?:(reason:any) => any, progressHandler?:(note:any) => any):Promise; - - /** - * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. - * - * Alias `.caught();` for compatibility with earlier ECMAScript version. - */ - catch(handler:(reason:any) => any):Promise; - caught(handler:(reason:any) => any):Promise; - - /** - * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. - * - * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. - * - * Alias `.caught();` for compatibility with earlier ECMAScript version. - */ - //TODO expand this complex overload (weird) - catch(predicate:(reason:any) => boolean, handler:(reason:any) => any):Promise; - caught(predicate:(reason:any) => boolean, handler:(reason:any) => any):Promise; - - catch(ErrorClass:Function, handler:(reason:any) => any):Promise; - caught(ErrorClass:Function, handler:(reason:any) => any):Promise; - - /** - * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. - */ - error(rejectedHandler:(reason:any) => any):Promise; - - /** - * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. - * - * Alias `.lastly();` for compatibility with earlier ECMAScript version. - */ - finally(handler:(value:any) => any):Promise; - lastly(handler:(value:any) => any):Promise; - - /** - * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. - */ - bind(thisArg:any):Promise; - - /** - * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. - */ - done(fulfilledHandler?:(value:any) => any, rejectedHandler?:(reason:any) => any, progressHandler?:(note:any) => any):Promise; - - /** - * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. - */ - progressed(handler:(note:any) => any):Promise; - - /** - * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - delay(ms:number):Promise; - - /** - * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. - * - * You may specify a custom error message with the `message` parameter. - */ - - timeout(ms:number, message?:string):Promise; - - /** - * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. - * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. - */ - nodeify(callback?:Function):Promise; - - /** - * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. - */ - cancellable():Promise; - - /** - * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. - * - * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. - * - * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. - * - * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. - */ - cancel():Promise; - - /** - * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. - */ - fork(fulfilledHandler?:(value:any) => any, rejectedHandler?:(reason:any) => any, progressHandler?:(note:any) => any):Promise; - - /** - * Create an uncancellable promise based on this promise. - */ - uncancellable():Promise; - - /** - * See if this promise can be cancelled. - */ - isCancellable():boolean; - - /** - * See if this `promise` has been fulfilled. - */ - isFulfilled():boolean; - - /** - * See if this `promise` has been rejected. - */ - isRejected():boolean; - - /** - * See if this `promise` is still defer. - */ - isPending():boolean; - - /** - * See if this `promise` is resolved -> either fulfilled or rejected. - */ - isResolved():boolean; - - /** - * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. - */ - inspect():PromiseInspection; - - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName].call(obj, arg...); - * }); - * - */ - call(propertyName:string, ...args:any[]):Promise; - - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName]; - * }); - * - */ - get(propertyName:string):Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * return value; - * }); - * - * - * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` - * - * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. - */ - return(value:any):Promise; - thenReturn():Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * throw reason; - * }); - * - * Same limitations apply as with `.return()`. - * - * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. - */ - throw(reason:any):Promise; - thenThrow():Promise; - - /** - * Convert to String. - */ - toString():string; - - /** - * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. - */ - toJSON():Object; - - /** - * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - all():Promise; - - /** - * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - props():Promise; - - /** - * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - settle():Promise; - - /** - * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - any():Promise; - - /** - * Same as calling `Promise.race(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - some(count:number):Promise; - - /** - * Same as calling `Promise.some(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - race():Promise; - - /** - * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. - */ - spread(fulfilledHandler?:(value:any) => any, rejectedHandler?:(reason:any) => any):Promise; - - /** - * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - map(mapper:(item:any, index:number, arrayLength:number) => any):Promise; - - /** - * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - reduce(reducer:(total:number, current:any, index:number, arrayLength:number) => any, initialValue?:any):Promise; - - /** - * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - filter(filterer:(item:any, index:number, arrayLength:number) => any):Promise; - } - - interface PromiseResolver { - /** - * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. - */ - resolve(value:any):void; - - /** - * Reject the underlying promise with `reason` as the rejection reason. - */ - reject(reason:any):void; - - /** - * Progress the underlying promise with `value` as the progression value. - */ - progress(value:any):void; - - /** - * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. - * - * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. - */ - callback:Function; - } - - interface PromiseInspection { - /** - * See if the underlying promise was fulfilled at the creation time of this inspection object. - */ - isFulfilled():boolean; - - /** - * See if the underlying promise was rejected at the creation time of this inspection object. - */ - isRejected():boolean; - - /** - * See if the underlying promise was defer at the creation time of this inspection object. - */ - isPending():boolean; - - /** - * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. - * - * throws `TypeError` - */ - value():any; - - /** - * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. - * - * throws `TypeError` - */ - error():any; - } - - interface PromiseStatic { - /** - * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. - */ - new(resolver:(resolve:(value:any) => void, reject:(reason:any) => any) => void):Promise; - - /** - * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. - * - * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. - * - * Alias for `attempt();` for compatibility with earlier ECMAScript version. - */ - try(fn:() => any, args?:any[], ctx?:any):Promise; - try(fn:() => any, args?:ArrayLike, ctx?:any):Promise; - attempt(fn:() => any, args?:any[], ctx?:any):Promise; - attempt(fn:() => any, args?:ArrayLike, ctx?:any):Promise; - - /** - * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. - * This method is convenient when a function can sometimes return synchronously or throw synchronously. - */ - method(fn:Function):Function; - - /** - * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. - */ - resolve(value:any):Promise; - - /** - * Create a promise that is rejected with the given `reason`. - */ - reject(reason:any):Promise; - - /** - * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?:Promise(#promise-resolution). - */ - defer():PromiseResolver; - - /** - * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is:Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that:Promise assimilates the state of the thenable. - */ - cast(value:any):Promise; - - /** - * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. - */ - bind(thisArg:any):Promise; - - /** - * See if `value` is a trusted Promise. - */ - is(value:any):boolean; - - /** - * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. - */ - longStackTraces():void; - - /** - * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. - */ - delay(value:Promise, ms:number):Promise; - delay(value:any, ms:number):Promise; - delay(ms:number):Promise; - - /** - * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. - * - * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. - * - * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. - */ - promisify(nodeFunction:Function, receiver?:any):Function; - - /** - * This overload has been **deprecated**. The overload will continue working for now. The recommended method for promisifying multiple methods at once is ``Promise.promisifyAll(Object target)`` - */ - promisify(target:Object):Object; - - /** - * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. - * - * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. - */ - promisifyAll(target:Object):Object; - - /** - * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - coroutine(generatorFunction:Function):Function; - - /** - * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - spawn(generatorFunction:Function):Promise; - - /** - * This is relevant to browser environments with no module loader. - * - * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. - */ - noConflict():Object; - - /** - * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. - * - * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. - */ - onPossiblyUnhandledRejection(handler:(reason:any) => any):void; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. - */ - all(values:any[]):Promise; - - /** - * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. - * - * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. - * - * *The original object is not modified.* - */ - props(object:Promise):Promise; - props(object:Object):Promise; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. - * - * *original:The array is not modified. The input array sparsity is retained in the resulting array.* - */ - settle(values:any[]):Promise; - - /** - * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. - */ - any(values:any[]):Promise; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. - * - * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. - */ - race(values:any[]):Promise; - - /** - * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. - * - * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. - * - * *The original array is not modified.* - */ - some(values:any[], count:number):Promise; - - /** - * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. - */ - join(...values:any[]):Promise; - - /** - * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. - * - * *The original array is not modified.* - */ - map(values:any[], mapper:(item:any, index:number, arrayLength:number) => any):Promise; - - /** - * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - * - * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* - */ - reduce(values:any[], reducer:(total:number, current:any, index:number, arrayLength:number) => any, initialValue?:any):Promise; - - /** - * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. - * - * *The original array is not modified. - */ - filter(values:any[], filterer:(item:any, index?:number, arrayLength?:number) => any):Promise; - } +// Note: these are preliminary non-generic typings using `any`: the generic versions are ready but need (tsc >= v1.0.0) due to issues in the compiler +// - https://github.com/borisyankov/DefinitelyTyped/issues/1563 +// - https://github.com/borisyankov/DefinitelyTyped/tree/def/bluebird/bluebird + +declare class Promise { + /** + * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. + */ + constructor(resolver: (resolve: (value: any) => void, reject: (reason: any) => any) => void); + /** + * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + */ + then(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any, progressHandler?: (note: any) => any):Promise; + + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(handler: (reason: any) => any):Promise; + caught(handler: (reason: any) => any):Promise; + + /** + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + //TODO expand this complex overload (weird) + catch(predicate: (reason: any) => boolean, handler: (reason: any) => any): Promise; + caught(predicate: (reason: any) => boolean, handler: (reason: any) => any): Promise; + + catch(ErrorClass: Function, handler: (reason: any) => any): Promise; + caught(ErrorClass: Function, handler: (reason: any) => any): Promise; + + /** + * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. + */ + error(rejectedHandler: (reason: any) => any): Promise; + + /** + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * + * Alias `.lastly();` for compatibility with earlier ECMAScript version. + */ + finally(handler: (value: any) => any): Promise; + lastly(handler: (value: any) => any): Promise; + + /** + * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + */ + bind(thisArg: any): Promise; + + /** + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + */ + done(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any, progressHandler?: (note: any) => any): Promise; + + /** + * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. + */ + progressed(handler: (note: any) => any): Promise; + + /** + * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + delay(ms: number): Promise; + + /** + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. + * + * You may specify a custom error message with the `message` parameter. + */ + + timeout(ms: number, message?: string): Promise; + + /** + * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. + * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. + */ + nodeify(callback?: Function): Promise; + + /** + * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. + */ + cancellable(): Promise; + + /** + * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. + * + * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. + * + * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. + * + * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. + */ + cancel(): Promise; + + /** + * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. + */ + fork(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any, progressHandler?: (note: any) => any): Promise; + + /** + * Create an uncancellable promise based on this promise. + */ + uncancellable(): Promise; + + /** + * See if this promise can be cancelled. + */ + isCancellable(): boolean; + + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; + + /** + * See if this `promise` has been rejected. + */ + isRejected(): boolean; + + /** + * See if this `promise` is still defer. + */ + isPending(): boolean; + + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; + + /** + * Synchronously inspect the state of this `promise`. The `Promise.Inspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. + */ + inspect(): Promise.Inspection; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName].call(obj, arg...); + * }); + * + */ + call(propertyName: string, ...args: any[]): Promise; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName]; + * }); + * + */ + get(propertyName: string): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * return value; + * }); + * + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` + * + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. + */ + return(value: any): Promise; + thenReturn(): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * throw reason; + * }); + * + * Same limitations apply as with `.return()`. + * + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. + */ + throw(reason: any): Promise; + thenThrow(): Promise; + + /** + * Convert to String. + */ + toString(): string; + + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): Object; + + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + all(): Promise; + + /** + * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + props(): Promise; + + /** + * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + settle(): Promise; + + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + any(): Promise; + + /** + * Same as calling `Promise.race(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + some(count: number): Promise; + + /** + * Same as calling `Promise.some(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + race(): Promise; + + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + spread(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any): Promise; + + /** + * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + map(mapper: (item: any, index: number, arrayLength: number) => any): Promise; + + /** + * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + reduce(reducer: (total: number, current: any, index: number, arrayLength: number) => any, initialValue?: any): Promise; + + /** + * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + filter(filterer: (item: any, index: number, arrayLength: number) => any): Promise; +} + +declare module Promise { + + interface Resolver { + /** + * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. + */ + resolve(value: any): void; + + /** + * Reject the underlying promise with `reason` as the rejection reason. + */ + reject(reason: any): void; + + /** + * Progress the underlying promise with `value` as the progression value. + */ + progress(value: any): void; + + /** + * Gives you a callback representation of the `Promise.Resolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. + * + * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. + */ + callback:Function; + } + + interface Inspection { + /** + * See if the underlying promise was fulfilled at the creation time of this inspection object. + */ + isFulfilled(): boolean; + + /** + * See if the underlying promise was rejected at the creation time of this inspection object. + */ + isRejected(): boolean; + + /** + * See if the underlying promise was defer at the creation time of this inspection object. + */ + isPending(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. + * + * throws `TypeError` + */ + value(): any; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. + * + * throws `TypeError` + */ + error(): any; + } + + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + // function try(fn: () => any, args?: any[], ctx?: any): Promise; + + function attempt(fn: () => any, args?: any[], ctx?: any): Promise; + + /** + * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + function method(fn: Function): Function; + + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + function resolve(value: any): Promise; + + /** + * Create a promise that is rejected with the given `reason`. + */ + function reject(reason: any): Promise; + + /** + * Create a promise with undecided fate and return a `Promise.Resolver` to control it. See resolution?:Promise(#promise-resolution). + */ + function defer(): Promise.Resolver; + + /** + * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is:Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that:Promise assimilates the state of the thenable. + */ + function cast(value: any): Promise; + + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + function bind(thisArg: any): Promise; + + /** + * See if `value` is a trusted Promise. + */ + function is(value: any): boolean; + + /** + * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + */ + function longStackTraces(): void; + + /** + * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. + */ + function delay(value: Promise, ms: number): Promise; + + function delay(value: any, ms: number): Promise; + + function delay(ms: number): Promise; + + /** + * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + function promisify(nodeFunction: Function, receiver?: any): Function; + + /** + * This overload has been **deprecated**. The overload will continue working for now. The recommended method for promisifying multiple methods at once is ``Promise.promisifyAll(Object target)`` + */ + function promisify(target: Object): Object; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + function promisifyAll(target: Object): Object; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + function coroutine(generatorFunction: Function): Function; + + /** + * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + function spawn(generatorFunction: Function): Promise; + + /** + * This is relevant to browser environments with no module loader. + * + * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. + */ + function noConflict(): Object; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + function onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + function all(values: any[]): Promise; + + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + function props(object: Promise): Promise; + + function props(object: Object): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``Promise.Inspection`` instances at respective positions in relation to the input array. + * + * *original:The array is not modified. The input array sparsity is retained in the resulting array.* + */ + function settle(values: any[]): Promise; + + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + function any(values: any[]): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + function race(values: any[]): Promise; + + /** + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + function some(values: any[], count: number): Promise; + + /** + * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. + */ + function join(...values: any[]): Promise; + + /** + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + function map(values: any[], mapper: (item: any, index: number, arrayLength: number) => any): Promise; + + /** + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + function reduce(values: any[], reducer: (total: number, current: any, index: number, arrayLength: number) => any, initialValue?: any): Promise; + + /** + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + function filter(values: any[], filterer: (item: any, index?: number, arrayLength?: number) => any): Promise; +} + +declare module 'bluebird' { +export = Promise; } diff --git a/bootstrap.paginator/bootstrap.paginator.d.ts b/bootstrap.paginator/bootstrap.paginator.d.ts index fa530edd27..e45f1c3cec 100644 --- a/bootstrap.paginator/bootstrap.paginator.d.ts +++ b/bootstrap.paginator/bootstrap.paginator.d.ts @@ -1,3 +1,8 @@ +// Type definitions for bootstrap.paginator +// Project: https://github.com/lyonlai/bootstrap-paginator +// Definitions by: derikwhittaker +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// interface PaginatorOptions{ @@ -20,4 +25,4 @@ interface PaginatorOptions{ interface JQuery { bootstrapPaginator(): JQuery; bootstrapPaginator(options: PaginatorOptions): JQuery; -} \ No newline at end of file +} diff --git a/bootstrap.timepicker/bootstrap.timepicker.d.ts b/bootstrap.timepicker/bootstrap.timepicker.d.ts index 8685882762..2dd80b8581 100644 --- a/bootstrap.timepicker/bootstrap.timepicker.d.ts +++ b/bootstrap.timepicker/bootstrap.timepicker.d.ts @@ -1,4 +1,7 @@ - +// Type definitions for bootstrap.timepicker +// Project: https://github.com/jdewit/bootstrap-timepicker +// Definitions by: derikwhittaker +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -21,4 +24,4 @@ interface JQuery { timepicker(methodName: string): JQuery; timepicker(methodName: string, params: any): JQuery; timepicker(options: TimeickerOptions): JQuery; -} \ No newline at end of file +} diff --git a/bootstrap/bootstrap.d.ts b/bootstrap/bootstrap.d.ts index c14bf61d4b..b9fe9cd597 100644 --- a/bootstrap/bootstrap.d.ts +++ b/bootstrap/bootstrap.d.ts @@ -107,3 +107,6 @@ interface JQuery { affix(options?: AffixOptions): JQuery; } + +declare module "bootstrap" { +} diff --git a/box2d/box2dweb.d.ts b/box2d/box2dweb.d.ts index b5f5579890..0f0576b433 100644 --- a/box2d/box2dweb.d.ts +++ b/box2d/box2dweb.d.ts @@ -1,3 +1,8 @@ +// Type definitions for bootstrap.timepicker +// Project: http://code.google.com/p/box2dweb/ +// Definitions by: jbaldwin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /** * Box2DWeb-2.1.d.ts Copyright (c) 2012-2013 Josh Baldwin http://github.com/jbaldwin/box2dweb.d.ts * There are a few competing javascript Box2D ports. diff --git a/breeze/breeze-tests.ts b/breeze/breeze-tests.ts index e4ee91f747..3fe45d8bf6 100644 --- a/breeze/breeze-tests.ts +++ b/breeze/breeze-tests.ts @@ -440,7 +440,7 @@ function test_entityState() { function test_entityType() { var myMetadataStore: breeze.MetadataStore; var myEntityType: breeze.EntityType; - var dataProperty1, dataProperty2, navigationProperty1: breeze.DataProperty; + var dataProperty1: breeze.DataProperty, dataProperty2: breeze.DataProperty, navigationProperty1: breeze.DataProperty; var em1: breeze.EntityManager; var entityManager = new breeze.EntityType({ metadataStore: myMetadataStore, @@ -453,7 +453,7 @@ function test_entityType() { myEntityType.addProperty(navigationProperty1); var custType = em1.metadataStore.getEntityType("Customer"); var countryProp = custType.getProperty("Country"); - var valFn = function (v) { + var valFn = function (v: string) { if (v == null) return true; return (v.substring(0,2) === "US"); }; @@ -533,15 +533,20 @@ function test_entityType() { // DayOfWeek.Friday.toString() === "Friday"; //} +interface CustomEntityManager extends breeze.EntityManager +{ + customTag: string; +} + function test_event() { - var myEntityManager: breeze.EntityManager; - var myEntity, person: breeze.Entity; + var myEntityManager: CustomEntityManager; + var myEntity: breeze.Entity, person: breeze.Entity; var salaryEvent = new core.Event("salaryEvent", person); core.Event.enable("propertyChanged", myEntityManager, false); core.Event.enable("propertyChanged", myEntityManager, true); core.Event.enable("propertyChanged", myEntity.entityAspect, false); core.Event.enable("propertyChanged", myEntity.entityAspect, null); - core.Event.enable("validationErrorsChanged", myEntityManager, function (em) { + core.Event.enable("validationErrorsChanged", myEntityManager, function (em: CustomEntityManager) { return em.customTag === "blue"; }); core.Event.isEnabled("propertyChanged", myEntityManager); @@ -694,8 +699,18 @@ function test_validationOptions() { var newOptions = validationOptions.using({ validateOnQuery: true, validateOnSave: false }); } +interface NumericRange +{ + max: number; + min: number; +} + +interface NumericRangeValidatorFunctionContext extends breeze.ValidatorFunctionContext, NumericRange +{ +} + function test_validator() { - var valFn = function (v) { + var valFn = function (v: any) { if (v == null) return true; return ( v.substr(0,2)=== "US"); }; @@ -707,11 +722,11 @@ function test_validator() { var custType = metadataStore.getEntityType("Customer"); var countryProp = custType.getProperty("Country"); countryProp.validators.push(countryValidator); - function isValidZipCode(value) { + function isValidZipCode(value: string) { var re = /^\d{5}([\-]\d{4})?$/; return (re.test(value)); } - var valFn = function (v) { + valFn = function (v: any) { if (v.getProperty("Country") === "USA") { var postalCode = v.getProperty("PostalCode"); return isValidZipCode(postalCode); @@ -723,8 +738,8 @@ function test_validator() { var em1: breeze.EntityManager; var custType = em1.metadataStore.getEntityType("Customer"); custType.validators.push(zipCodeValidator); - var numericRangeValidator = function (context) { - var valFn = function (v, ctx) { + var numericRangeValidator = function (context: NumericRange) { + var valFn = function (v: any, ctx: NumericRangeValidatorFunctionContext) { if (v == null) return true; if (typeof (v) !== "number") return false; if (ctx.min != null && v < ctx.min) return false; @@ -784,7 +799,7 @@ function test_validator() { var errMsg = result.errorMessage; var context = result.context; var sameValidator = result.validator; - var valFn = function (v) { + valFn = function (v: any) { if (v == null) return true; return (v.substr(0,2) === "US"); }; @@ -807,7 +822,7 @@ function test_demo() { function test_corefns() { var o1: Object; - var kvfn = function (p) { return p; } + var kvfn = function (p: any) { return p; } core.objectForEach(o1, kvfn); var o2: Object; diff --git a/breeze/breeze-tests.ts.tscparams b/breeze/breeze-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/breeze/breeze-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/breeze/breeze.d.ts b/breeze/breeze.d.ts index 320f724adb..f4f7ff8cea 100644 --- a/breeze/breeze.d.ts +++ b/breeze/breeze.d.ts @@ -1,10 +1,8 @@ // Type definitions for Breeze 1.4 // Project: http://www.breezejs.com/ -// Definitions by: Boris Yankov , -// IdeaBlade +// Definitions by: Boris Yankov , IdeaBlade // Definitions: https://github.com/borisyankov/DefinitelyTyped - // Updated Jan 14 2011 - Jay Traband ( www.ideablade.com). // Updated March 27 2013 - John Lantz (www.ideablade.com). // Updated Aug 13 2013 - Steve Schmitt ( www.ideablade.com). @@ -140,7 +138,7 @@ declare module breeze { shortName: string; unmappedProperties: DataProperty[]; validators: Validator[]; - addProperty(dataProperty: DataProperty); + addProperty(dataProperty: DataProperty): ComplexType; getProperties(): DataProperty[]; } @@ -387,7 +385,7 @@ declare module breeze { exportEntities(entities?: Entity[]): string; fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: boolean): Q.Promise; fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: boolean): Q.Promise; - fetchEntityByKey(entityKey: EntityKey): Q.Promise; + fetchEntityByKey(entityKey: EntityKey, checkLocalCacheFirst?: boolean): Q.Promise; fetchMetadata(callback?: (schema: any) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise; generateTempKeyValue(entity: Entity): any; getChanges(): Entity[]; @@ -645,8 +643,8 @@ declare module breeze { addDataService(dataService: DataService): void; addEntityType(structuralType: IStructuralType): void; exportMetadata(): string; - fetchMetadata(dataService: string, callback?: (data) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise; - fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise; + fetchMetadata(dataService: string, callback?: (data: any) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise; + fetchMetadata(dataService: DataService, callback?: (data: any) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise; getDataService(serviceName: string): DataService; getEntityType(entityTypeName: string, okIfNotFound?: boolean): IStructuralType; getEntityTypes(): IStructuralType[]; @@ -655,7 +653,7 @@ declare module breeze { importMetadata(exportedString: string): MetadataStore; isEmpty(): boolean; registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) =>void ): void; - trackUnmappedType(entityCtor: Function, interceptor?: Function); + trackUnmappedType(entityCtor: Function, interceptor?: Function): void; setEntityTypeForResourceName(resourceName: string, entityType: EntityType): void; setEntityTypeForResourceName(resourceName: string, entityTypeName: string): void; getEntityTypeNameForResourceName(resourceName: string): string; @@ -679,7 +677,7 @@ declare module breeze { serverPropertyNameToClient(serverPropertyName: string): string; serverPropertyNameToClient(serverPropertyName: string, property: IProperty): string; - setAsDefault(); + setAsDefault(): NamingConvention; } interface NamingConventionOptions { @@ -848,8 +846,8 @@ declare module breeze { static string(): Validator; static stringLength(context: { maxLength: number; minLength: number; }): Validator; - static register(validator: Validator); - static registerFactory(fn: () => Validator, name: string); + static register(validator: Validator): void; + static registerFactory(fn: () => Validator, name: string): void; validate(value: any, context?: any): ValidationError; getMessage(): string; diff --git a/breeze/breeze.d.ts.tscparams b/breeze/breeze.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/breeze/breeze.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/browser-harness/browser-harness.d.ts b/browser-harness/browser-harness.d.ts index 73eda812c5..68dbf8be51 100644 --- a/browser-harness/browser-harness.d.ts +++ b/browser-harness/browser-harness.d.ts @@ -6,28 +6,27 @@ /// declare module "browser-harness" { - import nodeEvents = require("events"); - interface HarnessEvents extends nodeEvents.NodeEventEmitter { - once(event: string, listener: (driver: Driver) => void): nodeEvents.NodeEventEmitter; - once(event: 'ready', listener: (driver: Driver) => void): nodeEvents.NodeEventEmitter; + interface HarnessEvents extends NodeEventEmitter { + once(event: string, listener: (driver: Driver) => void): NodeEventEmitter; + once(event: 'ready', listener: (driver: Driver) => void): NodeEventEmitter; - on(event: string, listener: (driver: Driver) => void): nodeEvents.NodeEventEmitter; - on(event: 'ready', listener: (driver: Driver) => void): nodeEvents.NodeEventEmitter; + on(event: string, listener: (driver: Driver) => void): NodeEventEmitter; + on(event: 'ready', listener: (driver: Driver) => void): NodeEventEmitter; } - interface DriverEvents extends nodeEvents.NodeEventEmitter { - once(event: string, listener: (text: string) => void): nodeEvents.NodeEventEmitter; - once(event: 'console.log', listener: (text: string) => void): nodeEvents.NodeEventEmitter; - once(event: 'console.warn', listener: (text: string) => void): nodeEvents.NodeEventEmitter; - once(event: 'console.error', listener: (text: string) => void): nodeEvents.NodeEventEmitter; - once(event: 'window.onerror', listener: (text: string) => void): nodeEvents.NodeEventEmitter; + interface DriverEvents extends NodeEventEmitter { + once(event: string, listener: (text: string) => void): NodeEventEmitter; + once(event: 'console.log', listener: (text: string) => void): NodeEventEmitter; + once(event: 'console.warn', listener: (text: string) => void): NodeEventEmitter; + once(event: 'console.error', listener: (text: string) => void): NodeEventEmitter; + once(event: 'window.onerror', listener: (text: string) => void): NodeEventEmitter; - on(event: string, listener: (text: string) => void): nodeEvents.NodeEventEmitter; - on(event: 'console.log', listener: (text: string) => void): nodeEvents.NodeEventEmitter; - on(event: 'console.warn', listener: (text: string) => void): nodeEvents.NodeEventEmitter; - on(event: 'console.error', listener: (text: string) => void): nodeEvents.NodeEventEmitter; - on(event: 'window.onerror', listener: (text: string) => void): nodeEvents.NodeEventEmitter; + on(event: string, listener: (text: string) => void): NodeEventEmitter; + on(event: 'console.log', listener: (text: string) => void): NodeEventEmitter; + on(event: 'console.warn', listener: (text: string) => void): NodeEventEmitter; + on(event: 'console.error', listener: (text: string) => void): NodeEventEmitter; + on(event: 'window.onerror', listener: (text: string) => void): NodeEventEmitter; } export interface Driver { diff --git a/browserify/browserify.d.ts b/browserify/browserify.d.ts index d66bf5a5f4..e725de98c8 100644 --- a/browserify/browserify.d.ts +++ b/browserify/browserify.d.ts @@ -5,7 +5,7 @@ /// -interface BrowserifyObject extends EventEmitter { +interface BrowserifyObject extends NodeEventEmitter { add(file: string): BrowserifyObject; require(file: string, opts?: { expose: string; @@ -31,6 +31,6 @@ declare module "browserify" { entries?: string[]; noParse?: string[]; }): BrowserifyObject; - + export = browserify; } \ No newline at end of file diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 059e835b84..7318744012 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chai 1.7.2 +// Type definitions for chai 1.7.2 // Project: http://chaijs.com/ // Definitions by: Jed Hunsaker // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped @@ -6,7 +6,7 @@ declare module chai { - function expect(target: any): Expect; + function expect(target: any, message?: string): Expect; // Provides a way to extend the internals of Chai function use(fn: (chai: any, utils: any) => void); diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 97568dbdcb..affee34583 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -1,3 +1,8 @@ +// Type definitions for CodeMirror +// Project: https://github.com/marijnh/CodeMirror +// Definitions by: mihailik +// Definitions: https://github.com/borisyankov/DefinitelyTyped + declare function CodeMirror(host: HTMLElement, options?: CodeMirror.EditorConfiguration): CodeMirror.Editor; declare function CodeMirror(callback: (host: HTMLElement) => void , options?: CodeMirror.EditorConfiguration): CodeMirror.Editor; diff --git a/cometd/cometd.d.ts b/cometd/cometd.d.ts index 6002fffb06..592c6c963d 100644 --- a/cometd/cometd.d.ts +++ b/cometd/cometd.d.ts @@ -1,5 +1,6 @@ // Type definitions for CometD 2.5.1 // Project: http://cometd.org +// Definitions by: Derek Cicerone // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module CometD { diff --git a/createjs/createjs.d.ts b/createjs/createjs.d.ts index 20f2a7574f..3ebfd11bf5 100644 --- a/createjs/createjs.d.ts +++ b/createjs/createjs.d.ts @@ -1,6 +1,6 @@ -// Type definitions for EaselJS 0.7.0, TweenJS 0.5.0, SoundJS 0.5.0, PreloadJS 0.4.0 +// Type definitions for EaselJS 0.7.1, TweenJS 0.5.1, SoundJS 0.5.2, PreloadJS 0.4.1 // Project: http://www.createjs.com/#!/EaselJS -// Definitions by: Pedro Ferreira +// Definitions by: Pedro Ferreira , Chris Smith , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped /* @@ -23,13 +23,13 @@ declare module createjs { // properties bubbles: boolean; cancelable: boolean; - currentTarget: Object; + currentTarget: any; // It is 'Object' type officially, but 'any' is easier to use. defaultPrevented: boolean; eventPhase: number; immediatePropagationStopped: boolean; propagationStopped: boolean; removed: boolean; - target: Object; + target: any; // It is 'Object' type officially, but 'any' is easier to use. timeStamp: number; type: string; @@ -38,15 +38,15 @@ declare module createjs { delta: number; error: string; id: string; - item: any; - loaded: number; + item: any; + loaded: number; name: string; next: string; - params: any[]; + params: any; paused: boolean; progress: number; - rawResult: Object; - result: Object; + rawResult: any; + result: any; runTime: number; src: string; time: number; @@ -78,16 +78,19 @@ declare module createjs { off(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; off(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; off(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; - on(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; - on(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function; - on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object; - on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): Object; + off(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + on(type: string, listener: (eventObj: Object) => boolean, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + on(type: string, listener: (eventObj: Object) => void, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; + on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; removeAllEventListeners(type?: string): void; removeEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; removeEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" toString(): string; + willTrigger(type: string): boolean; } export function indexOf(array: any[], searchElement: Object): number; diff --git a/cryptojs/cryptojs.d.ts b/cryptojs/cryptojs.d.ts index c0773525ce..d9c77dbe97 100644 --- a/cryptojs/cryptojs.d.ts +++ b/cryptojs/cryptojs.d.ts @@ -1,7 +1,6 @@ // Type definitions for CryptoJS 3.1.2 // Project: https://code.google.com/p/crypto-js/ -// Definitions by: -// Gia Bảo @ Sân Đình +// Definitions by: Gia Bảo @ Sân Đình // Definitions: https://github.com/borisyankov/DefinitelyTyped declare var CryptoJS: CryptoJS.CryptoJSStatic; @@ -107,6 +106,8 @@ declare module CryptoJS{ interface Cipher extends ICipher{} interface IStreamCipher extends ICipher{ + drop?: number; + createEncryptor(key: WordArray, cfg?: C): IStreamCipher createDecryptor(key: WordArray, cfg?: C): IStreamCipher @@ -339,10 +340,7 @@ declare module CryptoJS{ interface PBKDF2 extends EvpKDF{} //PBKDF2 is same as EvpKDF - interface RC4Drop extends RC4, lib.ICipher{} - interface IRC4DropCfg{ - drop?: number //default 192 - } + interface RC4Drop extends RC4 { } } module mode{ @@ -439,7 +437,7 @@ declare module CryptoJS{ RabbitLegacy: CryptoJS.lib.CipherHelper Rabbit: CryptoJS.lib.CipherHelper RC4: CryptoJS.lib.CipherHelper - RC4Drop: CryptoJS.lib.ICipherHelper + RC4Drop: CryptoJS.lib.ICipherHelper MD5: CryptoJS.lib.HasherHelper HmacMD5: CryptoJS.lib.IHasherHmacHelper diff --git a/d3/d3.d.ts b/d3/d3.d.ts index fe8887b7ed..4bce47e2b3 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1,6 +1,6 @@ // Type definitions for d3JS // Project: http://d3js.org/ -// Definitions by: TypeScript samples +// Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module D3 { @@ -847,7 +847,7 @@ declare module D3 { export interface Set{ has(value: any): boolean; - Add(value: any): any; + add(value: any): any; remove(value: any): boolean; values(): Array; forEach(func: (value: any) => void ): void; diff --git a/domready/domready-tests.ts b/domready/domready-tests.ts new file mode 100644 index 0000000000..7b7c40dfb8 --- /dev/null +++ b/domready/domready-tests.ts @@ -0,0 +1,5 @@ +/// + +domready(function () { + // dom is loaded! +}) \ No newline at end of file diff --git a/domready/domready.d.ts b/domready/domready.d.ts new file mode 100644 index 0000000000..c951f93972 --- /dev/null +++ b/domready/domready.d.ts @@ -0,0 +1,6 @@ +// Type definitions for domready +// Project: https://github.com/ded/domready +// Definitions by: Christian Holm Nielsen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare function domready(callback: () => any) : void; \ No newline at end of file diff --git a/dot/dot-tests.ts b/dot/dot-tests.ts new file mode 100644 index 0000000000..59e6cff759 --- /dev/null +++ b/dot/dot-tests.ts @@ -0,0 +1,32 @@ +/// + +var headertmpl = "

{{=it.title}}

"; + +var pagetmpl = "

Here is the page using a header template< / h2 >\n" + + "{{#def.header}}\n" + + "{{=it.name}}"; + +var customizableheadertmpl = "{{#def.header}}" + + "\n{{#def.mycustominjectionintoheader || ''} }"; + +var pagetmplwithcustomizableheader = "

Here is the page with customized header template

\n" + + "{{##def.mycustominjectionintoheader:\n" + + "
{{=it.title}} is not {{=it.name}}
\n" + + "#}}\n" + + "{{#def.customheader}}\n" + + "{{=it.name}}"; + +var def = { + header: headertmpl, + customheader: customizableheadertmpl +}; +var data = { + title: "My title", + name: "My name" +}; + +var pagefn = doT.template(pagetmpl, undefined, def); +var content = pagefn(data); + +pagefn = doT.template(pagetmplwithcustomizableheader, undefined, def); +var contentcustom = pagefn(data); diff --git a/dot/dot.d.ts b/dot/dot.d.ts new file mode 100644 index 0000000000..2ab677c26d --- /dev/null +++ b/dot/dot.d.ts @@ -0,0 +1,50 @@ +// Type definitions for doT v1.0.1 +// Project: https://github.com/olado/doT +// Definitions by: ZombieHunter +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var doT: doT.doTStatic; + +declare module doT { + + interface doTStatic { + /** + * Version number + */ + version: string; + /** + * Default template settings + */ + templateSettings: TemplateSettings; + + /** + * Compile template + */ + template(tmpl: string, c?: TemplateSettings, def?: Object): Function; + + /** + * For express + */ + compile(tmpl: string, def?: Object): Function; + } + + interface TemplateSettings { + evaluate: RegExp; + interpolate: RegExp; + encode: RegExp; + use: RegExp; + useParams: RegExp; + define: RegExp; + defineParams: RegExp; + conditional: RegExp; + iterate: RegExp; + varname: string; + strip: boolean; + append: boolean; + selfcontained: boolean; + } +} + +interface String { + encodeHTML(): string; +} \ No newline at end of file diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index f02b59f73f..ac630c9d4a 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -1,5 +1,6 @@ // Type definitions for Dropzone 3.7.1 // Project: http://www.dropzonejs.com/ +// Definitions by: Natan Vivo // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -74,4 +75,4 @@ declare class Dropzone { interface JQuery { dropzone(options: DropzoneOptions): Dropzone; -} \ No newline at end of file +} diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts index c2567f62c5..6c2013ec71 100644 --- a/durandal/durandal.d.ts +++ b/durandal/durandal.d.ts @@ -1,3 +1,8 @@ +// Type definitions for Durandal 2.0.1 +// Project: http://durandaljs.com +// Definitions by: Evan Larsen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. @@ -13,193 +18,8 @@ * @requires jquery */ declare module 'durandal/system' { - /** - * Durandal's version. - */ - export var version: string; - - /** - * A noop function. - */ - export var noop: Function; - - /** - * Gets the module id for the specified object. - * @param {object} obj The object whose module id you wish to determine. - * @returns {string} The module id. - */ - export function getModuleId(obj: any): string; - - /** - * Sets the module id for the specified object. - * @param {object} obj The object whose module id you wish to set. - * @param {string} id The id to set for the specified object. - */ - export function setModuleId(obj, id: string): void; - - /** - * Resolves the default object instance for a module. If the module is an object, the module is returned. If the module is a function, that function is called with `new` and it's result is returned. - * @param {object} module The module to use to get/create the default object for. - * @returns {object} The default object for the module. - */ - export function resolveObject(module: any): any; - - /** - * Gets/Sets whether or not Durandal is in debug mode. - * @param {boolean} [enable] Turns on/off debugging. - * @returns {boolean} Whether or not Durandal is current debugging. - */ - export function debug(enable?: boolean): boolean; - - /** - * Logs data to the console. Pass any number of parameters to be logged. Log output is not processed if the framework is not running in debug mode. - * @param {object} info* The objects to log. - */ - export function log(...msgs: any[]): void; - - /** - * Logs an error. - * @param {string} obj The error to report. - */ - export function error(error: string): void; - - /** - * Logs an error. - * @param {Error} obj The error to report. - */ - export function error(error: Error): void; - - /** - * Asserts a condition by throwing an error if the condition fails. - * @param {boolean} condition The condition to check. - * @param {string} message The message to report in the error if the condition check fails. - */ - export function assert(condition: boolean, message: string): void; - - /** - * Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise. - * @param {function} [action] The action to defer. You will be passed the deferred object as a paramter. - * @returns {JQueryDeferred} The deferred object. - */ - export function defer(action?: (dfd: JQueryDeferred) => void ): JQueryDeferred; - - /** - * Creates a simple V4 UUID. This should not be used as a PK in your database. It can be used to generate internal, unique ids. For a more robust solution see [node-uuid](https://github.com/broofa/node-uuid). - * @returns {string} The guid. - */ - export function guid(): string; - - /** - * Uses require.js to obtain a module. This function returns a promise which resolves with the module instance. - * @param {string} moduleId The id of the module to load. - * @returns {JQueryPromise} A promise for the loaded module. - */ - export function acquire(moduleId: string): JQueryPromise; - - /** - * Uses require.js to obtain an array of modules. This function returns a promise which resolves with the modules instances in an array. - * @param {string[]} moduleIds The ids of the modules to load. - * @returns {JQueryPromise} A promise for the loaded module. - */ - export function acquire(modules: string[]): JQueryPromise; - - /** - * Uses require.js to obtain multiple modules. This function returns a promise which resolves with the module instances in an array. - * @param {string} moduleIds* The ids of the modules to load. - * @returns {JQueryPromise} A promise for the loaded module. - */ - export function acquire(...moduleIds: string[]): JQueryPromise; - - /** - * Extends the first object with the properties of the following objects. - * @param {object} obj The target object to extend. - * @param {object} extension* Uses to extend the target object. - */ - export function extend(obj: any, ...extensions: any[]): any; - - /** - * Uses a setTimeout to wait the specified milliseconds. - * @param {number} milliseconds The number of milliseconds to wait. - * @returns {JQueryPromise} - */ - export function wait(milliseconds: number): JQueryPromise; - - /** - * Gets all the owned keys of the specified object. - * @param {object} object The object whose owned keys should be returned. - * @returns {string[]} The keys. - */ - export function keys(obj: any): string[]; - - /** - * Determines if the specified object is an html element. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isElement(obj: any): boolean; - - /** - * Determines if the specified object is an array. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isArray(obj: any): boolean; - - /** - * Determines if the specified object is a boolean. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isObject(obj: any): boolean; - - /** - * Determines if the specified object is a promise. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isPromise(obj: any): boolean; - - /** - * Determines if the specified object is a function arguments object. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isArguments(obj: any): boolean; - - /** - * Determines if the specified object is a function. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isFunction(obj: any): boolean; - - /** - * Determines if the specified object is a string. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isString(obj: any): boolean; - - /** - * Determines if the specified object is a number. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isNumber(obj: any): boolean; - - /** - * Determines if the specified object is a date. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isDate(obj: any): boolean; - - /** - * Determines if the specified object is a boolean. - * @param {object} object The object to check. - * @returns {boolean} True if matches the type, false otherwise. - */ - export function isBoolean(obj: any): boolean; + var theModule: DurandalSystemModule; + export = theModule; } /** @@ -208,75 +28,8 @@ declare module 'durandal/system' { * @requires jquery */ declare module 'durandal/viewEngine' { - /** - * The file extension that view source files are expected to have. - * @default .html - */ - export var viewExtension: string; - - /** - * The name of the RequireJS loader plugin used by the viewLocator to obtain the view source. (Use requirejs to map the plugin's full path). - * @default text - */ - export var viewPlugin: string; - - /** - * Determines if the url is a url for a view, according to the view engine. - * @param {string} url The potential view url. - * @returns {boolean} True if the url is a view url, false otherwise. - */ - export function isViewUrl(url: string):boolean; - - /** - * Converts a view url into a view id. - * @param {string} url The url to convert. - * @returns {string} The view id. - */ - export function convertViewUrlToViewId(url: string): string; - - /** - * Converts a view id into a full RequireJS path. - * @param {string} viewId The view id to convert. - * @returns {string} The require path. - */ - export function convertViewIdToRequirePath(viewId: string): string; - - /** - * Parses the view engine recognized markup and returns DOM elements. - * @param {string} markup The markup to parse. - * @returns {HTMLElement[]} The elements. - */ - export function parseMarkup(markup: string):Node[]; - - /** - * Calls `parseMarkup` and then pipes the results through `ensureSingleElement`. - * @param {string} markup The markup to process. - * @returns {HTMLElement} The view. - */ - export function processMarkup(markup: string): HTMLElement; - - /** - * Converts an array of elements into a single element. White space and comments are removed. If a single element does not remain, then the elements are wrapped. - * @param {HTMLElement[]} allElements The elements. - * @returns {HTMLElement} A single element. - */ - export function ensureSingleElement(allElements: Node[]): HTMLElement; - - /** - * Creates the view associated with the view id. - * @param {string} viewId The view id whose view should be created. - * @returns {JQueryPromise} A promise of the view. - */ - export function createView(viewId: string): JQueryPromise; - - /** - * Called when a view cannot be found to provide the opportunity to locate or generate a fallback view. Mainly used to ease development. - * @param {string} viewId The view id whose view should be created. - * @param {string} requirePath The require path that was attempted. - * @param {Error} requirePath The error that was returned from the attempt to locate the default view. - * @returns {Promise} A promise for the fallback view. - */ - export function createFallbackView(viewId: string, requirePath: string, err: Error): JQueryPromise; + var theModule: DurandalViewEngineModule; + export = theModule; } /** @@ -305,7 +58,7 @@ declare module 'durandal/binder' { * @param {DOMElement} view The view that is about to be bound. * @param {object} instruction The object that carries the binding instructions. */ - export var binding: (data:any, view:HTMLElement, instruction:BindingInstruction) => void; + export var binding: (data: any, view: HTMLElement, instruction: BindingInstruction) => void; /** * Called after every binding operation. Does nothing by default. @@ -335,7 +88,7 @@ declare module 'durandal/binder' { * @param {object} [obj] The data to bind to, causing the creation of a child binding context if present. */ export function bindContext(bindingContext: KnockoutBindingContext, view: HTMLElement, obj?: any): BindingInstruction; - + /** * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context. * @param {object} obj The data to bind to. @@ -358,7 +111,7 @@ declare module 'durandal/activator' { * @property {ActivatorSettings} defaults */ export var defaults: DurandalActivatorSettings; - + /** * Creates a new activator. * @method create @@ -383,62 +136,8 @@ declare module 'durandal/activator' { * @requires viewEngine */ declare module 'durandal/viewLocator' { - /** - * Allows you to set up a convention for mapping module folders to view folders. It is a convenience method that customizes `convertModuleIdToViewId` and `translateViewIdToArea` under the covers. - * @param {string} [modulesPath] A string to match in the path and replace with the viewsPath. If not specified, the match is 'viewmodels'. - * @param {string} [viewsPath] The replacement for the modulesPath. If not specified, the replacement is 'views'. - * @param {string} [areasPath] Partial views are mapped to the "views" folder if not specified. Use this parameter to change their location. - */ - export function useConvention(modulesPath?: string, viewsPath?: string, areasPath?: string): void; - - /** - * Maps an object instance to a view instance. - * @param {object} obj The object to locate the view for. - * @param {string} [area] The area to translate the view to. - * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. - * @returns {Promise} A promise of the view. - */ - export function locateViewForObject(obj: any, area:string, elementsToSearch?: HTMLElement[]): JQueryPromise; - - /** - * Converts a module id into a view id. By default the ids are the same. - * @param {string} moduleId The module id. - * @returns {string} The view id. - */ - export function convertModuleIdToViewId(moduleId: string): string; - - /** - * If no view id can be determined, this function is called to genreate one. By default it attempts to determine the object's type and use that. - * @param {object} obj The object to determine the fallback id for. - * @returns {string} The view id. - */ - export function determineFallbackViewId(obj: any): string; - - /** - * Takes a view id and translates it into a particular area. By default, no translation occurs. - * @param {string} viewId The view id. - * @param {string} area The area to translate the view to. - * @returns {string} The translated view id. - */ - export function translateViewIdToArea(viewId: string, area: string): string; - - /** - * Locates the specified view. - * @param {string|DOMElement} view A view. It will be immediately returned. - * @param {string} [area] The area to translate the view to. - * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. - * @returns {Promise} A promise of the view. - */ - export function locateView(view: HTMLElement, area?: string, elementsToSearch?: HTMLElement[]): JQueryPromise; - - /** - * Locates the specified view. - * @param {string|DOMElement} viewUrlOrId A view url or view id to locate. - * @param {string} [area] The area to translate the view to. - * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. - * @returns {Promise} A promise of the view. - */ - export function locateView(viewUrlOrId: string, area?: string, elementsToSearch?: HTMLElement[]): JQueryPromise; + var theModule: DurandalViewLocatorModule; + export = theModule; } /** @@ -608,7 +307,7 @@ declare module 'plugins/dialog' { * @param {string} viewUrl The view url relative to the base url which the view locator will use to find the message box's view. * @static */ - static setViewUrl(url:string):void; + static setViewUrl(url: string): void; } interface DialogContext { @@ -676,7 +375,7 @@ declare module 'plugins/dialog' { * @param {DialogContext} dialogContext The context to add. */ export function addContext(name: string, modalContext: DialogContext): void; - + /** * Gets the dialog model that is associated with the specified object. * @param {object} obj The object for whom to retrieve the dialog. @@ -815,7 +514,7 @@ declare module 'plugins/http' { * @default callback */ export var callbackParam: string; - + /** * Makes an HTTP GET request. * @param {string} url The url to send the get request to. @@ -832,7 +531,7 @@ declare module 'plugins/http' { * @returns {Promise} A promise of the response data. */ export function jsonp(url: string, query?: Object, callbackParam?: string): JQueryPromise; - + /** * Makes an HTTP POST request. * @param {string} url The url to send the post request to. @@ -1093,6 +792,329 @@ declare module 'plugins/router' { export = theModule; } +interface DurandalSystemModule { + /** + * Durandal's version. + */ + version: string; + + /** + * A noop function. + */ + noop: Function; + + /** + * Gets the module id for the specified object. + * @param {object} obj The object whose module id you wish to determine. + * @returns {string} The module id. + */ + getModuleId(obj: any): string; + + /** + * Sets the module id for the specified object. + * @param {object} obj The object whose module id you wish to set. + * @param {string} id The id to set for the specified object. + */ + setModuleId(obj, id: string): void; + + /** + * Resolves the default object instance for a module. If the module is an object, the module is returned. If the module is a function, that function is called with `new` and it's result is returned. + * @param {object} module The module to use to get/create the default object for. + * @returns {object} The default object for the module. + */ + resolveObject(module: any): any; + + /** + * Gets/Sets whether or not Durandal is in debug mode. + * @param {boolean} [enable] Turns on/off debugging. + * @returns {boolean} Whether or not Durandal is current debugging. + */ + debug(enable?: boolean): boolean; + + /** + * Logs data to the console. Pass any number of parameters to be logged. Log output is not processed if the framework is not running in debug mode. + * @param {object} info* The objects to log. + */ + log(...msgs: any[]): void; + + /** + * Logs an error. + * @param {string} obj The error to report. + */ + error(error: string): void; + + /** + * Logs an error. + * @param {Error} obj The error to report. + */ + error(error: Error): void; + + /** + * Asserts a condition by throwing an error if the condition fails. + * @param {boolean} condition The condition to check. + * @param {string} message The message to report in the error if the condition check fails. + */ + assert(condition: boolean, message: string): void; + + /** + * Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise. + * @param {function} [action] The action to defer. You will be passed the deferred object as a paramter. + * @returns {JQueryDeferred} The deferred object. + */ + defer(action?: (dfd: JQueryDeferred) => void): JQueryDeferred; + + /** + * Creates a simple V4 UUID. This should not be used as a PK in your database. It can be used to generate internal, unique ids. For a more robust solution see [node-uuid](https://github.com/broofa/node-uuid). + * @returns {string} The guid. + */ + guid(): string; + + /** + * Uses require.js to obtain a module. This function returns a promise which resolves with the module instance. + * @param {string} moduleId The id of the module to load. + * @returns {JQueryPromise} A promise for the loaded module. + */ + acquire(moduleId: string): JQueryPromise; + + /** + * Uses require.js to obtain an array of modules. This function returns a promise which resolves with the modules instances in an array. + * @param {string[]} moduleIds The ids of the modules to load. + * @returns {JQueryPromise} A promise for the loaded module. + */ + acquire(modules: string[]): JQueryPromise; + + /** + * Uses require.js to obtain multiple modules. This function returns a promise which resolves with the module instances in an array. + * @param {string} moduleIds* The ids of the modules to load. + * @returns {JQueryPromise} A promise for the loaded module. + */ + acquire(...moduleIds: string[]): JQueryPromise; + + /** + * Extends the first object with the properties of the following objects. + * @param {object} obj The target object to extend. + * @param {object} extension* Uses to extend the target object. + */ + extend(obj: any, ...extensions: any[]): any; + + /** + * Uses a setTimeout to wait the specified milliseconds. + * @param {number} milliseconds The number of milliseconds to wait. + * @returns {JQueryPromise} + */ + wait(milliseconds: number): JQueryPromise; + + /** + * Gets all the owned keys of the specified object. + * @param {object} object The object whose owned keys should be returned. + * @returns {string[]} The keys. + */ + keys(obj: any): string[]; + + /** + * Determines if the specified object is an html element. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isElement(obj: any): boolean; + + /** + * Determines if the specified object is an array. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isArray(obj: any): boolean; + + /** + * Determines if the specified object is a boolean. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isObject(obj: any): boolean; + + /** + * Determines if the specified object is a promise. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isPromise(obj: any): boolean; + + /** + * Determines if the specified object is a function arguments object. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isArguments(obj: any): boolean; + + /** + * Determines if the specified object is a function. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isFunction(obj: any): boolean; + + /** + * Determines if the specified object is a string. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isString(obj: any): boolean; + + /** + * Determines if the specified object is a number. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isNumber(obj: any): boolean; + + /** + * Determines if the specified object is a date. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isDate(obj: any): boolean; + + /** + * Determines if the specified object is a boolean. + * @param {object} object The object to check. + * @returns {boolean} True if matches the type, false otherwise. + */ + isBoolean(obj: any): boolean; +} + +interface DurandalViewEngineModule { + + /** + * The file extension that view source files are expected to have. + * @default .html + */ + viewExtension: string; + + /** + * The name of the RequireJS loader plugin used by the viewLocator to obtain the view source. (Use requirejs to map the plugin's full path). + * @default text + */ + viewPlugin: string; + + /** + * Determines if the url is a url for a view, according to the view engine. + * @param {string} url The potential view url. + * @returns {boolean} True if the url is a view url, false otherwise. + */ + isViewUrl(url: string): boolean; + + /** + * Converts a view url into a view id. + * @param {string} url The url to convert. + * @returns {string} The view id. + */ + convertViewUrlToViewId(url: string): string; + + /** + * Converts a view id into a full RequireJS path. + * @param {string} viewId The view id to convert. + * @returns {string} The require path. + */ + convertViewIdToRequirePath(viewId: string): string; + + /** + * Parses the view engine recognized markup and returns DOM elements. + * @param {string} markup The markup to parse. + * @returns {HTMLElement[]} The elements. + */ + parseMarkup(markup: string): Node[]; + + /** + * Calls `parseMarkup` and then pipes the results through `ensureSingleElement`. + * @param {string} markup The markup to process. + * @returns {HTMLElement} The view. + */ + processMarkup(markup: string): HTMLElement; + + /** + * Converts an array of elements into a single element. White space and comments are removed. If a single element does not remain, then the elements are wrapped. + * @param {HTMLElement[]} allElements The elements. + * @returns {HTMLElement} A single element. + */ + ensureSingleElement(allElements: Node[]): HTMLElement; + + /** + * Creates the view associated with the view id. + * @param {string} viewId The view id whose view should be created. + * @returns {JQueryPromise} A promise of the view. + */ + createView(viewId: string): JQueryPromise; + + /** + * Called when a view cannot be found to provide the opportunity to locate or generate a fallback view. Mainly used to ease development. + * @param {string} viewId The view id whose view should be created. + * @param {string} requirePath The require path that was attempted. + * @param {Error} requirePath The error that was returned from the attempt to locate the default view. + * @returns {Promise} A promise for the fallback view. + */ + createFallbackView(viewId: string, requirePath: string, err: Error): JQueryPromise; +} + +interface DurandalViewLocatorModule { + + /** + * Allows you to set up a convention for mapping module folders to view folders. It is a convenience method that customizes `convertModuleIdToViewId` and `translateViewIdToArea` under the covers. + * @param {string} [modulesPath] A string to match in the path and replace with the viewsPath. If not specified, the match is 'viewmodels'. + * @param {string} [viewsPath] The replacement for the modulesPath. If not specified, the replacement is 'views'. + * @param {string} [areasPath] Partial views are mapped to the "views" folder if not specified. Use this parameter to change their location. + */ + useConvention(modulesPath?: string, viewsPath?: string, areasPath?: string): void; + + /** + * Maps an object instance to a view instance. + * @param {object} obj The object to locate the view for. + * @param {string} [area] The area to translate the view to. + * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. + * @returns {Promise} A promise of the view. + */ + locateViewForObject(obj: any, area: string, elementsToSearch?: HTMLElement[]): JQueryPromise; + + /** + * Converts a module id into a view id. By default the ids are the same. + * @param {string} moduleId The module id. + * @returns {string} The view id. + */ + convertModuleIdToViewId(moduleId: string): string; + + /** + * If no view id can be determined, this function is called to genreate one. By default it attempts to determine the object's type and use that. + * @param {object} obj The object to determine the fallback id for. + * @returns {string} The view id. + */ + determineFallbackViewId(obj: any): string; + + /** + * Takes a view id and translates it into a particular area. By default, no translation occurs. + * @param {string} viewId The view id. + * @param {string} area The area to translate the view to. + * @returns {string} The translated view id. + */ + translateViewIdToArea(viewId: string, area: string): string; + + /** + * Locates the specified view. + * @param {string|DOMElement} view A view. It will be immediately returned. + * @param {string} [area] The area to translate the view to. + * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. + * @returns {Promise} A promise of the view. + */ + locateView(view: HTMLElement, area?: string, elementsToSearch?: HTMLElement[]): JQueryPromise; + + /** + * Locates the specified view. + * @param {string|DOMElement} viewUrlOrId A view url or view id to locate. + * @param {string} [area] The area to translate the view to. + * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. + * @returns {Promise} A promise of the view. + */ + locateView(viewUrlOrId: string, area?: string, elementsToSearch?: HTMLElement[]): JQueryPromise; +} + interface DurandalEventSubscription { /** * Attaches a callback to the event subscription. @@ -1346,7 +1368,7 @@ interface DurandalHistoryOptions { /** * The function that will be called back when the fragment changes. */ - routeHandler: (fragment: string) => void; + routeHandler?: (fragment: string) => void; /** * The url root used to extract the fragment when using push state. @@ -1384,7 +1406,7 @@ interface DurandalRouteConfiguration { route?: string; routePattern?: RegExp; isActive?: KnockoutComputed; - nav:any; + nav: any; } interface DurandalRouteInstruction { @@ -1656,4 +1678,4 @@ interface DurandalRootRouter extends DurandalRouterBase { * Installs the router's custom ko binding handler. */ install(): void; -} \ No newline at end of file +} diff --git a/easeljs/easeljs-tests.ts b/easeljs/easeljs-tests.ts index 6c083da5cd..ff68b79d65 100644 --- a/easeljs/easeljs-tests.ts +++ b/easeljs/easeljs-tests.ts @@ -53,4 +53,16 @@ function test_graphics() { var myGraphics: createjs.Graphics; myGraphics.beginStroke("#F00").beginFill("#00F").drawRect(20, 20, 100, 50).draw(myContext2D); +} + +function colorMatrixTest() { + var shape = new createjs.Shape().set({ x: 100, y: 100 }); + shape.graphics.beginFill("#ff0000").drawCircle(0, 0, 50); + + var matrix = new createjs.ColorMatrix().adjustHue(180).adjustSaturation(100); + shape.filters = [ + new createjs.ColorMatrixFilter(matrix) + ]; + + shape.cache(-50, -50, 100, 100); } \ No newline at end of file diff --git a/easeljs/easeljs.d.ts b/easeljs/easeljs.d.ts index dd15630832..2c5be3aa34 100644 --- a/easeljs/easeljs.d.ts +++ b/easeljs/easeljs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for EaselJS 0.7.0 +// Type definitions for EaselJS 0.7.1 // Project: http://www.createjs.com/#!/EaselJS // Definitions by: Pedro Ferreira , Chris Smith // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -55,6 +55,8 @@ declare module createjs { // methods clone(): Bitmap; + set(props: Object): Bitmap; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, regX?: number, regY?: number): Bitmap; } /** @@ -73,6 +75,9 @@ declare module createjs { spriteSheet: SpriteSheet; text: string; + // methods + set(props: Object): BitmapText; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, regX?: number, regY?: number): BitmapText; } export class BlurFilter extends Filter { @@ -120,12 +125,8 @@ declare module createjs { clone(): ColorFilter; } - export class ColorMatrix implements Array { - constructor(brightness: number, contrast: number, saturation: number, hue: number); - - static DELTA_INDEX: number[]; - static IDENTITY_MATRIX: number[]; - static LENGTH: number; + export class ColorMatrix { + constructor(brightness?: number, contrast?: number, saturation?: number, hue?: number); // methods adjustBrightness(value: number): ColorMatrix; @@ -135,41 +136,17 @@ declare module createjs { adjustSaturation(value: number): ColorMatrix; clone(): ColorMatrix; concat(...matrix: number[]): ColorMatrix; - copyMatrix(...matrix: ColorMatrix[]): ColorMatrix; + concat(matrix: ColorMatrix): ColorMatrix; + copyMatrix(...matrix: number[]): ColorMatrix; + copyMatrix(matrix: ColorMatrix): ColorMatrix; reset(): ColorMatrix; toArray(): number[]; - - // implements Array interface start - concat(...items: ColorMatrix[]): number[]; - join(separator?: string): string; - pop(): number; - push(...items: number[]): number; - reverse(): number[]; - shift(): number; - slice(start: number, end?: number): number[]; - sort(compareFn?: (a: number, b: number) => number): number[]; - splice(start: number): number[]; - unshift(...items: number[]): number; - indexOf(searchElement: number, fromIndex?: number): number; - - lastIndexOf(searchElement: number, fromIndex?: number): number; - every(callbackfn: (value: number, index: number, array: number[]) => boolean, thisArg?: any): boolean; - some(callbackfn: (value: number, index: number, array: number[]) => boolean, thisArg?: any): boolean; - forEach(callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any): void; - map(callbackfn: (value: number, index: number, array: number[]) => ColorMatrix, thisArg?: any): ColorMatrix[]; - - filter(callbackfn: (value: number, index: number, array: number[]) => boolean, thisArg?: any): number[]; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: number[]) => number, initialValue?: number): number; - reduce(callbackfn: (previousValue: ColorMatrix, currentValue: number, currentIndex: number, array: number[]) => ColorMatrix, initialValue: ColorMatrix): ColorMatrix; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: number[]) => number, initialValue?: number): number; - reduceRight(callbackfn: (previousValue: ColorMatrix, currentValue: number, currentIndex: number, array: number[]) => ColorMatrix, initialValue: ColorMatrix): ColorMatrix; - length: number; - [n: number]: number; - // implements Array interface end + toString(): string; } export class ColorMatrixFilter extends Filter { constructor(matrix: number[]); + constructor(matrix: ColorMatrix); // methods clone(): ColorMatrixFilter; @@ -177,7 +154,7 @@ declare module createjs { export class Command { // methods - constructor(f: any, params: any, path: any); + constructor(f: any, params: any, path?: any); exec(scope: any): void; } @@ -187,6 +164,7 @@ declare module createjs { // properties children: DisplayObject[]; mouseChildren: boolean; + tickChildren: boolean; // methods addChild(...child: DisplayObject[]): DisplayObject; @@ -203,7 +181,9 @@ declare module createjs { removeAllChildren(): void; removeChild(...child: DisplayObject[]): boolean; removeChildAt(...index: number[]): boolean; + set(props: Object): Container; setChildIndex(child: DisplayObject, index: number): void; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, regX?: number, regY?: number): Container; sortChildren(sortFunction: (a: DisplayObject, b: DisplayObject) => number): void; swapChildren(child1: DisplayObject, child2: DisplayObject): void; swapChildrenAt(index1: number, index2: number): void; @@ -214,7 +194,7 @@ declare module createjs { // properties alpha: number; - cacheCanvas: HTMLCanvasElement; // HTMLCanvasElement or Object + cacheCanvas: any; // HTMLCanvasElement or Object cacheID: number; compositeOperation: string; cursor: string; @@ -238,6 +218,7 @@ declare module createjs { */ snapToPixel: boolean; static suppressCrossDomainErrors: boolean; + tickEnabled: boolean; visible: boolean; x: number; y: number; @@ -274,7 +255,8 @@ declare module createjs { // methods clone(): DisplayObject; // throw error - + set(props: Object): DOMElement; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, regX?: number, regY?: number): DOMElement; } @@ -425,6 +407,8 @@ declare module createjs { constructor(type: string, bubbles: boolean, cancelable: boolean, stageX: number, stageY: number, nativeEvent: NativeMouseEvent, pointerID: number, primary: boolean, rawX: number, rawY: number); // properties + localX: number; + localY: number; nativeEvent: NativeMouseEvent; pointerID: number; primary: boolean; @@ -432,7 +416,6 @@ declare module createjs { rawY: number; stageX: number; stageY: number; - target: DisplayObject; // methods clone(): MouseEvent; @@ -442,23 +425,27 @@ declare module createjs { addEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function; addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object; addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): Object; - on(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; - on(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function; - on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object; - on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): Object; - removeEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; - removeEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; - removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; - removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; + dispatchEvent(eventObj: Object, target?: Object): boolean; + dispatchEvent(eventObj: string, target?: Object): boolean; + dispatchEvent(eventObj: Event, target?: Object): boolean; + hasEventListener(type: string): boolean; off(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; off(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; off(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; off(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; + off(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + on(type: string, listener: (eventObj: Object) => boolean, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + on(type: string, listener: (eventObj: Object) => void, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; + on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; removeAllEventListeners(type?: string): void; - dispatchEvent(eventObj: string, target?: Object): boolean; - dispatchEvent(eventObj: Object, target?: Object): boolean; - dispatchEvent(eventObj: Event, target?: Object): boolean; - hasEventListener(type: string): boolean; + removeEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; + removeEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; + removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; + removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + toString(): string; + willTrigger(type: string): boolean; } @@ -555,6 +542,8 @@ declare module createjs { // methods clone(recursive?: boolean): Shape; + set(props: Object): Shape; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, regX?: number, regY?: number): Shape; } @@ -583,6 +572,8 @@ declare module createjs { gotoAndStop(frameOrAnimation: string): void; gotoAndStop(frameOrAnimation: number): void; play(): void; + set(props: Object): Sprite; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, regX?: number, regY?: number): Sprite; stop(): void; } @@ -619,6 +610,8 @@ declare module createjs { export class SpriteSheetBuilder extends EventDispatcher { + constructor(); + // properties maxHeight: number; maxWidth: number; @@ -634,9 +627,9 @@ declare module createjs { addMovieClip(source: MovieClip, sourceRect?: Rectangle, scale?: number): void; build(): SpriteSheet; buildAsync(timeSlice?: number): void; - clone(): DisplayObject; // throw error + clone(): void; // throw error stopAsync(): void; - toString(): string; + } @@ -660,7 +653,8 @@ declare module createjs { // properties autoClear: boolean; - canvas: HTMLCanvasElement; + canvas: any; // HTMLCanvasElement or Object + handleEvent: Function; mouseInBounds: boolean; mouseMoveOutside: boolean; mouseX: number; @@ -677,7 +671,6 @@ declare module createjs { clone(): Stage; enableDOMEvents(enable?: boolean): void; enableMouseOver(frequency?: number): void; - handleEvent(evt: Object): void; toDataURL(backgroundColor: string, mimeType: string): string; update(...arg: any[]): void; @@ -703,6 +696,8 @@ declare module createjs { getMeasuredHeight(): number; getMeasuredLineHeight(): number; getMeasuredWidth(): number; + set(props: Object): Text; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, regX?: number, regY?: number): Text; } export class Ticker { @@ -731,7 +726,6 @@ declare module createjs { static setFPS(value: number): void; static setInterval(interval: number): void; static setPaused(value: boolean): void; - static toString(): string; // EventDispatcher mixins static addEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; @@ -746,16 +740,19 @@ declare module createjs { static off(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; static off(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; static off(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; - static on(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; - static on(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function; - static on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object; - static on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): Object; + static off(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + static on(type: string, listener: (eventObj: Object) => boolean, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + static on(type: string, listener: (eventObj: Object) => void, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + static on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; + static on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; static removeAllEventListeners(type?: string): void; static removeEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; static removeEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; - + static removeEventListener(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + static toString(): string; + static willTrigger(type: string): boolean; } export class TickerEvent { diff --git a/easystarjs/easystarjs-tests.ts b/easystarjs/easystarjs-tests.ts new file mode 100755 index 0000000000..a63d4ea0f1 --- /dev/null +++ b/easystarjs/easystarjs-tests.ts @@ -0,0 +1,47 @@ +/// + +// For node.js compile using: tsc --module commonjs easystarjs-tests.ts +// then run using: node easystarjs-tests.js +import EasyStar = require('easystarjs'); + +var test = new EasyStar.js(); + +test.setGrid([ + [0, 0, 0, 1, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0] +]); +test.setAcceptableTiles([0]); +test.setIterationsPerCalculation(1000); +test.findPath(2, 0, 4, 4, function (path: EasyStar.Position[]) +{ + if (path == null) + { + console.log("No path found!"); + return; + } + for (var i = 0; i < path.length; i++) + { + var pos = path[i]; + console.log("%d, %d", pos.x, pos.y); + } +}); + +test.calculate(); + +/* +Should log: + +2, 0 +2, 1 +1, 1 +1, 2 +1, 3 +2, 3 +3, 3 +4, 3 +4, 4 + +*/ \ No newline at end of file diff --git a/easystarjs/easystarjs.d.ts b/easystarjs/easystarjs.d.ts new file mode 100755 index 0000000000..7640b1a8b8 --- /dev/null +++ b/easystarjs/easystarjs.d.ts @@ -0,0 +1,34 @@ +// Type definitions for EasyStar.js 0.1.6 +// Project: http://easystarjs.com/ +// Definitions by: Magnus Gustafsson +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/* +easystarjs.d.ts may be freely distributed under the MIT license. +*/ + +declare module "easystarjs" +{ + class js + { + new (): js; + setGrid(grid: number[][]): void; + setAcceptableTiles(tiles: number[]): void; + findPath(startX: number, startY: number, endX: number, endY: number, callback: (path: Position[]) => void): void; + calculate(): void; + setIterationsPerCalculation(iterations: number): void; + avoidAdditionalPoint(x: number, y: number): void; + stopAvoidingAdditionalPoint(x: number, y: number): void; + stopAvoidingAllAdditionalPoints(): void; + enableDiagonals(): void; + disableDiagonals(): void; + setTileCost(tileType: number, multiplicativeCost: number): void; + } + + interface Position + { + x: number; + y: number; + } +} + + \ No newline at end of file diff --git a/ember/ember.d.ts b/ember/ember.d.ts index 4657ac5cb3..80be5d04d9 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -57,7 +57,7 @@ interface String { w(): string[]; } -interface Array { +interface Array { constructor(arr: any[]); activate(): void; addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; @@ -346,6 +346,10 @@ declare module Ember { The call will be delayed until the DOM has become ready. **/ ready: Function; + /** + Application's router. + **/ + Router: Router; } /** This module implements Observer-friendly Array-like behavior. This mixin is picked up by the @@ -1569,8 +1573,13 @@ declare module Ember { static metaForProperty(key: string): {}; static isClass: boolean; static isMethod: boolean; + map(callback: Function): Router; + } + class RouterDSL { + resource(name: string, options?: {}, callback?: Function): void; + resource(name: string, callback: Function): void; + route(name: string, options?: {}): void; } - var RouterDSL: Function; var SHIM_ES5: boolean; var STRINGS: boolean; class Select extends View { @@ -2261,7 +2270,7 @@ declare module Em { class RenderBuffer extends Ember.RenderBuffer { } class Route extends Ember.Route { } class Router extends Ember.Router { } - var RouterDSL: typeof Ember.RouterDSL; + class RouterDSL extends Ember.RouterDSL { } var SHIM_ES5: typeof Ember.SHIM_ES5; var STRINGS: typeof Ember.STRINGS; class Select extends Ember.Select { } diff --git a/es6-promises/es6-promises.d.ts b/es6-promises/es6-promises.d.ts index a44355233c..a50cd1fc64 100644 --- a/es6-promises/es6-promises.d.ts +++ b/es6-promises/es6-promises.d.ts @@ -5,10 +5,10 @@ interface Thenable { - then(onFulfill: (value: R) => Thenable, onReject: (error: any) => Thenable): Thenable; - then(onFulfill: (value: R) => Thenable, onReject?: (error: any) => U): Thenable; - then(onFulfill: (value: R) => U, onReject: (error: any) => Thenable): Thenable; - then(onFulfill?: (value: R) => U, onReject?: (error: any) => U): Thenable; + then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled: (value: R) => Thenable, onRejected?: (error: any) => U): Thenable; + then(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable; } @@ -130,4 +130,4 @@ declare module Promise { * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. */ function race(promises: Promise[]): Promise; -} \ No newline at end of file +} diff --git a/expect.js/expect.js.d.ts b/expect.js/expect.js.d.ts index e19f769b65..64c5871b07 100644 --- a/expect.js/expect.js.d.ts +++ b/expect.js/expect.js.d.ts @@ -1,4 +1,4 @@ -// Type definitions for expect.js 0.2.0 +// Type definitions for expect.js 0.2.0 // Project: https://github.com/LearnBoost/expect.js // Definitions by: Teppei Sato // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 4799dc0dda..5a1ba31b7e 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -1,3 +1,8 @@ +// Type definitions for express-validator +// Project: https://github.com/ctavan/express-validator +// Definitions by: Nathan Ridley +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + declare module ExpressValidator { export interface ValidationError { msg: string; diff --git a/express/express.d.ts b/express/express.d.ts index b97888998f..243aa41d4d 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -122,6 +122,10 @@ declare module "express" { del(name: string, ...handlers: RequestFunction[]): T; del(name: RegExp, ...handlers: RequestFunction[]): T; + + patch(name: string, ...handlers: RequestFunction[]): T; + + patch(name: RegExp, ...handlers: RequestFunction[]): T; } export class Router implements IRouter { @@ -152,6 +156,10 @@ declare module "express" { del(name: string, ...handlers: RequestFunction[]): Router; del(name: RegExp, ...handlers: RequestFunction[]): Router; + + patch(name: string, ...handlers: RequestFunction[]): Router; + + patch(name: RegExp, ...handlers: RequestFunction[]): Router; } interface Handler { @@ -1451,6 +1459,8 @@ declare module "express" { * @param callback or username * @param realm */ + export function basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Handler; + export function basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Handler; export function basicAuth(user: string, pass: string, realm?: string): Handler; diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index 0982329ee0..80087caa6c 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -1,6 +1,7 @@ // Type definitions for FabricJS // Project: http://fabricjs.com/ // Definitions by: Oliver Klemencic +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped /* USAGE diff --git a/filesystem/filesystem.d.ts b/filesystem/filesystem.d.ts index 54cf27b1f6..d3447f162f 100644 --- a/filesystem/filesystem.d.ts +++ b/filesystem/filesystem.d.ts @@ -1,4 +1,4 @@ -// Type Definitions for File API: Directories and System (File System API) +// Type Definitions for File System API // Project: http://www.w3.org/TR/file-system-api/ // Definitions by: Kon // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/firebase/firebase-tests.ts.tscparams b/firebase/firebase-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/firebase/firebase-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/firebase/firebase.d.ts b/firebase/firebase.d.ts index 901ad87baa..bac32fbc63 100644 --- a/firebase/firebase.d.ts +++ b/firebase/firebase.d.ts @@ -1,5 +1,5 @@ // Type definitions for Firebase API -// Project: https://www.firebase.com/docs/javascript/firebase/index.html +// Project: https://www.firebase.com/docs/javascript/firebase // Definitions by: Vincent Botone // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -53,7 +53,7 @@ declare class Firebase implements IFirebaseQuery { toString(): string; set(value: any, onComplete?: (error: any) => void): void; update(value: any, onComplete?: (error: any) => void): void; - remove(onComplete?: (error: any) => void); + remove(onComplete?: (error: any) => void): void; push(value: any, onComplete?: (error: any) => void): Firebase; setWithPriority(value: any, priority: string, onComplete?: (error: any) => void): void; setWithPriority(value: any, priority: number, onComplete?: (error: any) => void): void; diff --git a/firebase/firebase.d.ts.tscparams b/firebase/firebase.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/firebase/firebase.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/flight/flight.d.ts b/flight/flight.d.ts index a56981b1ca..19c8528df2 100644 --- a/flight/flight.d.ts +++ b/flight/flight.d.ts @@ -1,10 +1,10 @@ -/// - // Type definitions for Flight 1.1.1 // Project: http://flightjs.github.com/flight/ // Definitions by: Jonathan Hedrén // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module Flight { export interface Base { @@ -235,4 +235,4 @@ declare module Flight { } declare var DEBUG: Flight.DebugStatic; -declare var flight: Flight.FlightStatic; \ No newline at end of file +declare var flight: Flight.FlightStatic; diff --git a/ftdomdelegate/ftdomdelegate-tests.ts b/ftdomdelegate/ftdomdelegate-tests.ts new file mode 100644 index 0000000000..55dc7a737a --- /dev/null +++ b/ftdomdelegate/ftdomdelegate-tests.ts @@ -0,0 +1,15 @@ +/// + +window.addEventListener('load', function() { + var delegate = new Delegate(document.body); + delegate.on('click', 'button', function(event) { + // Do some things + } +); + + // Listen to all touch move + // events that reach the body + delegate.on('touchmove', function(event) { + // Do some other things + }); +}, false); \ No newline at end of file diff --git a/ftdomdelegate/ftdomdelegate.d.ts b/ftdomdelegate/ftdomdelegate.d.ts new file mode 100644 index 0000000000..04766bd26e --- /dev/null +++ b/ftdomdelegate/ftdomdelegate.d.ts @@ -0,0 +1,22 @@ +// Type definitions for ftdomdelegate +// Project: https://github.com/ftlabs/ftdomdelegate +// Definitions by: Christian Holm Nielsen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class Delegate +{ + constructor(element: HTMLElement); + + on(eventType: string, selector: string, handler : (event: Event, targetElement: Element) => void, eventData? : any) : void; + + on(eventType: string, selector: (element: Element) => boolean, handler : (event: Event, targetElement: Element) => void, eventData? : any) : void; + + on(eventType: string, handler:(event: Event, targetElement: Element) => void, eventData? : any) : void; + + off(eventType? : string, selector? : string, handler? : (event: Event, targetElement: Element) => void) : void; + off(eventType? : string, selector?: (element: Element) => boolean, handler? : (event: Event, targetElement: Element) => void) : void; + + root(element? : Element) : void; + + destroy() : void; +} \ No newline at end of file diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts index ec24c4e7fe..fd1303f69e 100644 --- a/fullCalendar/fullCalendar.d.ts +++ b/fullCalendar/fullCalendar.d.ts @@ -1,5 +1,5 @@ // Type definitions for FullCalendar 1.6.1 -// Project: http://arshaw.com/fullcalendar/ (http://arshaw.com/fullcalendar/) +// Project: http://arshaw.com/fullcalendar/ // Definitions by: Neil Stalker // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -310,4 +310,4 @@ interface JQuery { interface JQueryStatic { fullCalendar: FullCalendar.Calendar; -} \ No newline at end of file +} diff --git a/gamepad/gamepad-tests.ts b/gamepad/gamepad-tests.ts index e6ca9d272a..5d82c33ecd 100644 --- a/gamepad/gamepad-tests.ts +++ b/gamepad/gamepad-tests.ts @@ -38,7 +38,7 @@ console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); }, false); - var requestAnimationFrame = window.requestAnimationFrame || window["mozRequestAnimationFrame"]; + var requestAnimationFrame = window.requestAnimationFrame || (window).mozRequestAnimationFrame; var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads; if(getGamepads){ function runAnimation() diff --git a/gapi.pagespeedonline/gapi.pagespeedonline.d.ts b/gapi.pagespeedonline/gapi.pagespeedonline.d.ts index 4fe23abd28..44665784e7 100644 --- a/gapi.pagespeedonline/gapi.pagespeedonline.d.ts +++ b/gapi.pagespeedonline/gapi.pagespeedonline.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Page Speed Online Api +// Type definitions for Google Page Speed Online Api // Project: https://developers.google.com/speed/pagespeed/ // Definitions by: Frank M // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/gapi.youtube/gapi.youtube.d.ts b/gapi.youtube/gapi.youtube.d.ts index 3d0930787f..ee554e4398 100644 --- a/gapi.youtube/gapi.youtube.d.ts +++ b/gapi.youtube/gapi.youtube.d.ts @@ -1,4 +1,4 @@ -// Type definitions for YouTube Data API v3 +// Type definitions for YouTube Data API v3 // Project: https://developers.google.com/youtube/v3/ // Definitions by: Frank M // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/google.feeds/google.feed.api.d.ts b/google.feeds/google.feed.api.d.ts index 0db17b3ca0..4db5a2f75a 100644 --- a/google.feeds/google.feed.api.d.ts +++ b/google.feeds/google.feed.api.d.ts @@ -1,6 +1,7 @@ -//Project Google Feed Apis +// Type definitions for Google Feed Apis // Project: https://developers.google.com/feed/ -// Definitions by: https://github.com/RodneyJT +// Definitions by: RodneyJT +// Definitions: https://github.com/borisyankov/DefinitelyTyped declare module google.feeds { export class feed { diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index a08f739976..553c8e6549 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -1,3 +1,8 @@ +// Type definitions for Google Visualisation Apis +// Project: https://developers.google.com/chart/ +// Definitions by: Dan Ludwig +// Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module google { function load(visualization: string, version: string, packages: any): void; @@ -71,6 +76,7 @@ declare module google { addRows(array: any[]): number; getFilteredRows(filters: DataTableCellFilter[]): number[]; getFormattedValue(rowIndex: number, columnIndex: number): string; + getValue(rowIndex: number, columnIndex: number): any; getNumberOfColumns(): number; getNumberOfRows(): number; removeRow(rowIndex: number): void; @@ -468,4 +474,4 @@ declare module google { //#endregion } -} \ No newline at end of file +} diff --git a/googlemaps.infobubble/google.maps.infobubble-tests.ts b/googlemaps.infobubble/google.maps.infobubble-tests.ts new file mode 100644 index 0000000000..61f6b7ac5c --- /dev/null +++ b/googlemaps.infobubble/google.maps.infobubble-tests.ts @@ -0,0 +1,33 @@ +/// +/// + +function test_options() { + var options: google.maps.infobubble.InfoBubbleOptions; + options = {}; + + options.arrowPosition = 50; + options.arrowSize = 15; + options.arrowStyle = 0; + options.backgroundColor = "#000"; + options.borderColor = "#000"; + options.borderRadius = 5; + options.borderWidth = 1; + options.disableAnimation = false; + options.disableAutoPan = false; + options.maxHeight = 300; + options.maxWidth = 300; + options.minHeight = 300; + options.minWidth = 300; + options.padding = 10; + options.shadowStyle = 1; +} + +function test_bubble() { + var map: google.maps.Map; + var marker: google.maps.Marker; + var bubble: google.maps.infobubble.InfoBubble; + + bubble.open(map, marker); + var isOpen = bubble.isOpen(); + bubble.close(); +} \ No newline at end of file diff --git a/googlemaps.infobubble/google.maps.infobubble.d.ts b/googlemaps.infobubble/google.maps.infobubble.d.ts new file mode 100644 index 0000000000..f65dd11146 --- /dev/null +++ b/googlemaps.infobubble/google.maps.infobubble.d.ts @@ -0,0 +1,103 @@ +/// + +// Type definitions for CSS3 InfoBubble with tabs for Google Maps API V3 +// Project: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/src/ +// Definitions by: Johan Nilsson https://github.com/Dashue +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * @name CSS3 InfoBubble with tabs for Google Maps API V3 + * @version 0.8 + * @author Luke Mahe + * @fileoverview + * This library is a CSS Infobubble with tabs. It uses css3 rounded corners and + * drop shadows and animations. It also allows tabs + */ + +/* +The MIT License + +Copyright (c) 2014 https://github.com/Dashue + +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: + +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. +*/ + +declare module google.maps.infobubble { + + export interface InfoBubble { + /** + * Closes the infobubble + */ + close(): void; + + /** + * Checks if the infobubble is currently open + */ + isOpen(): boolean; + + /** + * Opens the infobubble + * @map The google map object + * @marker The marker used for anchoring the infobubble to + */ + open(map: google.maps.Map, marker: google.maps.Marker) : void; + } + + export interface InfoBubbleOptions { + + /** + * Percentage from the bottom left corner of the infobubble + */ + arrowPosition?: number; + + arrowSize?: number; + + /** + * 0: Middle, 1: Left, 2: Right + */ + arrowStyle?: number; + + backgroundColor?: string; + + borderColor?: string; + + borderRadius?: number; + + borderWidth?: number; + + disableAnimation?: boolean; + + disableAutoPan?: boolean; + + maxHeight?: number; + + maxWidth?: number; + + minHeight?: number; + + minWidth?: number; + + padding?: number; + + /** + * 0: None, 1: Right, 2: Under + */ + shadowStyle?: number; + } +} \ No newline at end of file diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 3be446e19d..4589e09f0a 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1,3 +1,8 @@ +// Type definitions for Google Geolocation 0.4.8 +// Project: https://developers.google.com/maps/ +// Definitions by: Folia A/S +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /* The MIT License @@ -108,7 +113,8 @@ declare module google.maps { scaleControl?: boolean; scaleControlOptions?: ScaleControlOptions; scrollwheel?: boolean; - streetView?: boolean; + streetView?: StreetViewPanorama; + streetViewControl?: boolean; streetViewControlOptions?: StreetViewControlOptions; styles?: MapTypeStyle[]; tilt?: number; @@ -1242,7 +1248,7 @@ declare module google.maps { /***** Geometry Library *****/ export module geometry { export class encoding { - static decodePath(encodedPath: string): LatLng; + static decodePath(encodedPath: string): LatLng[]; static encodePath(path: any[]): string; } diff --git a/greensock/greensock.d.ts b/greensock/greensock.d.ts index ce0a2b6e1d..455b28052a 100644 --- a/greensock/greensock.d.ts +++ b/greensock/greensock.d.ts @@ -1,4 +1,8 @@ -// GreenSock Animation Platform (GSAP) - http://www.greensock.com/get-started-js/ +// Type definitions for GreenSock Animation Platform 1.1 +// Project: http://www.greensock.com/get-started-js/ +// Definitions by: Robert S +// Definitions: https://github.com/borisyankov/DefinitelyTyped + // JavaScript Docs http://api.greensock.com/js/ // Version 1.1 (TypeScript 0.9) diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index f36b74d764..853cac370b 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -42,9 +42,20 @@ exports = (grunt: IGrunt) => { var valid = false; valid = valid && options.sourceRoot === "default"; valid = valid && currenttask.data.repeat > 0; - return valid; + + var done = this.async(); + done(); }); + grunt.registerMultiTask('task-1', "", function() { + var done = this.async(); + done(new Error('nope')); + }); + + grunt.registerMultiTask('task-2', "", function() { + var done = this.async(); + done(false); + }); // util methods var testOneArg = (a: number) => a * 2; @@ -61,4 +72,4 @@ exports = (grunt: IGrunt) => { fileMaps.length; fileMaps[0].src.length; fileMaps[0].dest; -}; \ No newline at end of file +}; diff --git a/gruntjs/gruntjs.d.ts b/gruntjs/gruntjs.d.ts index 99eadf435b..cfe2825e41 100644 --- a/gruntjs/gruntjs.d.ts +++ b/gruntjs/gruntjs.d.ts @@ -816,9 +816,10 @@ declare module grunt { * Either false or an Error object may be passed to the done function * to instruct Grunt that the task has failed. */ - done(success: boolean): void; - done(error: Error): void; - done(result: any): void; + (success: boolean): void; + (error: Error): void; + (result: any): void; + (): void; } /** @@ -1155,7 +1156,13 @@ declare module grunt { /** * Additional options for the Node.js child_process spawn method. */ - opts?: ISpawnOptions + opts?: { + cwd?: string + stdio?: any + custom?: any + env?: any + detached?: boolean + } /** * If this value is set and an error occurs, it will be used as the value diff --git a/handlebars/handlebars.d.ts b/handlebars/handlebars.d.ts index 28158031e5..ceff786637 100644 --- a/handlebars/handlebars.d.ts +++ b/handlebars/handlebars.d.ts @@ -16,7 +16,7 @@ interface HandlebarsStatic { parse(input: string): boolean; logger: Logger; log(level: number, obj: any): void; - compile(input: any, options?: any): (context: any, options?: any) => string; + compile(input: any, options?: any): (context?: any, options?: any) => string; Logger: typeof Logger; } diff --git a/highland/highland-tests.ts b/highland/highland-tests.ts new file mode 100644 index 0000000000..7acc6c50b9 --- /dev/null +++ b/highland/highland-tests.ts @@ -0,0 +1,396 @@ +/// + +// Note: try to maintain the ordering and separators + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var _: HighlandStatic; + +var obj: Object; +var err: Error; +var bool: boolean; +var num: number; +var str: string; +var x: any; +var f: Function; +var fn: Function; +var func: Function; +var arr: any[]; +var exp: RegExp; +var anyArr: any[]; +var strArr: string[]; +var numArr: string[]; +var funcArr: Function[]; + +var readable: ReadableStream; +var writable: WritableStream; +var emitter: NodeEventEmitter; + +// - - - - - - - - - - - - - - - - - + +var value: any; +var reason: any; +var insanity: any; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numStream: Highland.Stream; +var strStream: Highland.Stream; +var anyStream: Highland.Stream; +var boolStream: Highland.Stream; +var objStream: Highland.Stream; +var voidStream: Highland.Stream; + +// - - - - - - - - - - - - - - - - - + +var anyArrStream: Highland.Stream; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +interface Foo { + foo(): string; +} +interface Bar { + bar(): string; +} + +interface StrFooArrMap { + [key:string]: Foo[]; +} + +interface StrBarArrMap { + [key:string]: Bar[]; +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var foo: Foo; +var bar: Bar; + +var fooArr: Foo[]; +var barArr: Bar[]; + +var fooStream: Highland.Stream; +var barStream: Highland.Stream; + +var fooArrStream: Highland.Stream; +var barArrStream: Highland.Stream; + +var fooStreamArr: Highland.Stream[]; +var barStreamArr: Highland.Stream[]; + +var fooStreamArr: Highland.Stream[]; +var barStreamArr: Highland.Stream[]; + +var strFooArrMapStream: Highland.Stream; +var strBarArrMapStream: Highland.Stream; + +var fooThen: Highland.Thenable; +var barThen: Highland.Thenable; + +var fooArrThen: Highland.Thenable; +var barArrThen: Highland.Thenable; + +var fooThenArr: Highland.Thenable[]; +var barThenArr: Highland.Thenable[]; + +var fooStreamThen: Highland.Thenable>; +var barStreamThen: Highland.Thenable>; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// curries +var objCurStr: (obj: Object) => string; +var objCurObj: (obj: Object) => Object; +var objCurAny: (obj: Object) => any; +var numCurNum: (num: number) => number; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var steamError: Highland.StreamError; +var streamRedirect: Highland.StreamRedirect; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +steamError = new Highland.StreamError(err); +err = steamError.error; + +streamRedirect = new Highland.StreamRedirect(fooStream); +fooStream = streamRedirect.to; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// top-level module + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream = _(); +fooStream = _(fooArr); +fooStream = _((push, next) => { + push(null, foo); + push(err); + next(); +}); + +fooStream = _(fooStream); +fooStream = _(readable); +fooStream = _(emitter); + +fooStream = _(fooStreamThen); +fooStream = _(fooArrThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +obj = _.nil; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +f = _.curry(fn, foo); +f = _.curry(fn, foo, bar); + +f = _.ncurry(num, fn, foo); +f = _.ncurry(num, fn, foo, bar); + +f = _.partial(f, foo); +f = _.partial(f, foo, bar); + +f = _.flip(fn, foo); +f = _.flip(fn, foo, bar); + +f = _.compose(f); +f = _.compose(f, f); + +f = _.seq(f); +f = _.seq(f, f); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +bool = _.isStream(x); +bool = _.isStream(fooStream); + +bool = _.isStreamError(x); +bool = _.isStreamError(fooStream); + +bool = _.isStreamRedirect(x); +bool = _.isStreamRedirect(fooStream); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +anyStream = _.values(obj); +fooStream = _.values(fooArr); + +strStream = _.keys(obj); + +anyArrStream = _.pairs(obj); +anyArrStream = _.pairs(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +obj = _.extend(obj, obj); + +objCurObj = _.extend(obj); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +x = _.get(str, obj); + +objCurObj = _.get(str); + +obj = _.set(str, foo, obj); + +objCurAny = _.set(str, foo); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +_.log(str); +_.log(str, num, foo); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +f = _.wrapCallback(func); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +num = _.add(num, num); + +numCurNum = _.add(num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// instance methods + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream.pause(); +fooStream.resume(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream.end(); + +fooStream = fooStream.pipe(fooStream); +barStream = fooStream.pipe(barStream); + +fooStream.destroy(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barStream = fooStream.consume((err: Error, x: Foo, push: (err: Error, value?: Bar) => void, next: () => void) => { + push(err); + push(null, bar); + next(); +}); + +barStream = fooStream.consume((err, x, push, next) => { + push(err); + push(null, bar); + next(); +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream.pull((err: Error, x: Foo) => { + +}); + +fooStream.pull((err, x) => { + +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +bool = fooStream.write(foo); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream = fooStream.fork(); + +fooStream = fooStream.observe(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream = fooStream.errors((err: Error, push: (e: Error, x?: Foo) => void) => { + push(err); + push(null, x); + push(null, foo); +}); + +fooStream = fooStream.errors((err, push) => { + push(err); + push(null, x); + push(null, foo); +}); + +fooStream = fooStream.stopOnError((e: Error) => { + +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream.each((x: Foo) => { + +}); + +fooStream.apply(func); + +fooStream.toArray((arr: Foo[]) => { + +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barStream = fooStream.map((x: Foo) => { + return bar; +}); + +barStream = fooStream.flatMap((x: Foo) => { + return barStream; +}); + +barStream = fooStream.flatMap((x: Foo) => { + return bar; +}); + +barStream = fooStream.pluck(str); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream = fooStream.filter((x: Foo) => { + return bool; +}); + +fooStream = fooStream.flatFilter((x: Foo) => { + return boolStream; +}); + +fooStream = fooStream.find((x: Foo) => { + return bool; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +strFooArrMapStream = fooStream.group((x: Foo) => { + return str; +}); +strFooArrMapStream = fooStream.group(str); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream = fooStream.compact(); + +fooStream = fooStream.where(obj); + +fooStream = fooStream.zip(fooStream); +fooStream = fooStream.zip([foo, foo]); + +fooStream = fooStream.take(num); + +fooStream = fooStream.last(); + +barStream = fooStream.sequence(); + +barStream = fooStream.series(); + +barStream = fooStream.flatten(); + +fooStream = fooStream.parallel(num); + +fooStream = fooStream.otherwise(fooStream); + +fooStream = fooStream.append(foo); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barStream = fooStream.reduce(bar, (memo: Bar, x: Foo) => { + return memo; +}); + +barStream = fooStream.reduce1(bar, (memo: Bar, x: Foo) => { + return memo; +}); + +fooArrStream = fooStream.collect(); + +barStream = fooStream.scan(bar, (memo: Bar, x: Foo) => { + return memo; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream = fooStream.concat(fooStream); + +fooStream = fooStream.concat(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barStream = fooStream.invoke(str, anyArr); + +fooStream = fooStream.throttle(num); + +fooStream = fooStream.debounce(num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooStream = fooStream.latest(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/highland/highland.d.ts b/highland/highland.d.ts new file mode 100644 index 0000000000..252c617eaa --- /dev/null +++ b/highland/highland.d.ts @@ -0,0 +1,954 @@ +// Type definitions for Highland 1.14.0 +// Project: http://highlandjs.org/ +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +// TODO export the top-level functions + +// TODO figure out curry arguments +// TODO use externalised Thenable +// TODO use externalised Readable/Writable (not node's) + +/** + * Highland: the high-level streams library + * + * Highland may be freely distributed under the Apache 2.0 license. + * http://github.com/caolan/highland + * Copyright (c) Caolan McMahon + * + */ + +interface HighlandStatic { + /** + * The Stream constructor, accepts an array of values or a generator function + * as an optional argument. This is typically the entry point to the Highland + * APIs, providing a convenient way of chaining calls together. + * + * **Arrays -** Streams created from Arrays will emit each value of the Array + * and then emit a [nil](#nil) value to signal the end of the Stream. + * + * **Generators -** These are functions which provide values for the Stream. + * They are lazy and can be infinite, they can also be asynchronous (for + * example, making a HTTP request). You emit values on the Stream by calling + * `push(err, val)`, much like a standard Node.js callback. You call `next()` + * to signal you've finished processing the current data. If the Stream is + * still being consumed the generator function will then be called again. + * + * You can also redirect a generator Stream by passing a new source Stream + * to read from to next. For example: `next(other_stream)` - then any subsequent + * calls will be made to the new source. + * + * **Node Readable Stream -** Pass in a Node Readable Stream object to wrap + * it with the Highland API. Reading from the resulting Highland Stream will + * begin piping the data from the Node Stream to the Highland Stream. + * + * **EventEmitter / jQuery Elements -** Pass in both an event name and an + * event emitter as the two arguments to the constructor and the first + * argument emitted to the event handler will be written to the new Stream. + * + * **Promise -** Accepts an ES6 / jQuery style promise and returns a + * Highland Stream which will emit a single value (or an error). + * + * @id _(source) + * @section Streams + * @name _(source) + * @param {Array | Function | Readable Stream | Promise} source - (optional) source to take values from from + * @api public + */ + (): Highland.Stream; + (xs: R[]): Highland.Stream; + (xs: (push: (err: Error, x?: R) => void, next: () => void) => void): Highland.Stream; + + (xs: Highland.Stream): Highland.Stream; + (xs: ReadableStream): Highland.Stream; + (xs: NodeEventEmitter): Highland.Stream; + + // moar (promise for everything?) + (xs: Highland.Thenable>): Highland.Stream; + (xs: Highland.Thenable): Highland.Stream; + + /** + * The end of stream marker. This is sent along the data channel of a Stream + * to tell consumers that the Stream has ended. See the following map code for + * an example of detecting the end of a Stream: + * + * @id nil + * @section Streams + * @name _.nil + * @api public + */ + nil: Highland.Nil; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Transforms a function with specific arity (all arguments must be + * defined) in a way that it can be called as a chain of functions until + * the arguments list is saturated. + * + * This function is not itself curryable. + * + * @id curry + * @name curry(fn, [*arguments]) + * @section Functions + * @param {Function} fn - the function to curry + * @param args.. - any number of arguments to pre-apply to the function + * @returns Function + * @api public + */ + curry(fn: Function, ...args: any[]): Function; + + /** + * Same as `curry` but with a specific number of arguments. This can be + * useful when functions do not explicitly define all its parameters. + * + * This function is not itself curryable. + * + * @id ncurry + * @name ncurry(n, fn, [args...]) + * @section Functions + * @param {Number} n - the number of arguments to wait for before apply fn + * @param {Function} fn - the function to curry + * @param args... - any number of arguments to pre-apply to the function + * @returns Function + * @api public + */ + ncurry(n: number, fn: Function, ...args: any[]): Function; + + /** + * Partially applies the function (regardless of whether it has had curry + * called on it). This will always postpone execution until at least the next + * call of the partially applied function. + * + * @id partial + * @name partial(fn, args...) + * @section Functions + * @param {Function} fn - function to partial apply + * @param args... - the arguments to apply to the function + * @api public + */ + partial(f: Function, ...args: any[]): Function; + + /** + * Evaluates the function `fn` with the argument positions swapped. Only + * works with functions that accept two arguments. + * + * @id flip + * @name flip(fn, [x, y]) + * @section Functions + * @param {Function} f - function to flip argument application for + * @param x - parameter to apply to the right hand side of f + * @param y - parameter to apply to the left hand side of f + * @api public + */ + flip(fn: Function, ...args: any[]): Function; + + /** + * Creates a composite function, which is the application of function1 to + * the results of function2. You can pass an arbitrary number of arguments + * and have them composed. This means you can't partially apply the compose + * function itself. + * + * @id compose + * @name compose(fn1, fn2, ...) + * @section Functions + * @api public + */ + compose(...functions: Function[]): Function; + + /** + * The reversed version of compose. Where arguments are in the order of + * application. + * + * @id seq + * @name seq(fn1, fn2, ...) + * @section Functions + * @api public + */ + seq(...functions: Function[]): Function; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Returns true if `x` is a Highland Stream. + * + * @id isStream + * @section Streams + * @name _.isStream(x) + * @param x - the object to test + * @api public + */ + isStream(x: any): boolean; + + isStreamError(x: any): boolean; + + isStreamRedirect(x: any): boolean; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Returns values from an Object as a Stream. Reads properties + * lazily, so if you don't read from all keys on an object, not + * all properties will be read from (may have an effect where getters + * are used). + * + * @id values + * @section Objects + * @name _.values(obj) + * @param {Object} obj - the object to return values from + * @api public + */ + values(obj: Object): Highland.Stream; + + /** + * Returns keys from an Object as a Stream. + * + * @id keys + * @section Objects + * @name _.keys(obj) + * @param {Object} obj - the object to return keys from + * @api public + */ + keys(obj: Object): Highland.Stream; + + /** + * Returns key/value pairs for an Object as a Stream. Reads properties + * lazily, so if you don't read from all keys on an object, not + * all properties will be read from (may have an effect where getters + * are used). + * + * @id pairs + * @section Objects + * @name _.pairs(obj) + * @param {Object} obj - the object to return key/value pairs from + * @api public + */ + pairs(obj: Object): Highland.Stream; + + pairs(obj: any[]): Highland.Stream; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Extends one object with the properties of another. **Note:** The + * arguments are in the reverse order of other libraries such as + * underscore. This is so it follows the convention of other functions in + * this library and so you can more meaningfully partially apply it. + * + * @id extend + * @section Objects + * @name _.extend(a, b) + * @param {Object} a - the properties to extend b with + * @param {Object} b - the original object to extend + * @api public + */ + extend(extensions: Object, target: Object): Object; + + extend(target: Object): (extensions: Object) => Object; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Returns a property from an object. + * + * @id get + * @section Objects + * @name _.get(prop, obj) + * @param {String} prop - the property to return + * @param {Object} obj - the object to read properties from + * @api public + */ + get(prop: string, obj: Object): string; + + get(prop: string): (obj: Object) => Object; + + /** + * Updates a property on an object, returning the updated object. + * + * @id set + * @section Objects + * @name _.set(prop, value, obj) + * @param {String} prop - the property to return + * @param value - the value to set the property to + * @param {Object} obj - the object to set properties on + * @api public + */ + set(prop: string, val: any, obj: Object): Object; + + set(prop: string, val: any): (obj: Object) => Object; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Logs values to the console, a simple wrapper around `console.log` that + * it suitable for passing to other functions by reference without having to + * call `bind`. + * + * @id log + * @section Utils + * @name _.log(args..) + * @api public + */ + log(x: any, ...args: any[]): void; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Wraps a node-style async function which accepts a callback, transforming + * it to a function which accepts the same arguments minus the callback and + * returns a Highland Stream instead. Only the first argument to the + * callback (or an error) will be pushed onto the Stream. + * + * @id wrapCallback + * @section Utils + * @name _.wrapCallback(f) + * @param {Function} f - the node-style function to wrap + * @api public + */ + wrapCallback(f: Function): Function; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Add two values. Can be partially applied. + * + * @id add + * @section Operators + * @name _.add(a, b) + * @api public + */ + add(a: number, b: number): number; + + add(a: number): (b: number) => number; +} + +declare module Highland { + + interface Thenable { + then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled: (value: R) => Thenable, onRejected?: (error: any) => U): Thenable; + then(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable; + } + // hacky unique + // TODO do we need this? + interface Nil { + Highland_NIL: Nil; + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Used as an Error marker when writing to a Stream's incoming buffer + */ + // TODO is this public? + class StreamError { + constructor(err: Error); + + error: Error; + } + + /** + * Used as a Redirect marker when writing to a Stream's incoming buffer + */ + // TODO is this public? + class StreamRedirect { + constructor(to: Stream) + + to: Stream; + } + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Actual Stream constructor wrapped the the main exported function + */ + interface Stream extends NodeEventEmitter { + + /** + * Pauses the stream. All Highland Streams start in the paused state. + * + * @id pause + * @section Streams + * @name Stream.pause() + * @api public + */ + pause(): void; + + /** + * Resumes a paused Stream. This will either read from the Stream's incoming + * buffer or request more data from an upstream source. + * + * @id resume + * @section Streams + * @name Stream.resume() + * @api public + */ + resume(): void; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Ends a Stream. This is the same as sending a [nil](#nil) value as data. + * You shouldn't need to call this directly, rather it will be called by + * any [Node Readable Streams](http://nodejs.org/api/stream.html#stream_class_stream_readable) + * you pipe in. + * + * @id end + * @section Streams + * @name Stream.end() + * @api public + */ + end(): void; + + /** + * Pipes a Highland Stream to a [Node Writable Stream](http://nodejs.org/api/stream.html#stream_class_stream_writable) + * (Highland Streams are also Node Writable Streams). This will pull all the + * data from the source Highland Stream and write it to the destination, + * automatically managing flow so that the destination is not overwhelmed + * by a fast source. + * + * This function returns the destination so you can chain together pipe calls. + * + * @id pipe + * @section Streams + * @name Stream.pipe(dest) + * @param {Writable Stream} dest - the destination to write all data to + * @api public + */ + pipe(dest: Stream): Stream; + pipe(dest: ReadWriteStream): Stream; + pipe(dest: WritableStream): void; + + /** + * Destroys a stream by unlinking it from any consumers and sources. This will + * stop all consumers from receiving events from this stream and removes this + * stream as a consumer of any source stream. + * + * This function calls end() on the stream and unlinks it from any piped-to streams. + * + * @id pipe + * @section Streams + * @name Stream.destroy() + * @api public + */ + destroy(): void; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Consumes values from a Stream (once resumed) and returns a new Stream for + * you to optionally push values onto using the provided push / next functions. + * + * This function forms the basis of many higher-level Stream operations. + * It will not cause a paused stream to immediately resume, but behaves more + * like a 'through' stream, handling values as they are read. + * + * @id consume + * @section Streams + * @name Stream.consume(f) + * @param {Function} f - the function to handle errors and values + * @api public + */ + consume(f: (err: Error, x: R, push: (err: Error, value?: U) => void, next: () => void) => void): Stream; + + /** + * Consumes a single item from the Stream. Unlike consume, this function will + * not provide a new stream for you to push values onto, and it will unsubscribe + * as soon as it has a single error, value or nil from the source. + * + * You probably won't need to use this directly, but it is used internally by + * some functions in the Highland library. + * + * @id pull + * @section Streams + * @name Stream.pull(f) + * @param {Function} f - the function to handle data + * @api public + */ + pull(f: (err: Error, x: R) => void): void; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Writes a value to the Stream. If the Stream is paused it will go into the + * Stream's incoming buffer, otherwise it will be immediately processed and + * sent to the Stream's consumers (if any). Returns false if the Stream is + * paused, true otherwise. This lets Node's pipe method handle back-pressure. + * + * You shouldn't need to call this yourself, but it may be called by Node + * functions which treat Highland Streams as a [Node Writable Stream](http://nodejs.org/api/stream.html#stream_class_stream_writable). + * + * @id write + * @section Streams + * @name Stream.write(x) + * @param x - the value to write to the Stream + * @api public + */ + write(x: R): boolean; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Forks a stream, allowing you to add additional consumers with shared + * back-pressure. A stream forked to multiple consumers will only pull values + * from it's source as fast as the slowest consumer can handle them. + * + * @id fork + * @section Streams + * @name Stream.fork() + * @api public + */ + fork(): Stream; + + /** + * Observes a stream, allowing you to handle values as they are emitted, without + * adding back-pressure or causing data to be pulled from the source. This can + * be useful when you are performing two related queries on a stream where one + * would block the other. Just be aware that a slow observer could fill up it's + * buffer and cause memory issues. Where possible, you should use [fork](#fork). + * + * @id observe + * @section Streams + * @name Stream.observe() + * @api public + */ + observe(): Stream; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Extracts errors from a Stream and applies them to an error handler + * function. Returns a new Stream with the errors removed (unless the error + * handler chooses to rethrow them using `push`). Errors can also be + * transformed and put back onto the Stream as values. + * + * @id errors + * @section Streams + * @name Stream.errors(f) + * @param {Function} f - the function to pass all errors to + * @api public + */ + errors(f: (err: Error, push: (err: Error, x?: R) => void) => void): Stream; + + /** + * Like the [errors](#errors) method, but emits a Stream end marker after + * an Error is encountered. + * + * @id stopOnError + * @section Streams + * @name Stream.stopOnError(f) + * @param {Function} f - the function to handle an error + * @api public + */ + stopOnError(f: (err: Error) => void): Stream; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Iterates over every value from the Stream, calling the iterator function + * on each of them. This function causes a **thunk**. + * + * If an error from the Stream reaches the `each` call, it will emit an + * error event (which will cause it to throw if unhandled). + * + * @id each + * @section Streams + * @name Stream.each(f) + * @param {Function} f - the iterator function + * @api public + */ + each(f: (x: R) => void): void; + + /** + * Applies results from a Stream as arguments to a function + * + * @id apply + * @section Streams + * @name Stream.apply(f) + * @param {Function} f - the function to apply arguments to + * @api public + */ + // TODO what to do here? + apply(f: Function): void; + + /** + * Collects all values from a Stream into an Array and calls a function with + * once with the result. This function causes a **thunk**. + * + * If an error from the Stream reaches the `toArray` call, it will emit an + * error event (which will cause it to throw if unhandled). + * + * @id toArray + * @section Streams + * @name Stream.toArray(f) + * @param {Function} f - the callback to provide the completed Array to + * @api public + */ + toArray(f: (arr: R[]) => void): void; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Creates a new Stream of transformed values by applying a function to each + * value from the source. The transformation function can be replaced with + * a non-function value for convenience, and it will emit that value + * for every data event on the source Stream. + * + * @id map + * @section Streams + * @name Stream.map(f) + * @param f - the transformation function or value to map to + * @api public + */ + map(f: (x: R) => U): Stream; + + /** + * Creates a new Stream of values by applying each item in a Stream to an + * iterator function which may return a Stream. Each item on these result + * Streams are then emitted on a single output Stream. + * + * The same as calling `stream.map(f).flatten()`. + * + * @id flatMap + * @section Streams + * @name Stream.flatMap(f) + * @param {Function} f - the iterator function + * @api public + */ + flatMap(f: (x: R) => Stream): Stream; + flatMap(f: (x: R) => U): Stream; + + /** + * Retrieves values associated with a given property from all elements in + * the collection. + * + * @id pluck + * @section Streams + * @name Stream.pluck(property) + * @param {String} prop - the property to which values should be associated + * @api public + */ + pluck(prop: string): Stream; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Creates a new Stream including only the values which pass a truth test. + * + * @id filter + * @section Streams + * @name Stream.filter(f) + * @param f - the truth test function + * @api public + */ + filter(f: (x: R) => boolean): Stream; + + /** + * Filters using a predicate which returns a Stream. If you need to check + * against an asynchronous data source when filtering a Stream, this can + * be convenient. The Stream returned from the filter function should have + * a Boolean as it's first value (all other values on the Stream will be + * disregarded). + * + * @id flatFilter + * @section Streams + * @name Stream.flatFilter(f) + * @param {Function} f - the truth test function which returns a Stream + * @api public + */ + flatFilter(f: (x: R) => Stream): Stream; + + /** + * A convenient form of filter, which returns the first object from a + * Stream that passes the provided truth test + * + * @id find + * @section Streams + * @name Stream.find(f) + * @param {Function} f - the truth test function which returns a Stream + * @api public + */ + find(f: (x: R) => boolean): Stream; + + /** + * A convenient form of reduce, which groups items based on a function or property name + * + * @id group + * @section Streams + * @name Stream.group(f) + * @param {Function|String} f - the function or property name on which to group, + * toString() is called on the result of a function. + * @api public + */ + // TODO verify this + group(f: (x: R) => string): Stream<{[prop:string]:R[]}>; + group(prop: string): Stream<{[prop:string]:R[]}>; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Filters a Stream to drop all non-truthy values. + * + * @id compact + * @section Streams + * @name Stream.compact() + * @api public + */ + compact(): Stream; + + /** + * A convenient form of filter, which returns all objects from a Stream + * match a set of property values. + * + * @id where + * @section Streams + * @name Stream.where(props) + * @param {Object} props - the properties to match against + * @api public + */ + where(props: Object): Stream; + + /** + * Takes two Streams and returns a Stream of corresponding pairs. + * + * @id zip + * @section Streams + * @name Stream.zip(ys) + * @param {Array | Stream} ys - the other stream to combine values with + * @api public + */ + zip(ys: R[]): Stream; + zip(ys: Stream): Stream; + + /** + * Creates a new Stream with the first `n` values from the source. + * + * @id take + * @section Streams + * @name Stream.take(n) + * @param {Number} n - integer representing number of values to read from source + * @api public + */ + take(n: number): Stream; + + /** + * Drops all values from the Stream apart from the last one (if any). + * + * @id last + * @section Streams + * @name Stream.last() + * @api public + */ + last(): Stream; + + /** + * Reads values from a Stream of Streams, emitting them on a Single output + * Stream. This can be thought of as a flatten, just one level deep. Often + * used for resolving asynchronous actions such as a HTTP request or reading + * a file. + * + * @id sequence + * @section Streams + * @name Stream.sequence() + * @api public + */ + //TODO figure out typing + sequence(): Stream; + + /** + * An alias for the [sequence](#sequence) method. + * + * @id series + * @section Streams + * @name Stream.series() + * @api public + */ + // TODO figure out typing + series(): Stream; + + /** + * Recursively reads values from a Stream which may contain nested Streams + * or Arrays. As values or errors are encountered, they are emitted on a + * single output Stream. + * + * @id flatten + * @section Streams + * @name Stream.flatten() + * @api public + */ + flatten(): Stream; + flatten(): Stream; + + /** + * Takes a Stream of Streams and reads from them in parallel, buffering + * the results until they can be returned to the consumer in their original + * order. + * + * @id parallel + * @section Streams + * @name Stream.parallel(n) + * @param {Number} n - the maximum number of concurrent reads/buffers + * @api public + */ + parallel(n: number): Stream; + + /** + * Switches source to an alternate Stream if the current Stream is empty. + * + * @id otherwise + * @section Streams + * @name Stream.otherwise(ys) + * @param {Stream} ys - alternate stream to use if this stream is empty + * @api public + */ + otherwise(ys: Stream): Stream; + + /** + * Adds a value to the end of a Stream. + * + * @id append + * @section Streams + * @name Stream.append(y) + * @param y - the value to append to the Stream + * @api public + */ + append(y: R): Stream; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Boils down a Stream to a single value. The memo is the initial state + * of the reduction, and each successive step of it should be returned by + * the iterator function. The iterator is passed two arguments: + * the memo and the next value. + * + * @id reduce + * @section Streams + * @name Stream.reduce(memo, iterator) + * @param memo - the initial state of the reduction + * @param {Function} iterator - the function which reduces the values + * @api public + */ + // TODO: convert this to this.scan(z, f).last() + reduce(memo: U, f: (memo: U, x: R) => U): Stream; + + /** + * Same as [reduce](#reduce), but uses the first element as the initial + * state instead of passing in a `memo` value. + * + * @id reduce1 + * @section Streams + * @name Stream.reduce1(iterator) + * @param {Function} iterator - the function which reduces the values + * @api public + */ + reduce1(memo: U, f: (memo: U, x: R) => U): Stream; + + /** + * Groups all values into an Array and passes down the stream as a single + * data event. This is a bit like doing [toArray](#toArray), but instead + * of accepting a callback and causing a *thunk*, it passes the value on. + * + * @id collect + * @section Streams + * @name Stream.collect() + * @api public + */ + collect(): Stream; + + /** + * Like [reduce](#reduce), but emits each intermediate value of the + * reduction as it is calculated. + * + * @id scan + * @section Streams + * @name Stream.scan(memo, iterator) + * @param memo - the initial state of the reduction + * @param {Function} iterator - the function which reduces the values + * @api public + */ + scan(memo: U, x: (memo: U, x: R) => U): Stream; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Concatenates a Stream to the end of this Stream. + * + * Be aware that in the top-level export, the args may be in the reverse + * order to what you'd expect `_([a], [b]) => [b, a]`, as this follows the + * convention of other top-level exported functions which do `x` to `y`. + * + * @id concat + * @section Streams + * @name Stream.concat(ys) + * @params {Stream | Array} ys - the values to concatenate onto this Stream + * @api public + */ + concat(ys: Stream): Stream; + concat(ys: R[]): Stream; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Calls a named method on each object from the Stream - returning + * a new stream with the result of those calls. + * + * @id invoke + * @section Streams + * @name Stream.invoke(method, args) + * @param {String} method - the method name to call + * @param {Array} args - the arguments to call the method with + * @api public + */ + invoke(method: string, args: any[]): Stream; + + /** + * Ensures that only one data event is push downstream (or into the buffer) + * every `ms` milliseconds, any other values are dropped. + * + * @id throttle + * @section Streams + * @name Stream.throttle(ms) + * @param {Number} ms - the minimum milliseconds between each value + * @api public + */ + throttle(ms: number): Stream; + + /** + * Holds off pushing data events downstream until there has been no more + * data for `ms` milliseconds. Sends the last value that occurred before + * the delay, discarding all other values. + * + * @id debounce + * @section Streams + * @name Stream.debounce(ms) + * @param {Number} ms - the milliseconds to wait before sending data + * @api public + */ + debounce(ms: number): Stream; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + /** + * Creates a new Stream, which when read from, only returns the last + * seen value from the source. The source stream does not experience + * back-pressure. Useful if you're using a Stream to model a changing + * property which you need to query periodically. + * + * @id latest + * @section Streams + * @name Stream.latest() + * @api public + */ + latest(): Stream; + } +} + +declare var highland:HighlandStatic; + +declare module 'highland' { + export = highland; +} + diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index 04ffde1061..9e3567cdb9 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -1,10 +1,7 @@ -/* - highlight.js definition by Niklas Mollenhauer - Last Update: 10.09.2013 - Source Code: https://github.com/isagalaev/highlight.js - Project Page: http://softwaremaniacs.org/soft/highlight/en/ -*/ - +// Type definitions for highlight.js +// Project: https://github.com/isagalaev/highlight.js +// Definitions by: Niklas Mollenhauer +// Definitions: https://github.com/borisyankov/DefinitelyTyped declare module "highlight.js" { module hljs diff --git a/humane/humane.d.ts b/humane/humane.d.ts index aa3184db89..06f865636a 100644 --- a/humane/humane.d.ts +++ b/humane/humane.d.ts @@ -1,6 +1,6 @@ // Type definitions for Humane 3.0 // Project: http://wavded.github.com/humane-js/ -// Definitions by: https://github.com/jmvrbanac +// Definitions by: jmvrbanac // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index 5fd6310304..6fabcce447 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -1,11 +1,12 @@ -/// - // Type definitions for i18next (v1.5.10 incl. jQuery) // Project: http://i18next.com -// Sources: https://github.com/jamuhl/i18next/ // Definitions by: Maarten Docter - Blog: http://www.maartendocter.nl // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Sources: https://github.com/jamuhl/i18next/ + +/// + interface IResourceStore { [language: string]: IResourceStoreLanguage; } diff --git a/icheck/icheck.d.ts b/icheck/icheck.d.ts index 750d9e94e4..5df433875e 100644 --- a/icheck/icheck.d.ts +++ b/icheck/icheck.d.ts @@ -1,6 +1,6 @@ // Type definitions for iCheck v0.8 // Project: http://damirfoy.com/iCheck/ -// Definitions by: Dániel Tar https://github.com/qcz +// Definitions by: Dániel Tar // Definitions: https://github.com/borisyankov/DefinitelyTyped interface ICheckOptions { @@ -109,4 +109,4 @@ interface ICheckOptions { interface JQuery { iCheck(options?: ICheckOptions): JQuery; iCheck(command: string, callback?: () => void): void; -} \ No newline at end of file +} diff --git a/ix.js/ix.d.ts b/ix.js/ix.d.ts index 8de0366e71..ebd5b160b4 100644 --- a/ix.js/ix.d.ts +++ b/ix.js/ix.d.ts @@ -1,6 +1,7 @@ // Type definitions for IxJS 1.0.6 / ix.js // Project: https://github.com/Reactive-Extensions/IxJS // Definitions by: Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/ix.js/l2o.d.ts b/ix.js/l2o.d.ts index d36cb25304..209c9b6757 100644 --- a/ix.js/l2o.d.ts +++ b/ix.js/l2o.d.ts @@ -1,6 +1,7 @@ -// Type definitions for IxJS 1.0.6 / l2o.js +// Type definitions for IxJS 1.0.6 / l2o.js // Project: https://github.com/Reactive-Extensions/IxJS // Definitions by: Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped declare module Ix { export interface Disposable { @@ -247,4 +248,4 @@ declare module Ix { } var Enumerable: EnumerableStatic; -} \ No newline at end of file +} diff --git a/jake/jake.d.ts b/jake/jake.d.ts index 14d488bd3a..6995abc83c 100644 --- a/jake/jake.d.ts +++ b/jake/jake.d.ts @@ -114,7 +114,7 @@ declare module jake{ */ breakOnError?:boolean; } - export function exec(cmds:string[], callback?:()=>void, opts?:ExecOptions); + export function exec(cmds:string[], callback?:()=>void, opts?:ExecOptions):void; /** @@ -124,11 +124,7 @@ declare module jake{ * @event stderr When the stderr for the child-process recieves data. This streams the stderr data. Passes one arg, the chunk of data. * @event error When a shell-command */ - export interface Exec extends EventEmitter{ - constructor(cmds:string[], callback?:()=>void, opts?:ExecOptions); - constructor(cmds:string[], opts?:ExecOptions, callback?:()=>void); - constructor(cmds:string, callback?:()=>void, opts?:ExecOptions); - constructor(cmds:string, opts?:ExecOptions, callback?:()=>void); + export interface Exec extends NodeEventEmitter { append(cmd:string): void; run(): void; } @@ -174,7 +170,7 @@ declare module jake{ * Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. * @default false */ - asyc?: boolean; + async?: boolean; } /** @@ -182,7 +178,7 @@ declare module jake{ * * @event complete */ - export class Task implements EventEmitter { + export class Task implements NodeEventEmitter { /** * @name name The name of the Task * @param prereqs Prerequisites to be run before this task @@ -201,18 +197,16 @@ declare module jake{ */ reenable(): void; - addListener(event: string, listener: Function): EventEmitter; - on(event: string, listener: Function): EventEmitter; - once(event: string, listener: Function): EventEmitter; - removeListener(event: string, listener: Function): EventEmitter; - removeAllListeners(event?: string): EventEmitter; + addListener(event: string, listener: Function): NodeEventEmitter; + on(event: string, listener: Function): NodeEventEmitter; + once(event: string, listener: Function): NodeEventEmitter; + removeListener(event: string, listener: Function): NodeEventEmitter; + removeAllListeners(event?: string): NodeEventEmitter; setMaxListeners(n: number): void; listeners(event: string): Function[]; - emit(event: string, arg1?: any, arg2?: any): boolean; + emit(event: string, ...args: any[]): boolean; } - - export class DirectoryTask{ /** * @param name The name of the directory to create. @@ -225,7 +219,7 @@ declare module jake{ * Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. * @default false */ - asyc?: boolean; + async?: boolean; } export class FileTask{ @@ -275,7 +269,6 @@ declare module jake{ exclude(file:FileFilter[]): void; exclude(...file:FileFilter[]): void; - /** * Populates the FileList from the include/exclude rules with a list of * actual files @@ -377,12 +370,12 @@ declare module jake{ constructor(name:string, packageFiles:string[]); } - export function addListener(event: string, listener: Function); - export function on(event: string, listener: Function); - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListener(event: string): void; + export function addListener(event: string, listener: Function): NodeEventEmitter; + export function on(event: string, listener: Function): NodeEventEmitter; + export function once(event: string, listener: Function): NodeEventEmitter; + export function removeListener(event: string, listener: Function): NodeEventEmitter; + export function removeAllListener(event: string): NodeEventEmitter; export function setMaxListeners(n: number): void; - export function listeners(event: string): { Function; }[]; - export function emit(event: string, arg1?: any, arg2?: any): void; + export function listeners(event: string): Function[]; + export function emit(event: string, ...args: any[]): boolean; } diff --git a/jake/jake.d.ts.tscparams b/jake/jake.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/jake/jake.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/jasmine/jasmine-1.3.d.ts b/jasmine/jasmine-1.3.d.ts index 59e7d17570..b380959d0c 100644 --- a/jasmine/jasmine-1.3.d.ts +++ b/jasmine/jasmine-1.3.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine 1.3 +// Type definitions for Jasmine 1.3 // Project: http://pivotal.github.com/jasmine/ // Definitions by: Boris Yankov // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index c3e95e4279..4c01b347bf 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Jasmine 2.0 +// Type definitions for Jasmine 2.0 // Project: http://pivotal.github.com/jasmine/ -// Definitions by: Boris Yankov and Theodore Brown +// Definitions by: Boris Yankov , Theodore Brown // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped diff --git a/jointjs/jointjs.d.ts b/jointjs/jointjs.d.ts index 88c67290c4..f4e0926ea7 100644 --- a/jointjs/jointjs.d.ts +++ b/jointjs/jointjs.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Joint JS 0.6 +// Type definitions for Joint JS 0.6 // Project: http://www.jointjs.com/ -// Definitions by: Aidan Reel with help from David Durman +// Definitions by: Aidan Reel , David Durman // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -112,4 +112,4 @@ declare module joint { function deepMixin(objects: any[]): any; function deepSupplement(objects: any[], defaultIndicator?: any): any; } -} \ No newline at end of file +} diff --git a/jquery.address/jquery.address.d.ts b/jquery.address/jquery.address.d.ts index bd016d5b1e..cb71172457 100644 --- a/jquery.address/jquery.address.d.ts +++ b/jquery.address/jquery.address.d.ts @@ -1,10 +1,10 @@ -/// - // Type definitions for jQuery.Address 1.5 // Project: https://github.com/asual/jquery-address // Definitions by: Martin Duparc <@martinduparc> // Definitions: https://github.com/borisyankov/DefinitelyTyped/ +/// + interface JQueryAddressStatic { (); change(callback: any): void; diff --git a/jquery.are-you-sure/jquery.are-you-sure-tests.ts b/jquery.are-you-sure/jquery.are-you-sure-tests.ts index 6f8691e05d..89ac4e87a8 100644 --- a/jquery.are-you-sure/jquery.are-you-sure-tests.ts +++ b/jquery.are-you-sure/jquery.are-you-sure-tests.ts @@ -14,5 +14,6 @@ $("test").areYouSure({ message: "Oops - sure you wanna leave?", dirtyClass: "soiled", fieldSelector: "input[type='text']", - change: function () { alert("changed");} + change: function () { alert("changed");}, + silent: true }) \ No newline at end of file diff --git a/jquery.are-you-sure/jquery.are-you-sure.d.ts b/jquery.are-you-sure/jquery.are-you-sure.d.ts index 62cc39c2c8..81392361ab 100644 --- a/jquery.are-you-sure/jquery.are-you-sure.d.ts +++ b/jquery.are-you-sure/jquery.are-you-sure.d.ts @@ -19,6 +19,9 @@ interface AreYouSureOptions { /**Jquery selector to use to find input elements*/ fieldSelector?: string; + + /**Make Are-You-Sure "silent" by disabling the warning message*/ + silent?: boolean; } interface AreYouSure { diff --git a/jquery.color/jquery.color-tests.ts b/jquery.color/jquery.color-tests.ts new file mode 100644 index 0000000000..267ee3b63b --- /dev/null +++ b/jquery.color/jquery.color-tests.ts @@ -0,0 +1,46 @@ +/// +/// + +var color = $.Color("rgba(255, 255, 255, 0.4)"); +var color1 = $.Color({red: 255, green: 255, blue: 255}); +var color2 = $.Color({hue: 359, saturation: 0.5, lightness: 0.5}); + +// getters +var red = color.red(); +var green = color.green(); +var blue = color.blue(); +var alpha = color.alpha(); +var hue = color.hue(); +var saturation = color.saturation(); +var lightness = color.lightness(); + +// setters +var newRed = color.red(20); +var newGreen = color.green(20); +var newBlue = color.blue(20); +var newAlpha = color.alpha(0.5); +var newHue = color.hue(20); +var newSaturation = color.saturation(0.5); +var newLightness = color.lightness(0.5); + +// rgba methods +var rgba = color.rgba(); +var newRgba1 = color.rgba(255, 255, 255, 0.5); +var newRgba2 = color.rgba({red: 255, green: 255, blue: 255}); +var newRgba3 = color.rgba(rgba); + +// hsla methods +var hsla = color.hsla(); +var newHsla1 = color.hsla(359, 0.5, 0.5, 0.5); +var newHsla2 = color.hsla({hue: 359, saturation: 0.5, lightness: 0.5}); +var newHsla3 = color.hsla(hsla); + +// string methods +var rgbaString = color.toRgbaString(); +var hslaString = color.toHslaString(); +var hexString = color.toHexString(); + +// other colors +var transitionedColor = color.transition(newRed, 0.5); +var blendedColor = color.blend(newRed); +var isEqual = color.is(newRed); diff --git a/jquery.color/jquery.color.d.ts b/jquery.color/jquery.color.d.ts new file mode 100644 index 0000000000..8d5000a6c2 --- /dev/null +++ b/jquery.color/jquery.color.d.ts @@ -0,0 +1,168 @@ +// Type definitions for jquery.color.js v2.1.2 +// Project: https://github.com/jquery/jquery-color +// Definitions by: Derek Cicerone +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQueryColor { + /** + * Returns the red component of the color (integer from 0 - 255). + */ + red(): number; + + /** + * Returns a copy of the color object with the red set to val. + */ + red(val: number): JQueryColor; + + /** + * Returns the green component of the color (integer from 0 - 255). + */ + green(): number; + + /** + * Returns a copy of the color object with the green set to val. + */ + green(val: number): JQueryColor; + + /** + * Returns the blue component of the color (integer from 0 - 255). + */ + blue(): number; + + /** + * Returns a copy of the color object with the blue set to val. + */ + blue(val: number): JQueryColor; + + /** + * Returns the alpha value of this color (float from 0.0 - 1.0). + */ + alpha(): number; + + /** + * Returns a copy of the color object with the alpha set to val. + */ + alpha(val: number): JQueryColor; + + /** + * Returns the hue component of the color (integer from 0 - 359). + */ + hue(): number; + + /** + * Returns a copy of the color object with the hue set to val. + */ + hue(val: number): JQueryColor; + + /** + * Returns the saturation component of the color (float from 0.0 - 1.0). + */ + saturation(): number; + + /** + * Returns a copy of the color object with the saturation set to val. + */ + saturation(val: number): JQueryColor; + + /** + * Returns the lightness component of the color (float from 0.0 - 1.0). + */ + lightness(): number; + + /** + * Returns a copy of the color object with the lightness set to val. + */ + lightness(val: number): JQueryColor; + + /** + * Returns a rgba "tuple" [ red, green, blue, alpha ]. + */ + rgba(): number[]; + + /** + * Returns a copy of the color with any defined values set to the new value. + */ + rgba(red: number, green: number, blue: number, alpha?: number): JQueryColor; + + /** + * Returns a copy of the color with any defined values set to the new value. + */ + rgba(val: RgbaColor): JQueryColor; + + /** + * Returns a copy of the color with any defined values set to the new value. + */ + rgba(vals: number[]): JQueryColor; + + /** + * Returns a HSL tuple [ hue, saturation, lightness, alpha ]. + */ + hsla(): number[]; + + /** + * Returns a copy of the color with any defined values set to the new value. + */ + hsla(hue: number, saturation: number, lightness: number, alpha?: number): JQueryColor; + + /** + * Returns a copy of the color with any defined values set to the new value. + */ + hsla(val: HslaColor): JQueryColor; + + /** + * Returns a copy of the color with any defined values set to the new value. + */ + hsla(vals: number[]): JQueryColor; + + /** + * Returns a CSS string "rgba(255, 255, 255, 0.4)". + */ + toRgbaString(): string; + + /** + * Returns a css string "hsla(330, 75%, 25%, 0.4)". + */ + toHslaString(): string; + + /** + * Returns a css string "#abcdef", with "includeAlpha" uses "#rrggbbaa" (alpha *= 255). + */ + toHexString(includeAlpha?: boolean): string; + + /** + * The color distance (0.0 - 1.0) of the way between this color and othercolor. + */ + transition(othercolor: JQueryColor, distance: number): JQueryColor; + + /** + * Will apply this color on top of the other color using alpha blending. + */ + blend(othercolor: JQueryColor): void; + + /** + * Checks if two colors are equal. + */ + is(otherColor: JQueryColor): boolean; +} + +interface HslaColor { + hue?: number; + saturation?: number; + lightness?: number; + alpha?: number; +} + +interface RgbaColor { + red?: number; + green?: number; + blue?: number; + alpha?: number; +} + +interface JQueryStatic { + Color(color: HslaColor): JQueryColor; + Color(color: RgbaColor): JQueryColor; + Color(color: string): JQueryColor; +} diff --git a/jquery.colorbox/jquery.colorbox.d.ts b/jquery.colorbox/jquery.colorbox.d.ts index 164d47bb3b..d284223462 100644 --- a/jquery.colorbox/jquery.colorbox.d.ts +++ b/jquery.colorbox/jquery.colorbox.d.ts @@ -1,10 +1,10 @@ -/// - // Type definitions for jQuery.Colorbox 1.4.15 // Project: http://www.jacklmoore.com/colorbox/ // Definitions by: Gidon Junge <@gjunge> // Definitions: https://github.com/borisyankov/DefinitelyTyped/ +/// + interface ColorboxResizeSettings { height?: number; innerHeight?: number; diff --git a/jquery.colorpicker/jquery.colorpicker.d.ts.tscparams b/jquery.colorpicker/jquery.colorpicker.d.ts.tscparams deleted file mode 100644 index 3cc762b550..0000000000 --- a/jquery.colorpicker/jquery.colorpicker.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" \ No newline at end of file diff --git a/jquery.cycle2/jquery.cycle2-tests.ts b/jquery.cycle2/jquery.cycle2-tests.ts new file mode 100644 index 0000000000..8a7eedf635 --- /dev/null +++ b/jquery.cycle2/jquery.cycle2-tests.ts @@ -0,0 +1,50 @@ +/// +/// + +// basic +$('#element').cycle(); + + +// code snippets from http://jquery.malsup.com/cycle2/api +$('.cycle-slideshow').cycle({ + speed: 600, + manualSpeed: 100 +}); + +var newSlide = ''; +$('.cycle-slideshow').cycle('add', newSlide); + +$('.cycle-slideshow').cycle('destroy'); + +// goto 3rd slide +$('.cycle-slideshow').cycle('goto', 2); + +$('.cycle-slideshow').cycle('next'); + +$('.cycle-slideshow').cycle('pause'); + +$('.cycle-slideshow').cycle('prev'); + +$('.cycle-slideshow').cycle('reinit'); + +// remove 2nd slide +$('.cycle-slideshow').cycle('remove', 1); + +$('.cycle-slideshow').cycle('resume'); + +$('.cycle-slideshow').cycle('stop'); + + +// from http://jquery.malsup.com/cycle2/demo/add.php +var images = [ + '', + '', + '' +]; + +$('button').one('click', function() { + for (var i=0; i < images.length; i++) { + $('.cycle-slideshow').cycle('add', images[i]); + } + $(this).prop('disabled', true) +}) diff --git a/jquery.cycle2/jquery.cycle2.d.ts b/jquery.cycle2/jquery.cycle2.d.ts new file mode 100644 index 0000000000..699d2aff87 --- /dev/null +++ b/jquery.cycle2/jquery.cycle2.d.ts @@ -0,0 +1,143 @@ +// Type definitions for jQuery Cycle2 version 2.1.2 (build 20140216) +// Project: http://jquery.malsup.com/cycle2/ (also https://github.com/malsup/cycle2) +// Definitions by: Donny Nadolny +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +interface JQuery { + cycle: JQueryCycle2.Cycle2; + + on(methodName: 'cycle-after', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState, outgoingSlideEl: Element, incomingSlideEl: Element, forwardFlag: boolean) => void): JQuery; + on(methodName: 'cycle-before', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState, outgoingSlideEl: Element, incomingSlideEl: Element, forwardFlag: boolean) => void): JQuery; + on(methodName: 'cycle-bootstrap', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState, API: JQueryCycle2.API) => void): JQuery; + on(methodName: 'cycle-destroyed', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-finished', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-initialized', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-next', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-pager-activated', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-paused', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-post-initialize', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-pre-initialize', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-prev', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-resumed', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-slide-added', callback: (event: JQueryEventObject, jQueryWrappedSlideEl: JQuery) => void): JQuery; + on(methodName: 'cycle-slide-removed', callback: (event: JQueryEventObject, indexOfSlideRemoved: number, removedSlideEl: Element) => void): JQuery; + on(methodName: 'cycle-stopped', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-transition-stopped', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState) => void): JQuery; + on(methodName: 'cycle-update-view', callback: (event: JQueryEventObject, optionHash: JQueryCycle2.OptionsWithState, slideOptionsHash: JQueryCycle2.OptionsWithState, currentSlideEl: Element) => void): JQuery; +} + + +declare module JQueryCycle2 { + interface Cycle2 { + (options?: Options): JQuery; + (methodName: 'add', newSlide: any): JQuery; // string or JQuery + (methodName: 'destroy'): JQuery; + (methodName: 'goto', index: number): JQuery; + (methodName: 'next'): JQuery; + (methodName: 'pause'): JQuery; + (methodName: 'prev'): JQuery; + (methodName: 'reinit'): JQuery; + (methodName: 'remove', index: number): JQuery; + (methodName: 'resume'): JQuery; + (methodName: 'stop'): JQuery; + (methodNameDontCallMe: string, arg1DontCallMe: any, arg2DontCallMe: any): JQuery; // catch-all, shouldn't ever be called though + } + + interface Options { + allowWrap?: boolean; + autoHeight?: any; // number or string + autoSelector?: string; + caption?: string; + captionTemplate?: string; + continueAuto?: boolean; + delay?: number; + disabledClass?: string; + easing?: string; + fx?: string; + hideNonActive?: boolean; + loader?: any; // boolean or 'wait' + log?: boolean; + loop?: number; + manualSpeed?: number; + manualTrump?: boolean; + next?: string; + nextEvent?: string; + overlay?: string; + overlayTemplate?: string; + pager?: string; + pagerActivateClass?: string; + pagerEvent?: string; + pagerTemplate?: string; + pauseOnHover?: any; // boolean or string + paused?: boolean; + prev?: string; + prevEvent?: string; + progressive?: string; + random?: boolean; + reverse?: boolean; + slideActiveClass?: string; + slideCss?: any; + slideClass?: string; + slides?: string; + speed?: number; + startingSlide?: number; + swipe?: boolean; + sync?: boolean; + timeout?: number; + tmplRegex?: string; + updateView?: number; + } + + interface OptionsWithState extends Options { + busy: boolean; + currSlide: number; + nextSlide: number; + paused: boolean; + slideNum: number; + slideCount: number; + } + + interface API { + add(slides: any, prepend?: boolean): void; // string or array or JQuery + addInitialSlides(): void; + advanceSlide(numberOfOpositions: number): boolean; // always false + buildPagerLink(slideOptionHash: Options, slide: any /*not sure*/): void; + buildSlideOpts(slide: any /*not sure*/): Options; + calcFirstSlide(): void; + calcNextSlide(): void; + calcTx(slideOptions: Options, manual: boolean): Transition; + destroy(): void; + doTransition(slideOptions: Options, currEl: Element, nextEl: Element, fwdFlag: boolean, callback: Function): void; + getComponent(nameOfComponent: string): JQuery; + getSlideIndex(slideElement: Element): number; + getSlideOpts(slideIndex: number): Options; + goto(index: number): void; + initSlide(slideOptions: Options, slide: any /*not sure*/, suggestedZindex: number): void; + initSlideshow(): void; + log(...args: any[]): void; + next(): void; + page(pagerEl: Element, targetEl: Element): void; + pause(): void; + postInitSlideshow(): void; + preInitSlideshow(): void; + prepareTx(manualFlag: boolean, fwdFlag: boolean): void; + prev(): void; + queueTransition(slideOptions: Options): void; + reinit(): void; + remove(slideIndexToRemove: number): void; + resume(): void; + stackSlides(currEl: Element, nextEl: Element, fwdFlag: boolean): void; + stop(): void; + stopTransition(): void; + tmpl(templateString: string, optionHash: Options, slideEl: Element): void; + trigger(eventName: String, ...args: any[]): void; + updateView(): void; + } + + interface Transition { + before(opts: Options, curr: Element, next: Element, fwd: boolean): void; + } +} \ No newline at end of file diff --git a/jquery.gridster/gridster.d.ts b/jquery.gridster/gridster.d.ts index 968c0f3330..b293dcb2fa 100644 --- a/jquery.gridster/gridster.d.ts +++ b/jquery.gridster/gridster.d.ts @@ -1,4 +1,9 @@ -/* +// Type definitions for jQuery.gridster 0.1.0 +// Project: https://github.com/jbaldwin/gridster +// Definitions by: Josh Baldwin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* gridster-0.1.0.d.ts may be freely distributed under the MIT license. Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/gridster.d.ts diff --git a/jquery.jnotify/jquery.jnotify.d.ts b/jquery.jnotify/jquery.jnotify.d.ts index 7c9cf05bbb..21a9485d7d 100644 --- a/jquery.jnotify/jquery.jnotify.d.ts +++ b/jquery.jnotify/jquery.jnotify.d.ts @@ -1,8 +1,8 @@ -// Typescript type definitions for jQuery.jNotify 1.0 by Fabio Franzini +// Type definitions for jQuery.jNotify 1.0 // Project: http://jnotify.codeplex.com // Definitions by: James Curran // Definitions: https://github.com/borisyankov/DefinitelyTyped - +// Project by: Fabio Franzini /// @@ -22,4 +22,4 @@ interface JNotifyOptions { interface JQuery { jnotifyInizialize(options?: JNotifyInitOptions); jnotifyAddMessage(options?: JNotifyOptions); -} \ No newline at end of file +} diff --git a/jquery.livestampjs/jquery.livestampjs.d.ts b/jquery.livestampjs/jquery.livestampjs.d.ts index d460b888d4..35453d4f3f 100644 --- a/jquery.livestampjs/jquery.livestampjs.d.ts +++ b/jquery.livestampjs/jquery.livestampjs.d.ts @@ -1,9 +1,10 @@ // Type definitions for Livestamp.js -// A simple, unobtrusive jQuery plugin that provides auto-updating timeago text to your timestamped HTML elements using Moment.js. -// Project: http://http://mattbradley.github.com/livestampjs/ +// Project: http://mattbradley.github.com/livestampjs/ // Definitions by: Vincent Bortone // Definitions: https://github.com/borisyankov/DefinitelyTyped +// A simple, unobtrusive jQuery plugin that provides auto-updating timeago text to your timestamped HTML elements using Moment.js. + /// /// @@ -24,4 +25,4 @@ interface JQuery { livestamp(moment: Moment): JQuery; livestamp(timestamp: number): JQuery; livestamp(timestamp: string): JQuery; -} \ No newline at end of file +} diff --git a/jquery.menuaim/jquery.menuaim.d.ts b/jquery.menuaim/jquery.menuaim.d.ts index 138adc65dc..54215620af 100644 --- a/jquery.menuaim/jquery.menuaim.d.ts +++ b/jquery.menuaim/jquery.menuaim.d.ts @@ -1,5 +1,9 @@ -/// +// Type definitions for jQuery-menu-aim +// Project: https://github.com/kamens/jQuery-menu-aim +// Definitions by: Robert Fonseca-Ensor +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// interface JQueryMenuAimOptions { /** Function to call when a row is purposefully activated. Use this diff --git a/jquery.noty/jquery.noty.d.ts b/jquery.noty/jquery.noty.d.ts index fe548b6e8c..9ec7d85e4f 100644 --- a/jquery.noty/jquery.noty.d.ts +++ b/jquery.noty/jquery.noty.d.ts @@ -1,7 +1,8 @@ -// Typescript type definitions for jQuery.noty v2.0 by Nedim Carter +// Type definitions for jQuery.noty v2.0 // Project: http://needim.github.io/noty/ // Definitions by: Aaron King // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Project by: Nedim Carter /// @@ -64,4 +65,4 @@ declare var noty: { closed: boolean; shown: boolean; -} \ No newline at end of file +} diff --git a/jquery.pickadate/jquery.pickadate-tests.ts b/jquery.pickadate/jquery.pickadate-tests.ts index f99d55ecc3..fde52f3e3e 100644 --- a/jquery.pickadate/jquery.pickadate-tests.ts +++ b/jquery.pickadate/jquery.pickadate-tests.ts @@ -1,4 +1,4 @@ -/// +/// /* * Date picker tests diff --git a/jquery.pickadate/jquery.pickadate.d.ts b/jquery.pickadate/jquery.pickadate.d.ts index 077ae15cde..274f20f909 100644 --- a/jquery.pickadate/jquery.pickadate.d.ts +++ b/jquery.pickadate/jquery.pickadate.d.ts @@ -1,4 +1,4 @@ -// Type definitions for pickadate.js 3.3.0 +// Type definitions for pickadate.js 3.3.0 // Project: https://github.com/amsul/pickadate.js // Definitions by: Theodore Brown // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/jquery.simulate/jquery.simulate-tests.ts b/jquery.simulate/jquery.simulate-tests.ts new file mode 100644 index 0000000000..98de970342 --- /dev/null +++ b/jquery.simulate/jquery.simulate-tests.ts @@ -0,0 +1,6 @@ +/// + +var $element = $("body"); + +$element.simulate("click"); +$element.simulate("mousewheel", { detail: 50 }); diff --git a/jquery.simulate/jquery.simulate.d.ts b/jquery.simulate/jquery.simulate.d.ts new file mode 100644 index 0000000000..65114ad70f --- /dev/null +++ b/jquery.simulate/jquery.simulate.d.ts @@ -0,0 +1,19 @@ +// Type definitions for jquery.simulate.js +// Project: https://github.com/jquery/jquery-simulate +// Definitions by: Derek Cicerone +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQuery { + + /** + * Simulates an event. + * + * @param type + * the type of event (eg: "mousemove", "keydown", etc...) + * @param options + * the options for the event (these are event-specific) + */ + simulate(type: string, options?: any): void; +} diff --git a/jquery.sortElements/jquery.sortElement.d.ts b/jquery.sortElements/jquery.sortElement.d.ts index d558e023af..a9768fc972 100644 --- a/jquery.sortElements/jquery.sortElement.d.ts +++ b/jquery.sortElements/jquery.sortElement.d.ts @@ -1,4 +1,4 @@ -// Typescript type definitions for jQuery.sortElements by James Padolsey +// Type definitions for jQuery.sortElements // Project: http://james.padolsey.com/javascript/sorting-elements-with-jquery/ // Definitions by: Tim Bureck // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,4 +7,4 @@ interface JQuery { sortElements(comparator:Function, getSortable?:Function):JQuery; -} \ No newline at end of file +} diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 95fed2635a..06f19801d5 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -448,11 +448,6 @@ function test_toggle() { }); } -function test_easing() { - var result: number = $.easing.linear(3); - var result: number = $.easing.swing(3); -} - function test_append() { $('.inner').append('

Test

'); $('.container').append($('h2')); @@ -573,7 +568,7 @@ function test_bind() { $("form").bind("submit", function (event) { event.stopPropagation(); }); - $("p").bind("myCustomEvent", function (e, myName, myValue) { + $("p").bind("myCustomEvent", function (e, myName?, myValue?) { $(this).text(myName + ", hi there!"); $("span").stop().css("opacity", 1) .text("myName = " + myName) @@ -595,6 +590,70 @@ function test_bind() { }); } +function test_unbind() { + $("#foo").unbind(); + + $("#foo").unbind("click"); + + var handler = function () { + alert("The quick brown fox jumps over the lazy dog."); + }; + $("#foo").bind("click", handler); + $("#foo").unbind("click", handler); + + $("#foo").bind("click", function () { + alert("The quick brown fox jumps over the lazy dog."); + }); + + // Will NOT work + $("#foo").unbind("click", function () { + alert("The quick brown fox jumps over the lazy dog."); + }); + + $("#foo").bind("click.myEvents", handler); + + $("#foo").unbind("click"); + + $("#foo").unbind("click.myEvents"); + + $("#foo").unbind(".myEvents"); + + var timesClicked = 0; + $("#foo").bind("click", function (event) { + alert("The quick brown fox jumps over the lazy dog."); + timesClicked++; + if (timesClicked >= 3) { + $(this).unbind(event); + } + }); + + function aClick() { + $("div").show().fadeOut("slow"); + } + $("#bind").click(function () { + $("#theone") + .bind("click", aClick) + .text("Can Click!"); + }); + $("#unbind").click(function () { + $("#theone") + .unbind("click", aClick) + .text("Does nothing..."); + }); + + $("p").unbind(); + + $("p").unbind("click"); + + var foo = function () { + // Code to handle some kind of event + }; + + $("p").bind("click", foo); // ... Now foo will be called when paragraphs are clicked ... + + $("p").unbind("click", foo); // ... foo will no longer be called. +} + function test_blur() { $('#target').blur(function () { alert('Handler for .blur() called.'); @@ -668,6 +727,11 @@ function test_callbacksFunctions() { callbacks.add(bar); callbacks.fire('world'); callbacks.disable(); + + // Test the disabled state of the list + console.log(callbacks.disabled()); + // Outputs: true + callbacks.empty(); callbacks.fire('hello'); console.log(callbacks.fired()); @@ -754,6 +818,61 @@ function test_submit() { $("#target").submit(); } +function test_trigger() { + + $("#foo").on("click", function () { + alert($(this).text()); + }); + $("#foo").trigger("click"); + + $("#foo").on("custom", function (event, param1?, param2?) { + alert(param1 + "\n" + param2); + }); + $("#foo").trigger("custom", ["Custom", "Event"]); + + $("button:first").click(function () { + update($("span:first")); + }); + + $("button:last").click(function () { + $("button:first").trigger("click"); + update($("span:last")); + }); + + function update(j) { + var n = parseInt(j.text(), 10); + j.text(n + 1); + } + + $("form:first").trigger("submit"); + + var event = jQuery.Event("submit"); + $("form:first").trigger(event); + if (event.isDefaultPrevented()) { + // Perform an action... + } + + $("p") + .click(function (event, a, b) { + // When a normal click fires, a and b are undefined + // for a trigger like below a refers to "foo" and b refers to "bar" + }) + .trigger("click", ["foo", "bar"]); + + var event = jQuery.Event("logged"); + (event).user = "foo"; + (event).pass = "bar"; + $("body").trigger(event); + + // Adapted from jQuery documentation which may be wrong on this occasion + var event2 = jQuery.Event("logged"); + $("body").trigger(event2, { + type: "logged", + user: "foo", + pass: "bar" + }); +} + function test_clone() { $('.hello').clone().appendTo('.goodbye'); var $elem = $('#elem').data({ "arr": [1] }), @@ -1064,7 +1183,6 @@ function test_delay() { }); } -/* Not existing, but not recommended either function test_delegate() { $("table").delegate("td", "click", function () { $(this).toggleClass("chosen"); @@ -1082,7 +1200,7 @@ function test_delegate() { $("body").delegate("a", "click", function (event) { event.preventDefault(); }); - $("body").delegate("p", "myCustomEvent", function (e, myName, myValue) { + $("body").delegate("p", "myCustomEvent", function (e, myName?, myValue?) { $(this).text("Hi there!"); $("span").stop().css("opacity", 1) .text("myName = " + myName) @@ -1092,7 +1210,48 @@ function test_delegate() { $("p").trigger("myCustomEvent"); }); } -*/ + +function test_undelegate() { + function aClick() { + $("div").show().fadeOut("slow"); + } + $("#bind").click(function () { + $("body") + .delegate("#theone", "click", aClick) + .find("#theone").text("Can Click!"); + }); + $("#unbind").click(function () { + $("body") + .undelegate("#theone", "click", aClick) + .find("#theone").text("Does nothing..."); + }); + + $("p").undelegate(); + + $("p").undelegate("click"); + + var foo = function () { + // Code to handle some kind of event + }; + + // ... Now foo will be called when paragraphs are clicked ... + $("body").delegate("p", "click", foo); + + // ... foo will no longer be called. + $("body").undelegate("p", "click", foo); + + var foo = function () { + // Code to handle some kind of event + }; + + // Delegate events under the ".whatever" namespace + $("form").delegate(":button", "click.whatever", foo); + + $("form").delegate("input[type='text'] ", "keypress.whatever", foo); + + // Unbind all events delegated under the ".whatever" namespace + $("form").undelegate(".whatever"); +} function test_dequeue() { $("button").click(function () { @@ -1718,15 +1877,10 @@ function test_has() { } function test_hasClass() { - $("div#result1").append($("p:first").hasClass("selected")); - $("div#result2").append($("p:last").hasClass("selected")); - $("div#result3").append($("p").hasClass("selected")); - $('#mydiv').hasClass('foo'); - // typescript has a bug to (boolean).toString() - I'll comment this code until typescript team solve this problem. - //$("div#result1").append($("p:first").hasClass("selected").toString()); - //$("div#result2").append($("p:last").hasClass("selected").toString()); - //$("div#result3").append($("p").hasClass("selected").toString()); + $("div#result1").append($("p:first").hasClass("selected").toString()); + $("div#result2").append($("p:last").hasClass("selected").toString()); + $("div#result3").append($("p").hasClass("selected").toString()); } function test_hasData() { @@ -2012,11 +2166,17 @@ function test_index() { function test_innerHeight() { var p = $("p:first"); $("p:last").text("innerHeight:" + p.innerHeight()); + + p.innerHeight(123); + p.innerHeight('123px'); } function test_innerWidth() { var p = $("p:first"); $("p:last").text("innerWidth:" + p.innerWidth()); + + p.innerWidth(123); + p.innerWidth('123px'); } function test_outerHeight() { @@ -2024,6 +2184,9 @@ function test_outerHeight() { $("p:last").text( "outerHeight:" + p.outerHeight() + " , outerHeight( true ):" + p.outerHeight(true)); + + p.outerHeight(123); + p.outerHeight('123px'); } function test_outerWidth() { @@ -2031,6 +2194,9 @@ function test_outerWidth() { $("p:last").text( "outerWidth:" + p.outerWidth() + " , outerWidth( true ):" + p.outerWidth(true)); + + p.outerWidth(123); + p.outerWidth('123px'); } function test_scrollLeft() { @@ -2213,7 +2379,7 @@ function test_isEmptyObject() { jQuery.isEmptyObject({ foo: "bar" }); } -function test_isFuction() { +function test_isFunction() { function stub() { }; var objs: any[] = [ function () { }, @@ -2316,6 +2482,27 @@ function test_jQuery() { }); } +function test_fn_extend() { + jQuery.fn.extend({ + check: function () { + return this.each(function () { + this.checked = true; + }); + }, + uncheck: function () { + return this.each(function () { + this.checked = false; + }); + } + }); + + // Use the newly created .check() method + //$( "input[type='checkbox']" ).check(); + // The above test cannot be run as no way that I know of in TypeScript to model the augmentation of jQueryStatic with dynamically added methods + // The below would only work at runtime if extend had first been called. + $("input[type='checkbox']")["check"](); +} + function test_jquery() { var a = { what: "A regular JS object" }, b = $('body'); @@ -2422,6 +2609,16 @@ function test_jquery() { jQuery(function ($) { // Your code using failsafe $ alias here... }); + + $(document.body) + .click(function () { + $(document.body).append($("
")); + var n = $("div").length; + $("span").text("There are " + n + " divs." + + "Click to add more."); + }) + // Trigger the click to start + .trigger("click"); } function test_keydown() { diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 9fc3b1dffb..958128e2c1 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1,3 +1,8 @@ +// Type definitions for jQuery 1.10.x / 2.0.x +// Project: http://jquery.com/ +// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton, Diullei Gomes , Tass Iliopoulos , Jason Swearingen, Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /* ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use @@ -13,10 +18,6 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -// Typing for the jQuery library, version 1.10.x / 2.0.x -// Project: http://jquery.com/ -// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton, Diullei Gomes , Tass Iliopoulos , Jason Swearingen, Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly -// Definitions: https://github.com/borisyankov/DefinitelyTyped /** * Interface for the AJAX setting that will configure the AJAX request @@ -99,7 +100,7 @@ interface JQueryAjaxSettings { /** * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } */ - jsonp?: string; + jsonp?: any; /** * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. */ @@ -158,28 +159,98 @@ interface JQueryAjaxSettings { xhrFields?: { [key: string]: any; }; } -/* - Interface for the jqXHR object -*/ +/** + * Interface for the jqXHR object + */ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { + /** + * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). + */ overrideMimeType(mimeType: string): any; abort(statusText?: string): void; } -/* - Interface for the JQuery callback -*/ +/** + * Interface for the JQuery callback + */ interface JQueryCallback { - add(...callbacks: any[]): any; - disable(): any; - empty(): any; - fire(...arguments: any[]): any; + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function): JQueryCallback; + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function[]): JQueryCallback; + + /** + * Disable a callback list from doing anything more. + */ + disable(): JQueryCallback; + + /** + * Determine if the callbacks list has been disabled. + */ + disabled(): boolean; + + /** + * Remove all of the callbacks from a list. + */ + empty(): JQueryCallback; + + /** + * Call all of the callbacks with the given arguments + * + * @param arguments The argument or list of arguments to pass back to the callback list. + */ + fire(...arguments: any[]): JQueryCallback; + + /** + * Determine if the callbacks have already been called at least once. + */ fired(): boolean; - fireWith(context: any, ...args: any[]): any; - has(callback: any): boolean; - lock(): any; + + /** + * Call all callbacks in a list with the given context and arguments. + * + * @param context A reference to the context in which the callbacks in the list should be fired. + * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. + */ + fireWith(context?: any, ...args: any[]): JQueryCallback; + + /** + * Determine whether a supplied callback is in a list + * + * @param callback The callback to search for. + */ + has(callback: Function): boolean; + + /** + * Lock a callback list in its current state. + */ + lock(): JQueryCallback; + + /** + * Determine if the callbacks list has been locked. + */ locked(): boolean; - remove(...callbacks: any[]): any; + + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function): JQueryCallback; + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function[]): JQueryCallback; } /* @@ -415,14 +486,6 @@ interface JQueryAnimationOptions { specialEasing?: Object; } -/** - * The interface used to specify easing functions. - */ -interface JQueryEasing { - linear(p: number): number; - swing(p: number): number; -} - /** * Static members of jQuery (those on $ and jQuery themselves) */ @@ -778,54 +841,183 @@ interface JQueryStatic { Event: JQueryEventConstructor; - // Internals + /** + * Takes a string and throws an exception containing it. + * + * @param message The message to send out. + */ error(message: any): JQuery; - // Miscellaneous expr: any; fn: any; //TODO: Decide how we want to type this + isReady: boolean; // Properties support: JQuerySupport; - // Utilities + /** + * Check to see if a DOM element is a descendant of another DOM element. + * + * @param container The DOM element that may contain the other element. + * @param contained The DOM element that may be contained by (a descendant of) the other element. + */ contains(container: Element, contained: Element): boolean; - each(collection: any, callback: (indexInArray: any, valueOfElement: any) => any): any; - each(collection: JQuery, callback: (indexInArray: number, valueOfElement: HTMLElement) => any): any; - each(collection: T[], callback: (indexInArray: number, valueOfElement: T) => any): any; + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: T[], + callback: (indexInArray: number, valueOfElement: T) => any + ): any; - extend(target: any, ...objs: any[]): any; - extend(deep: boolean, target: any, ...objs: any[]): any; + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: any, + callback: (indexInArray: any, valueOfElement: any) => any + ): any; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(target: any, object1?: any, ...objectN: any[]): any; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; + + /** + * Execute some JavaScript code globally. + * + * @param code The JavaScript code to execute. + */ globalEval(code: string): any; + /** + * Finds the elements of an array which satisfy a filter function. The original array is not affected. + * + * @param array The array to search through. + * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. + * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. + */ grep(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; + /** + * Search for a specified value within an array and return its index (or -1 if not found). + * + * @param value The value to search for. + * @param array An array through which to search. + * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. + */ inArray(value: T, array: T[], fromIndex?: number): number; + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + */ isArray(obj: any): boolean; + /** + * Check to see if an object is empty (contains no enumerable properties). + * + * @param obj The object that will be checked to see if it's empty. + */ isEmptyObject(obj: any): boolean; + /** + * Determine if the argument passed is a Javascript function object. + * + * @param obj Object to test whether or not it is a function. + */ isFunction(obj: any): boolean; + /** + * Determines whether its argument is a number. + * + * @param obj The value to be tested. + */ isNumeric(value: any): boolean; + /** + * Check to see if an object is a plain object (created using "{}" or "new Object"). + * + * @param obj The object that will be checked to see if it's a plain object. + */ isPlainObject(obj: any): boolean; + /** + * Determine whether the argument is a window. + * + * @param obj Object to test whether or not it is a window. + */ isWindow(obj: any): boolean; + /** + * Check to see if a DOM node is within an XML document (or is an XML document). + * + * @param node he DOM node that will be checked to see if it's in an XML document. + */ isXMLDoc(node: Node): boolean; + /** + * Convert an array-like object into a true JavaScript array. + * + * @param obj Any object to turn into a native Array. + */ makeArray(obj: any): any[]; + /** + * Translate all items in an array or object to new array of items. + * + * @param array The Array to translate. + * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. + */ map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; - map(array: any, callback: (elementOfArray: any, indexInArray: any) => any): any; + /** + * Translate all items in an array or object to new array of items. + * + * @param arrayOrObject The Array or Object to translate. + * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. + */ + map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any; + /** + * Merge the contents of two arrays together into the first array. + * + * @param first The first array to merge, the elements of second added. + * @param second The second array to merge into the first, unaltered. + */ merge(first: T[], second: T[]): T[]; - merge(first: T[], second: U[]): any[]; + /** + * An empty function. + */ noop(): any; + /** + * Return a number representing the current time. + */ now(): number; - parseJSON(json: string): any; + /** + * Takes a well-formed JSON string and returns the resulting JavaScript object. + * + * @param json The JSON string to parse. + */ + parseJSON(json: string): Object; /** * Parses a string into an XML document. @@ -834,13 +1026,26 @@ interface JQueryStatic { */ parseXML(data: string): XMLDocument; - queue(element: Element, queueName: string, newQueue: any[]): JQuery; - + /** + * Remove the whitespace from the beginning and end of a string. + * + * @param str Remove the whitespace from the beginning and end of a string. + */ trim(str: string): string; + /** + * Determine the internal JavaScript [[Class]] of an object. + * + * @param obj Object to get the internal JavaScript [[Class]] of. + */ type(obj: any): string; - unique(arr: any[]): any[]; + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. + * + * @param array The Array of DOM elements. + */ + unique(array: Element[]): Element[]; /** * Parses a string into an array of DOM nodes. @@ -850,10 +1055,6 @@ interface JQueryStatic { * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string */ parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; - - Animation(elem: any, properties: any, options: any): any; - - easing: JQueryEasing; } /** @@ -1217,11 +1418,39 @@ interface JQuery { */ innerHeight(): number; + /** + * Sets the inner height on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerHeight(height: number): JQuery; + + /** + * Sets the inner height on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerHeight(height: string): JQuery; + /** * Get the current computed width for the first element in the set of matched elements, including padding but not border. */ innerWidth(): number; + /** + * Sets the inner width on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerWidth(width: number): JQuery; + + /** + * Sets the inner width on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerWidth(width: string): JQuery; + /** * Get the current coordinates of the first element in the set of matched elements, relative to the document. */ @@ -1246,6 +1475,20 @@ interface JQuery { */ outerHeight(includeMargin?: boolean): number; + /** + * Sets the outer height on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerHeight(height: number): JQuery; + + /** + * Sets the outer height on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerHeight(height: string): JQuery; + /** * Get the current computed width for the first element in the set of matched elements, including padding and border. * @@ -1253,6 +1496,20 @@ interface JQuery { */ outerWidth(includeMargin?: boolean): number; + /** + * Sets the outer width on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerWidth(width: number): JQuery; + + /** + * Sets the outer width on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerWidth(width: string): JQuery; + /** * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. */ @@ -1827,14 +2084,59 @@ interface JQuery { */ toggle(showOrHide: boolean): JQuery; - // Events + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + */ bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ bind(eventType: string, preventBubble: boolean): JQuery; - bind(...events: any[]): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param events An object containing one or more DOM event types and functions to execute for them. + */ + bind(events: any): JQuery; + /** + * Trigger the "blur" event on an element + */ + blur(): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ blur(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** @@ -2330,41 +2632,248 @@ interface JQuery { */ submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - trigger(eventType: string, ...extraParameters: any[]): JQuery; - trigger(event: JQueryEventObject): JQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(eventType: string, extraParameters?: any[]): JQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(eventType: string, extraParameters?: Object): JQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param event A jQuery.Event object. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(event: JQueryEventObject, extraParameters?: any[]): JQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param event A jQuery.Event object. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(event: JQueryEventObject, extraParameters?: Object): JQuery; + /** + * Execute all handlers attached to an element for an event. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ triggerHandler(eventType: string, ...extraParameters: any[]): Object; + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param handler The function that is to be no longer executed. + */ unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). + */ unbind(eventType: string, fls: boolean): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param evt A JavaScript event object as passed to an event handler. + */ unbind(evt: any): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + */ undelegate(): JQuery; - undelegate(selector: any, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - undelegate(selector: any, events: any): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" + * @param handler A function to execute at the time the event is triggered. + */ + undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param events An object of one or more event types and previously bound functions to unbind from them. + */ + undelegate(selector: string, events: Object): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param namespace A string containing a namespace to unbind all events from. + */ undelegate(namespace: string): JQuery; + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ unload(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - // Internals + /** + * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) + */ context: Element; + jquery: string; + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ error(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + */ pushStack(elements: any[]): JQuery; - pushStack(elements: any[], name: any, arguments: any): JQuery; + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + * @param name The name of a jQuery method that generated the array of elements. + * @param arguments The arguments that were passed in to the jQuery method (for serialization). + */ + pushStack(elements: any[], name: string, arguments: any[]): JQuery; - // Manipulation - after(...content: any[]): JQuery; - after(func: (index: any) => any): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: JQuery, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: any[], ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: Element, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: Text, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + after(func: (index: number) => any): JQuery; - append(...content: any[]): JQuery; - append(func: (index: any, html: any) => any): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: JQuery, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: any[], ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: Element, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: Text, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + append(func: (index: number, html: string) => any): JQuery; - appendTo(target: any): JQuery; + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: JQuery): JQuery; + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: any[]): JQuery; + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: Element): JQuery; + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: string): JQuery; before(...content: any[]): JQuery; before(func: (index: any) => any): JQuery; @@ -2405,8 +2914,12 @@ interface JQuery { wrapInner(wrappingElement: any): JQuery; wrapInner(func: (index: any) => any): JQuery; - // Miscellaneous - each(func: (index: any, elem: Element) => any): JQuery; + /** + * Iterate over a jQuery object, executing a function for each matched element. + * + * @param func A function to execute for each matched element. + */ + each(func: (index: number, elem: Element) => any): JQuery; get(index?: number): any; diff --git a/jquerymobile/jquerymobile-tests.ts b/jquerymobile/jquerymobile-tests.ts index 19231849f4..b28d308a02 100644 --- a/jquerymobile/jquerymobile-tests.ts +++ b/jquerymobile/jquerymobile-tests.ts @@ -71,7 +71,7 @@ function test_pagesDialogs() { } }); - $(document).bind("pagebeforechange", function (e, data) { + $(document).bind("pagebeforechange", function (e, data?) { if (typeof data.toPage === "string") { var u = $.mobile.path.parseUrl(data.toPage), re = /^#category-item/; diff --git a/jquerymobile/jquerymobile.d.ts b/jquerymobile/jquerymobile.d.ts index d81e439009..ebcaac48fa 100644 --- a/jquerymobile/jquerymobile.d.ts +++ b/jquerymobile/jquerymobile.d.ts @@ -202,6 +202,18 @@ interface ListViewEvents { create?: JQueryMobileEvent; } +interface FilterableOptions { + children?: any; + defaults?: boolean; + disabled?: boolean; + enhanced?: boolean; + filterCallback?: {(index: number, searchValue?: string): boolean; }; + filterPlaceholder?: string; + filterReveal?: boolean; + filterTheme?: string; + input: any; +} + interface NavbarOptions { iconpos: string; } @@ -371,6 +383,7 @@ interface JQueryMobile extends JQueryMobileOptions { checkboxradio: any; selectmenu: any; listview: any; + filterable: any; defaultHomeScroll: number; } @@ -446,6 +459,10 @@ interface JQuery { listview(options: ListViewOptions): JQuery; listview(events: ListViewEvents): JQuery; + filterable(): JQuery; + filterable(command: string): JQuery; + filterable(options: FilterableOptions): JQuery; + navbar(options?: NavbarOptions): JQuery; table(): JQuery; diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 3a1823a920..41cc3214df 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -714,7 +714,7 @@ declare module JQueryUI { distance?: number; } - interface keyCode { + interface KeyCode { BACKSPACE: number; COMMA: number; DELETE: number; @@ -751,7 +751,7 @@ declare module JQueryUI { buttonset: Button; datepicker: Datepicker; dialog: Dialog; - keyCode: keyCode; + keyCode: KeyCode; menu: Menu; progressbar: Progressbar; slider: Slider; diff --git a/jsfl/jsfl.d.ts b/jsfl/jsfl.d.ts index 94e3d4d80d..a8c9911d27 100644 --- a/jsfl/jsfl.d.ts +++ b/jsfl/jsfl.d.ts @@ -1,3 +1,8 @@ +// Type definitions for JSFL +// Project: https://adobe.com +// Definitions by: soywiz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + interface FlashPoint { x: number; y: number; @@ -169,7 +174,7 @@ interface FlashDocument { /** Exports the currently active profile to an XML */ exportPublishProfile(fileURI: string): void; - /** returns a string that specifies, in XML format, the specified profile. If you dont pass a value for profileName, the current profile is exported. */ + /** returns a string that specifies, in XML format, the specified profile. If you don't pass a value for profileName, the current profile is exported. */ exportPublishProfileString(profileName?: string): string; /** Exports the document in the Flash SWF format. */ @@ -1030,7 +1035,7 @@ interface FlashTimeline { /** Creates a new motion object at a designated start and end frame. */ createMotionObject(startFrameIndex?: number, endFrameIndex?: number): void; - /** Sets the frame.tweenType property to motion for each selected keyframe on the current layer, and converts each frames contents to a single symbol instance if necessary. */ + /** Sets the frame.tweenType property to motion for each selected keyframe on the current layer, and converts each frame's contents to a single symbol instance if necessary. */ createMotionTween(startFrameIndex?: number, endFrameIndex?: number): void; /** Cuts a range of frames on the current layer from the timeline and saves them to the clipboard. */ @@ -1051,13 +1056,13 @@ interface FlashTimeline { /** Finds an array of indexes for the layers with the given name. */ findLayerIndex(name: string): number[]; - /** Retrieves the specified propertys value for the selected frames. */ + /** Retrieves the specified property's value for the selected frames. */ getFrameProperty(property: string, startframeIndex?: number, endFrameIndex?: number): any; /** Returns an XML string that represents the current positions of the horizontal and vertical guide lines for a timeline(View > Guides > Show Guides). */ getGuidelines(): string; - /** Retrieves the specified propertys value for the selected layers. */ + /** Retrieves the specified property's value for the selected layers. */ getLayerProperty(property: string): any; /** Retrieves the currently selected frames in an array. */ @@ -1144,9 +1149,9 @@ interface FlashTimeline { } interface FlashPath { - /// Appends a cubic Bzier curve segment to the path. + /// Appends a cubic Bézier curve segment to the path. addCubicCurve(xAnchor: number, yAnchor: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): void; - /// Appends a quadratic Bzier segment to the path. + /// Appends a quadratic Bézier segment to the path. addCurve(xAnchor: number, yAnchor: number, x2: number, y2: number, x3: number, y3: number): void; /// Adds a point to the path. addPoint(x: number, y: number): void; @@ -1396,4 +1401,4 @@ declare var fl: FlashFL; declare var FLfile: FlashFLfile; declare function alert(alertText: string): void; declare function confirm(strAlert: string): boolean; -declare function prompt(promptMsg: string, text?: string): string; \ No newline at end of file +declare function prompt(promptMsg: string, text?: string): string; diff --git a/jsfl/xJSFL.d.ts b/jsfl/xJSFL.d.ts index 7db97360b0..bc3af28c5e 100644 --- a/jsfl/xJSFL.d.ts +++ b/jsfl/xJSFL.d.ts @@ -1,3 +1,8 @@ +// Type definitions for xJSFL +// Project: http://www.xjsfl.com/ +// Definitions by: soywiz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// interface _xjsfl { diff --git a/jsoneditoronline/jsoneditoronline.d.ts b/jsoneditoronline/jsoneditoronline.d.ts index 64ce20bf1a..171fca2d53 100644 --- a/jsoneditoronline/jsoneditoronline.d.ts +++ b/jsoneditoronline/jsoneditoronline.d.ts @@ -1,9 +1,10 @@ // Type definitions for JSONEditorOnline -// JSON Editor Online is a tool to easily edit and format JSON online. JSON is displayed in a clear, editable treeview and in formatted plain text. // Project: https://github.com/josdejong/jsoneditoronline // Definitions by: Vincent Bortone // Definitions: https://github.com/borisyankov/DefinitelyTyped +// JSON Editor Online is a tool to easily edit and format JSON online. JSON is displayed in a clear, editable treeview and in formatted plain text. + interface JSONEditorOptions { change?: () => void; history?: boolean; @@ -177,4 +178,4 @@ declare class JSONFormatter { setText(jsonString: string): void; getText(): string; onError(err: string): void; -} \ No newline at end of file +} diff --git a/jsplumb/jquery.jsPlumb.d.ts b/jsplumb/jquery.jsPlumb.d.ts index 6561f2960a..ed7bc8452f 100644 --- a/jsplumb/jquery.jsPlumb.d.ts +++ b/jsplumb/jquery.jsPlumb.d.ts @@ -1,9 +1,7 @@ // Type definitions for jsPlumb 1.3.16 jQuery adapter. // Project: http://jsplumb.org -// https://github.com/sporritt/jsplumb -// https://code.google.com/p/jsplumb -// // Definitions by: Steve Shearn +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -104,4 +102,4 @@ interface SelectParams { scope?: string; source: string; target: string; -} \ No newline at end of file +} diff --git a/jwplayer/jwplayer.d.ts b/jwplayer/jwplayer.d.ts index 2540ce9d1a..be4ab4fd36 100644 --- a/jwplayer/jwplayer.d.ts +++ b/jwplayer/jwplayer.d.ts @@ -1,9 +1,10 @@ // Type definitions for JW Player -// JW Player is the leading HTML5 & Flash video player, optimized for mobile and the desktop. Easy enough for beginners, advanced enough for pros. // Project: http://developer.longtailvideo.com/trac/ // Definitions by: Martin Duparc // Definitions: https://github.com/borisyankov/DefinitelyTyped +// JW Player is the leading HTML5 & Flash video player, optimized for mobile and the desktop. Easy enough for beginners, advanced enough for pros. + interface JWPlayer { addButton(icon: string, label: string, handler: () => void, id: string): void; getBuffer(): number; diff --git a/keyboardjs/keyboardjs.d.ts b/keyboardjs/keyboardjs.d.ts index 150f0e3901..dfafd30a8a 100644 --- a/keyboardjs/keyboardjs.d.ts +++ b/keyboardjs/keyboardjs.d.ts @@ -1,9 +1,10 @@ // Type definitions for KeyboardJS -// A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts. // Project: https://github.com/RobertWHurst/KeyboardJS // Definitions by: Vincent Bortone // Definitions: https://github.com/borisyankov/DefinitelyTyped +// A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts. + interface KeyboardJSSubBinding { clear(): void; } @@ -46,4 +47,4 @@ interface KeyboardJSStatic { }; } -declare var KeyboardJS: KeyboardJSStatic; \ No newline at end of file +declare var KeyboardJS: KeyboardJSStatic; diff --git a/knockback/knockback.d.ts b/knockback/knockback.d.ts index 55657672eb..50848e6841 100644 --- a/knockback/knockback.d.ts +++ b/knockback/knockback.d.ts @@ -1,4 +1,9 @@ -/// +// Type definitions for Knockback.js +// Project: http://kmalakoff.github.io/knockback/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// /// declare module Knockback { @@ -215,4 +220,4 @@ declare module Knockback { } -declare var kb: Knockback.Static; \ No newline at end of file +declare var kb: Knockback.Static; diff --git a/knockout.deferred.updates/knockout.deferred.updates.d.ts b/knockout.deferred.updates/knockout.deferred.updates.d.ts index 1d9313dcee..e3423f5e90 100644 --- a/knockout.deferred.updates/knockout.deferred.updates.d.ts +++ b/knockout.deferred.updates/knockout.deferred.updates.d.ts @@ -21,7 +21,7 @@ interface KnockoutStatic { } // Observables -interface KnockoutSubscribableFunctions { +interface KnockoutSubscribableFunctions { deferUpdates: boolean; } diff --git a/knockout.editables/ko.editables.d.ts b/knockout.editables/ko.editables.d.ts index e072965b21..b6da1f13f6 100644 --- a/knockout.editables/ko.editables.d.ts +++ b/knockout.editables/ko.editables.d.ts @@ -1,7 +1,9 @@ -/// +// Type definitions for knockout-editables 0.9 +// Project:http://romanych.github.com/ko.editables/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped -// build: ko.editables 0.9 -// http://romanych.github.com/ko.editables/ +/// // bestowed by ko.editable(target) interface KnockoutEditable { @@ -27,4 +29,4 @@ interface KnockoutEditableStatic { // extend ko global interface KnockoutStatic { editable: KnockoutEditableStatic; -} \ No newline at end of file +} diff --git a/knockout.es5/knockout.es5.d.ts b/knockout.es5/knockout.es5.d.ts index 868655545e..651d7d40f3 100644 --- a/knockout.es5/knockout.es5.d.ts +++ b/knockout.es5/knockout.es5.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Knockout-ES5 +// Type definitions for Knockout-ES5 // Project: https://github.com/SteveSanderson/knockout-es5 // Definitions by: Sebastián Galiano // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/knockout.kogrid/knockout.kogrid-tests.ts b/knockout.kogrid/knockout.kogrid-tests.ts index 94c061156d..54dde59e1d 100644 --- a/knockout.kogrid/knockout.kogrid-tests.ts +++ b/knockout.kogrid/knockout.kogrid-tests.ts @@ -19,7 +19,7 @@ module KoGridTests } public createDefaultGridOptions(dataArray: KnockoutObservableArray, selectedItems: KnockoutObservableArray): kg.GridOptions { - var result = { + return { data: dataArray, displaySelectionCheckbox: false, footerVisible: false, @@ -28,7 +28,6 @@ module KoGridTests plugins: null, selectedItems: selectedItems }; - return result; } } } \ No newline at end of file diff --git a/knockout.kogrid/ko-grid.d.ts b/knockout.kogrid/ko-grid.d.ts index c8d1b27c1c..2e5f255380 100644 --- a/knockout.kogrid/ko-grid.d.ts +++ b/knockout.kogrid/ko-grid.d.ts @@ -1,6 +1,7 @@ // Type definitions for ko-grid // Project: http://knockout-contrib.github.io/KoGrid/ -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: huer12 +// Definitions: https://github.com/borisyankov/DefinitelyTyped // These are very definitely preliminary. Please feel free to improve. @@ -189,4 +190,4 @@ declare module kg { /** currentPage: the uhm... current page. */ currentPage?: number; } -} \ No newline at end of file +} diff --git a/knockout.postbox/knockout-postbox.d.ts b/knockout.postbox/knockout-postbox.d.ts index daa35458ab..65f0bbf132 100644 --- a/knockout.postbox/knockout-postbox.d.ts +++ b/knockout.postbox/knockout-postbox.d.ts @@ -20,11 +20,11 @@ interface KnockoutObservable { } interface KnockoutObservableArray { - subscribeTo(topic: string, useLastPublishedValueToInitialize?: boolean, transform?: (val: any) => T): KnockoutObservableArray; + subscribeTo(topic: string, useLastPublishedValueToInitialize?: boolean, transform?: (val: any) => any /* T */): KnockoutObservableArray; unsubscribeFrom(topic: string): KnockoutObservableArray; - publishOn(topic: string, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservableArray; + publishOn(topic: string, skipInitialPublish?: boolean, equalityComparer?: (newValue: any /* T */, oldValue: any /* T */) => boolean): KnockoutObservableArray; stopPublishingOn(topic: string): KnockoutObservableArray; - syncWith(topic: string, initializeWithLatestValue?: boolean, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservableArray; + syncWith(topic: string, initializeWithLatestValue?: boolean, skipInitialPublish?: boolean, equalityComparer?: (newValue: any /* T */, oldValue: any /* T */) => boolean): KnockoutObservableArray; } interface KnockoutStatic { diff --git a/knockout.projections/knockout.projections.d.ts b/knockout.projections/knockout.projections.d.ts index 5e85308a9d..77f3bf0ec8 100644 --- a/knockout.projections/knockout.projections.d.ts +++ b/knockout.projections/knockout.projections.d.ts @@ -1,6 +1,7 @@ // Type definitions for knockout-projections 1.0.0 // Project: https://github.com/stevesanderson/knockout-projections // Definitions by: John Reilly +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/knockout.rx/knockout.rx-tests.ts b/knockout.rx/knockout.rx-tests.ts index 674e9bb6a4..21a0a52484 100644 --- a/knockout.rx/knockout.rx-tests.ts +++ b/knockout.rx/knockout.rx-tests.ts @@ -1,6 +1,6 @@ /// -var ax: Rx.IObservable; +var ax: Rx.Observable; var ao = ax.toKoObservable(); diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index e9c85a7f80..f897bc7619 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -1,25 +1,26 @@ // Type definitions for knockout.rx 0.1 // Project: https://github.com/Igorbek/knockout.rx // Definitions by: Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// /// interface KnockoutSubscribableFunctions { - toObservable(event?: string): Rx.IObservable; - toObservable(event: string): Rx.IObservable; + toObservable(event?: string): Rx.Observable; + toObservable(event: string): Rx.Observable; } interface KnockoutObservableFunctions { - toObservableWithReplyLatest(): Rx.IObservable; + toObservableWithReplyLatest(): Rx.Observable; } interface KnockoutComputedFunctions { - toObservableWithReplyLatest(): Rx.IObservable; + toObservableWithReplyLatest(): Rx.Observable; } declare module Rx { - interface IObservable { + interface Observable { toKoSubscribable(): KnockoutSubscribable; toKoObservable(initialValue?: T): KnockoutObservable; } diff --git a/knockout.validation/knockout.validation.d.ts b/knockout.validation/knockout.validation.d.ts index 2e00c5223d..e65ec67439 100644 --- a/knockout.validation/knockout.validation.d.ts +++ b/knockout.validation/knockout.validation.d.ts @@ -138,7 +138,7 @@ interface KnockoutStatic { applyBindingsWithValidation(viewModel: any, rootNode?: any, options?: KnockoutValidationConfiguration): void; } -interface KnockoutSubscribableFunctions { +interface KnockoutSubscribableFunctions { isValid: KnockoutComputed; isValidating: KnockoutObservable; rules: KnockoutObservableArray; diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index e74012548c..1ebef13ef5 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -38,7 +38,7 @@ function test_computed() { this.firstName = ko.observable('Planet'); this.lastName = ko.observable('Earth'); - this.fullName = ko.computed({ + this.fullName = ko.computed({ read: function () { return this.firstName() + " " + this.lastName(); }, @@ -257,7 +257,7 @@ interface KnockoutExtenders { required(target, overrideMessage); } -interface KnockoutObservableArrayFunctions { +interface KnockoutObservableArrayFunctions { filterByProperty(propName, matchValue): KnockoutComputed; } @@ -491,7 +491,7 @@ function test_mappingplugin() { } // Define your own functions -interface KnockoutSubscribableFunctions { +interface KnockoutSubscribableFunctions { publishOn(topic: string): any; subscribeTo(topic: string): any; } diff --git a/lazy.js/lazy.js-test.ts b/lazy.js/lazy.js-test.ts deleted file mode 100644 index b5252a1bcf..0000000000 --- a/lazy.js/lazy.js-test.ts +++ /dev/null @@ -1,194 +0,0 @@ -/// - -var sequence:LazyJS.Sequence; -var arraySeq:LazyJS.ArrayLikeSequence; -var objectSeq:LazyJS.ObjectLikeSequence; -var asyncSeq:LazyJS.AsyncSequence; -var stringSeq:LazyJS.StringLikeSequence; - -var obj:Object; -var bool:boolean; -var num:number; -var str:string; -var x:any = null; -var arr:any[]; -var exp:RegExp; -var strArr:string[]; -var numArr:string[]; - -function fnCallback():void { -} - -function fnErrorCallback(error:any):void { - -} - -function fnValueCallback(value:any):void { -} - -function fnGetKeyCallback(value:any):string { - return ''; -} - -function fnTestCallback(value:any):boolean { - return false; -} - -function fnMapCallback(value:any):any { - return null; -} - -function fnMapStringCallback(value:string):string { - return ''; -} - -function fnNumberCallback(value:any):number { - return 0; -} - -function fnMemoCallback(memo:any, value:any):any { - return null; -} - -function fnGeneratorCallback(index:number):any { - return null; -} - -// Lazy - -arraySeq = Lazy([]); -objectSeq = Lazy({}); -stringSeq = Lazy(''); - -// Strict - -var Strict = Lazy.strict(); -arraySeq = Strict([1,2,num]).pop(); - -// Sequence - -asyncSeq = sequence.async(num); -sequence = sequence.chunk(num); -sequence = sequence.compact(); -sequence = sequence.concat(arr); -sequence = sequence.consecutive(num); -bool = sequence.contains(x); -sequence = sequence.countBy(str); -sequence = sequence.countBy(fnGetKeyCallback); -sequence = sequence.dropWhile(fnTestCallback); -sequence = sequence.each(fnValueCallback); -bool = sequence.every(fnTestCallback); -sequence = sequence.filter(fnTestCallback); -sequence = sequence.find(fnTestCallback); -sequence = sequence.findWhere(obj); - -x = sequence.first(); -sequence= sequence.first(num); - -sequence = sequence.flatten(); -objectSeq = sequence.groupBy(fnGetKeyCallback); -sequence = sequence.indexOf(x); -sequence = sequence.initial(); -sequence = sequence.initial(num); -sequence = sequence.intersection(arr); -sequence = sequence.invoke(str); -bool = sequence.isEmpty(); -str = sequence.join(); -str = sequence.join(str); - -x = sequence.last(); -sequence = sequence.last(num); - -sequence = sequence.lastIndexOf(x); -sequence = sequence.map(fnMapCallback); -x = sequence.max(); -x = sequence.max(fnNumberCallback); -x = sequence.min(); -x = sequence.min(fnNumberCallback); -sequence = sequence.pluck(str); -x = sequence.reduce(fnMemoCallback); -x = sequence.reduce(fnMemoCallback, x); -x = sequence.reduceRight(fnMemoCallback, x); -sequence = sequence.reject(fnTestCallback); -sequence = sequence.rest(num); -sequence = sequence.reverse(); -sequence = sequence.shuffle(); -bool = sequence.some(); -bool = sequence.some(fnTestCallback); -sequence = sequence.sortBy(fnNumberCallback); -sequence = sequence.sortedIndex(x); -sequence = sequence.sum(); -sequence = sequence.sum(fnNumberCallback); -sequence = sequence.takeWhile(fnTestCallback); -sequence = sequence.union(arr); -sequence = sequence.uniq(); -sequence = sequence.where(obj); -sequence = sequence.without(arr); -sequence = sequence.zip(arr); - -arr = sequence.toArray(); -obj = sequence.toObject(); - - -// ArrayLikeSequence - -arraySeq = arraySeq.concat(); -arraySeq = arraySeq.first(); -arraySeq = arraySeq.first(num); -x = arraySeq.get(num); -num = arraySeq.length(); -arraySeq = arraySeq.map(fnMapCallback); -arraySeq = arraySeq.pop(); -arraySeq = arraySeq.rest(); -arraySeq = arraySeq.rest(num); -arraySeq = arraySeq.reverse(); -arraySeq = arraySeq.shift(); -arraySeq = arraySeq.slice(num); -arraySeq = arraySeq.slice(num, num); - - -// ObjectLikeSequence - -objectSeq = objectSeq.defaults(obj); -sequence = objectSeq.functions(); -objectSeq = objectSeq.get(str); -objectSeq = objectSeq.invert(); -sequence = objectSeq.keys(); -objectSeq = objectSeq.omit(strArr); -sequence = objectSeq.pairs(); -objectSeq = objectSeq.pick(strArr); -arr = objectSeq.toArray(); -obj = objectSeq.toObject(); -sequence = objectSeq.values(); - - -// StringLikeSequence - -str = stringSeq.charAt(num); -num = stringSeq.charCodeAt(num); -bool = stringSeq.contains(str); -bool = stringSeq.endsWith(str); - -str = stringSeq.first(); -stringSeq = stringSeq.first(num); - -num = stringSeq.indexOf(str); -num = stringSeq.indexOf(str, num); - -str = stringSeq.last(); -stringSeq = stringSeq.last(num); - -num = stringSeq.lastIndexOf(str); -num = stringSeq.lastIndexOf(str, num); -stringSeq = stringSeq.mapString(fnMapStringCallback); -stringSeq = stringSeq.match(exp); -stringSeq = stringSeq.reverse(); - -sequence = stringSeq.split(str); -sequence = stringSeq.split(exp); - -bool = stringSeq.startsWith(str); -stringSeq = stringSeq.substring(num); -stringSeq = stringSeq.substring(num, num); -stringSeq = stringSeq.toLowerCase(); -stringSeq = stringSeq.toUpperCase(); diff --git a/lazy.js/lazy.js-tests.ts b/lazy.js/lazy.js-tests.ts new file mode 100644 index 0000000000..356ee177b5 --- /dev/null +++ b/lazy.js/lazy.js-tests.ts @@ -0,0 +1,191 @@ +/// + +var sequence: LazyJS.Sequence; +var arraySeq: LazyJS.ArrayLikeSequence; +var objectSeq: LazyJS.ObjectLikeSequence; +var asyncSeq: LazyJS.AsyncSequence; +var stringSeq: LazyJS.StringLikeSequence; + +var obj: Object; +var bool: boolean; +var num: number; +var str: string; +var x: any = null; +var arr: any[]; +var exp: RegExp; +var strArr: string[]; +var numArr: string[]; + +function fnCallback(): void { +} + +function fnErrorCallback(error: any): void { + +} + +function fnValueCallback(value: any): void { +} + +function fnGetKeyCallback(value: any): string { + return ''; +} + +function fnTestCallback(value: any): boolean { + return false; +} + +function fnMapCallback(value: any): any { + return null; +} + +function fnMapStringCallback(value: string): string { + return ''; +} + +function fnNumberCallback(value: any): number { + return 0; +} + +function fnMemoCallback(memo: any, value: any): any { + return null; +} + +function fnGeneratorCallback(index: number): any { + return null; +} + +// Lazy + +arraySeq = Lazy([]); +objectSeq = Lazy({}); +stringSeq = Lazy(''); + +// Strict + +var Strict = Lazy.strict(); +arraySeq = Strict([1, 2, num]).pop(); + +// Sequence + +asyncSeq = sequence.async(num); +sequence = sequence.chunk(num); +sequence = sequence.compact(); +sequence = sequence.concat(arr); +sequence = sequence.consecutive(num); +bool = sequence.contains(x); +sequence = sequence.countBy(str); +sequence = sequence.countBy(fnGetKeyCallback); +sequence = sequence.dropWhile(fnTestCallback); +sequence = sequence.each(fnValueCallback); +bool = sequence.every(fnTestCallback); +sequence = sequence.filter(fnTestCallback); +sequence = sequence.find(fnTestCallback); +sequence = sequence.findWhere(obj); + +x = sequence.first(); +sequence = sequence.first(num); + +sequence = sequence.flatten(); +objectSeq = sequence.groupBy(fnGetKeyCallback); +sequence = sequence.indexOf(x); +sequence = sequence.initial(); +sequence = sequence.initial(num); +sequence = sequence.intersection(arr); +sequence = sequence.invoke(str); +bool = sequence.isEmpty(); +str = sequence.join(); +str = sequence.join(str); + +x = sequence.last(); +sequence = sequence.last(num); + +sequence = sequence.lastIndexOf(x); +sequence = sequence.map(fnMapCallback); +x = sequence.max(); +x = sequence.max(fnNumberCallback); +x = sequence.min(); +x = sequence.min(fnNumberCallback); +sequence = sequence.pluck(str); +x = sequence.reduce(fnMemoCallback); +x = sequence.reduce(fnMemoCallback, x); +x = sequence.reduceRight(fnMemoCallback, x); +sequence = sequence.reject(fnTestCallback); +sequence = sequence.rest(num); +sequence = sequence.reverse(); +sequence = sequence.shuffle(); +bool = sequence.some(); +bool = sequence.some(fnTestCallback); +sequence = sequence.sortBy(fnNumberCallback); +sequence = sequence.sortedIndex(x); +sequence = sequence.sum(); +sequence = sequence.sum(fnNumberCallback); +sequence = sequence.takeWhile(fnTestCallback); +sequence = sequence.union(arr); +sequence = sequence.uniq(); +sequence = sequence.where(obj); +sequence = sequence.without(arr); +sequence = sequence.zip(arr); + +arr = sequence.toArray(); +obj = sequence.toObject(); + +// ArrayLikeSequence + +arraySeq = arraySeq.concat(); +arraySeq = arraySeq.first(); +arraySeq = arraySeq.first(num); +x = arraySeq.get(num); +num = arraySeq.length(); +arraySeq = arraySeq.map(fnMapCallback); +arraySeq = arraySeq.pop(); +arraySeq = arraySeq.rest(); +arraySeq = arraySeq.rest(num); +arraySeq = arraySeq.reverse(); +arraySeq = arraySeq.shift(); +arraySeq = arraySeq.slice(num); +arraySeq = arraySeq.slice(num, num); + +// ObjectLikeSequence + +objectSeq = objectSeq.defaults(obj); +sequence = objectSeq.functions(); +objectSeq = objectSeq.get(str); +objectSeq = objectSeq.invert(); +sequence = objectSeq.keys(); +objectSeq = objectSeq.omit(strArr); +sequence = objectSeq.pairs(); +objectSeq = objectSeq.pick(strArr); +arr = objectSeq.toArray(); +obj = objectSeq.toObject(); +sequence = objectSeq.values(); + +// StringLikeSequence + +str = stringSeq.charAt(num); +num = stringSeq.charCodeAt(num); +bool = stringSeq.contains(str); +bool = stringSeq.endsWith(str); + +str = stringSeq.first(); +stringSeq = stringSeq.first(num); + +num = stringSeq.indexOf(str); +num = stringSeq.indexOf(str, num); + +str = stringSeq.last(); +stringSeq = stringSeq.last(num); + +num = stringSeq.lastIndexOf(str); +num = stringSeq.lastIndexOf(str, num); +stringSeq = stringSeq.mapString(fnMapStringCallback); +stringSeq = stringSeq.match(exp); +stringSeq = stringSeq.reverse(); + +sequence = stringSeq.split(str); +sequence = stringSeq.split(exp); + +bool = stringSeq.startsWith(str); +stringSeq = stringSeq.substring(num); +stringSeq = stringSeq.substring(num, num); +stringSeq = stringSeq.toLowerCase(); +stringSeq = stringSeq.toUpperCase(); diff --git a/lazy.js/lazy.js.d.ts b/lazy.js/lazy.js.d.ts index baba46a461..47925bdf94 100644 --- a/lazy.js/lazy.js.d.ts +++ b/lazy.js/lazy.js.d.ts @@ -242,3 +242,7 @@ declare module LazyJS { declare var Lazy:LazyJS.LazyStatic; +declare module 'lazy.js' { +export = Lazy; +} + diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 5462a8afb1..3044970b0c 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -991,9 +991,9 @@ declare module L { export class Default extends Icon { /** - * Creates an icon instance with default options. + * Creates a default icon instance with the given options. */ - constructor(options: IconOptions); + constructor(options?: IconOptions); static imagePath: string; } diff --git a/leapmotionTS/LeapMotionTS.d.ts b/leapmotionTS/LeapMotionTS.d.ts index dac337976d..411409aeca 100644 --- a/leapmotionTS/LeapMotionTS.d.ts +++ b/leapmotionTS/LeapMotionTS.d.ts @@ -1,5 +1,5 @@ -// Type definitions for Leap Motion TS (SDK version 0.7.9) -// Project: https://github.com/logotype/LeapMotionTS and http://www.leapmotion.com +// Type definitions for Leap Motion TS 0.7.9 +// Project: https://github.com/logotype/LeapMotionTS // Definitions by: Victor Norgren // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -295,4 +295,4 @@ export declare class Vector3 { static forward(): Vector3; static backward(): Vector3; public toString(): string; -} \ No newline at end of file +} diff --git a/linq/linq.3.0.3-Beta4.d.ts b/linq/linq.3.0.3-Beta4.d.ts index 77c95d123f..d75d0982bc 100755 --- a/linq/linq.3.0.3-Beta4.d.ts +++ b/linq/linq.3.0.3-Beta4.d.ts @@ -1,6 +1,7 @@ // Type definitions for linq.js, ver 3.0.3-Beta4 // Project: http://linqjs.codeplex.com/ // Definitions by: neuecc (http://www.codeplex.com/site/users/view/neuecc) +// Definitions: https://github.com/borisyankov/DefinitelyTyped declare module linqjs { interface IEnumerator { @@ -192,4 +193,4 @@ declare module linqjs { } // export definition -declare var Enumerable: linqjs.EnumerableStatic; \ No newline at end of file +declare var Enumerable: linqjs.EnumerableStatic; diff --git a/linq/linq.jquery.d.ts b/linq/linq.jquery.d.ts index 896b53c5ae..c4b874baed 100755 --- a/linq/linq.jquery.d.ts +++ b/linq/linq.jquery.d.ts @@ -1,6 +1,7 @@ // Type definitions for linq.jquery (from linq.js) // Project: http://linqjs.codeplex.com/ // Definitions by: neuecc (http://www.codeplex.com/site/users/view/neuecc) +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// /// diff --git a/localForage/localForage-tests.ts b/localForage/localForage-tests.ts new file mode 100644 index 0000000000..f1a416dcf7 --- /dev/null +++ b/localForage/localForage-tests.ts @@ -0,0 +1,34 @@ +/// + +declare var localForage: lf.ILocalForage +declare var callback: lf.ICallback +declare var promise: lf.IPromise + +() => { + localForage.clear() + localForage.length + localForage.key(0) + + localForage.getItem("key", (str: string) => { + var newStr: string = str + }) + localForage.getItem("key").then((str: string) => { + var newStr: string = str + }) + + localForage.setItem("key", "value", (str: string) => { + var newStr: string = str + }) + localForage.setItem("key", "value").then((str: string) => { + var newStr: string = str + }) + + localForage.removeItem("key", (str: string) => { + var newStr: string = str + }) + localForage.removeItem("key").then((str: string) => { + var newStr: string = str + }) + + promise.then(callback) +} diff --git a/localForage/localForage.d.ts b/localForage/localForage.d.ts new file mode 100644 index 0000000000..c3d0371d00 --- /dev/null +++ b/localForage/localForage.d.ts @@ -0,0 +1,26 @@ +// Type definitions for Mozilla's localForage +// Project: https://github.com/mozilla/localforage +// Definitions by: david pichsenmeister +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module lf { + interface ILocalForage { + clear(): void + key(index: number): T + length: number + getItem(key: string, callback: ICallback): void + getItem(key: string): IPromise + setItem(key: string, value: T, callback: ICallback): void + setItem(key: string, value: T): IPromise + removeItem(key: string, callback: ICallback): void + removeItem(key: string): IPromise + } + + interface ICallback { + (data: T): void + } + + interface IPromise { + then(callback: ICallback): void + } +} \ No newline at end of file diff --git a/lodash/lodash-tests.disabled.ts b/lodash/lodash-tests.disabled.ts index 18c3cadd6f..aca0bbdf0b 100644 --- a/lodash/lodash-tests.disabled.ts +++ b/lodash/lodash-tests.disabled.ts @@ -592,6 +592,9 @@ source.addEventListener('message', <_.LoDashObjectWrapper>_(function() 'maxWait': 1000 }), false); +var returnedDebounce = _.throttle(function (a) { return a * 5; }, 5); +returnedThrottled(4); + result = _.defer(function() { console.log('deferred'); }); result = <_.LoDashWrapper>_(function() { console.log('deferred'); }).defer(); @@ -608,15 +611,20 @@ var data = { 'curly': { 'name': 'curly', 'age': 60 } }; -var stooge = _.memoize(function(name: string) { return data[name]; }, _.identity); +var stooge = _.memoize(function(name: string) { return data[name]; }, _.identity); stooge('curly'); stooge['cache']['curly'].name = 'jerome'; stooge('curly'); -var initialize = _.once(function(){ }); -initialize(); +var returnedMemoize = _.throttle(function (a) { return a * 5; }, 5); +returnedMemoize(4); + +var initialize = _.once(function(){ }); initialize(); +initialize();'' +var returnedOnce = _.throttle(function (a) { return a * 5; }, 5); +returnedOnce(4); var greetPartial = function(greeting: string, name: string) { return greeting + ' ' + name; }; var hi = _.partial(greetPartial, 'hi'); @@ -638,6 +646,9 @@ jQuery('.interactive').on('click', _.throttle(function() { }, 300000, { 'trailing': false })); +var returnedThrottled = _.throttle(function (a) { return a*5; }, 5); +returnedThrottled(4); + var helloWrap = function(name: string) { return 'hello ' + name; }; var helloWrap2 = _.wrap(helloWrap, function(func) { return 'before, ' + func('moe') + ', after'; @@ -950,9 +961,9 @@ class Mage { } var mage = new Mage(); -result = _.times(3, _.partial(_.random, 1, 6)); -result = _.times(3, function(n: number) { mage.castSpell(n); }); -result = _.times(3, function(n: number) { this.cast(n); }, mage); +result = _.times(3, <() => number>_.partial(_.random, 1, 6)); +result = _.times(3, function(n: number) { mage.castSpell(n); }); +result = _.times(3, function(n: number) { this.cast(n); }, mage); result = _.unescape('Moe, Larry & Curly'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 5de99d755a..b48f7e6034 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -321,7 +321,7 @@ declare module _ { /** * @see _.findIndex **/ - findIndex( + findIndex( array: List, whereDictionary: W): number; } @@ -404,7 +404,7 @@ declare module _ { * @see _.first * @param whereValue "_.where" style callback value **/ - first( + first( array: List, whereValue: W): T[]; @@ -438,7 +438,7 @@ declare module _ { /** * @see _.first **/ - head( + head( array: List, whereValue: W): T[]; @@ -472,7 +472,7 @@ declare module _ { /** * @see _.first **/ - take( + take( array: List, whereValue: W): T[]; } @@ -507,12 +507,12 @@ declare module _ { callback: ListIterator, thisArg?: any): T[]; - flatten( + flatten( array: List, isShallow: boolean, whereValue: W): T[]; - flatten( + flatten( array: List, whereValue: W): T[]; @@ -548,11 +548,11 @@ declare module _ { flatten( pluckValue: string): LoDashArrayWrapper; - flatten( + flatten( isShallow: boolean, whereValue: W): LoDashArrayWrapper; - flatten( + flatten( whereValue: W): LoDashArrayWrapper; } @@ -638,7 +638,7 @@ declare module _ { * @see _.initial * @param whereValue _.where style callback **/ - initial( + initial( array: List, whereValue: W): T[]; } @@ -700,7 +700,7 @@ declare module _ { * @see _.last * @param whereValue _.where style callback **/ - last( + last( array: List, whereValue: W): T[]; } @@ -848,7 +848,7 @@ declare module _ { /** * @see _.rest **/ - rest( + rest( array: List, whereValue: W): T[]; @@ -882,7 +882,7 @@ declare module _ { /** * @see _.rest **/ - drop( + drop( array: List, whereValue: W): T[]; @@ -916,7 +916,7 @@ declare module _ { /** * @see _.rest **/ - tail( + tail( array: List, whereValue: W): T[]; } @@ -958,7 +958,7 @@ declare module _ { * @see _.sortedIndex * @param pluckValue the _.where style callback **/ - sortedIndex( + sortedIndex( array: List, value: T, whereValue: W): number; @@ -1028,12 +1028,12 @@ declare module _ { * @see _.uniq * @param whereValue _.where style callback **/ - uniq( + uniq( array: List, isSorted: boolean, whereValue: W): T[]; - uniq( + uniq( array: List, whereValue: W): T[]; @@ -1073,11 +1073,11 @@ declare module _ { * @see _.uniq * @param whereValue _.where style callback **/ - unique( + unique( array: List, whereValue?: W): T[]; - unique( + unique( array: List, isSorted: boolean, whereValue?: W): T[]; @@ -1315,7 +1315,7 @@ declare module _ { * @see _.every * @param whereValue _.where style callback **/ - every( + every( collection: Collection, whereValue: W): boolean; @@ -1339,7 +1339,7 @@ declare module _ { * @see _.every * @param whereValue _.where style callback **/ - all( + all( collection: Collection, whereValue: W): boolean; } @@ -1378,7 +1378,7 @@ declare module _ { * @see _.filter * @param pluckValue _.pluck style callback **/ - filter( + filter( collection: Collection, whereValue: W): T[]; @@ -1402,7 +1402,7 @@ declare module _ { * @see _.filter * @param pluckValue _.pluck style callback **/ - select( + select( collection: Collection, whereValue: W): T[]; } @@ -1426,7 +1426,7 @@ declare module _ { * @see _.filter * @param pluckValue _.pluck style callback **/ - filter( + filter( whereValue: W): LoDashArrayWrapper; /** @@ -1447,7 +1447,7 @@ declare module _ { * @see _.filter * @param pluckValue _.pluck style callback **/ - select( + select( whereValue: W): LoDashArrayWrapper; } @@ -1477,7 +1477,7 @@ declare module _ { * @see _.find * @param _.pluck style callback **/ - find( + find( collection: Collection, whereValue: W): T; @@ -1501,7 +1501,7 @@ declare module _ { * @see _.find * @param _.pluck style callback **/ - detect( + detect( collection: Collection, whereValue: W): T; @@ -1525,7 +1525,7 @@ declare module _ { * @see _.find * @param _.pluck style callback **/ - findWhere( + findWhere( collection: Collection, whereValue: W): T; @@ -1557,7 +1557,7 @@ declare module _ { * @see _.find * @param _.pluck style callback **/ - findLast( + findLast( collection: Collection, whereValue: W): T; @@ -1756,12 +1756,12 @@ declare module _ { * @see _.groupBy * @param whereValue _.where style callback **/ - groupBy( + groupBy( collection: List, whereValue: W): Dictionary; } - interface LoDashArrayWrapper { + interface LoDashArrayWrapper { /** * @see _.groupBy **/ @@ -1778,7 +1778,7 @@ declare module _ { /** * @see _.groupBy **/ - groupBy( + groupBy( whereValue: W): _.LoDashObjectWrapper>; } @@ -1817,7 +1817,7 @@ declare module _ { * @see _.indexBy * @param whereValue _.where style callback **/ - indexBy( + indexBy( collection: List, whereValue: W): Dictionary; } @@ -1919,27 +1919,27 @@ declare module _ { **/ map( callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; + thisArg?: any): LoDashArrayWrapper; /** * @see _.map * @param pluckValue _.pluck style callback **/ map( - pluckValue: string): LoDashArrayWrapper; + pluckValue: string): LoDashArrayWrapper; /** * @see _.map **/ collect( callback: ListIterator, - thisArg?: any): LoDashArrayWrapper; + thisArg?: any): LoDashArrayWrapper; /** * @see _.map **/ collect( - pluckValue: string): LoDashArrayWrapper; + pluckValue: string): LoDashArrayWrapper; } interface LoDashObjectWrapper { @@ -1948,14 +1948,14 @@ declare module _ { **/ map( callback: ObjectIterator, - thisArg?: any): LoDashObjectWrapper; + thisArg?: any): LoDashObjectWrapper; /** * @see _.map **/ collect( callback: ObjectIterator, - thisArg?: any): LoDashObjectWrapper; + thisArg?: any): LoDashObjectWrapper; } //_.max @@ -1993,7 +1993,7 @@ declare module _ { * @see _.max * @param whereValue _.where style callback **/ - max( + max( collection: Collection, whereValue: W): T; } @@ -2033,7 +2033,7 @@ declare module _ { * @see _.min * @param whereValue _.where style callback **/ - min( + min( collection: Collection, whereValue: W): T; } @@ -2190,7 +2190,7 @@ declare module _ { * @see _.reject * @param whereValue _.where style callback **/ - reject( + reject( collection: Collection, whereValue: W): T[]; } @@ -2281,7 +2281,7 @@ declare module _ { * @see _.some * @param whereValue _.where style callback **/ - some( + some( collection: Collection, whereValue: W): boolean; @@ -2305,7 +2305,7 @@ declare module _ { * @see _.some * @param whereValue _.where style callback **/ - any( + any( collection: Collection, whereValue: W): boolean; } @@ -2345,7 +2345,7 @@ declare module _ { * @see _.sortBy * @param whereValue _.where style callback **/ - sortBy( + sortBy( collection: List, whereValue: W): T[]; } @@ -2580,10 +2580,10 @@ declare module _ { * @param options.trailing Specify execution on the trailing edge of the timeout. * @return The new debounced function. **/ - debounce( - func: Function, + debounce( + func: T, wait: number, - options?: DebounceSettings): Function; + options?: DebounceSettings): T; } interface LoDashObjectWrapper { @@ -2670,9 +2670,9 @@ declare module _ { * @param resolver Hash function for storing the result of `fn`. * @return Returns the new memoizing function. **/ - memoize( - func: Function, - resolver?: (n: any) => string): Function; + memoize( + func: T, + resolver?: Function): T; } //_.once @@ -2684,7 +2684,7 @@ declare module _ { * @param func Function to only execute once. * @return The new restricted function. **/ - once(func: Function): Function; + once(func: T): T; } //_.partial @@ -2733,10 +2733,10 @@ declare module _ { * @param options.trailing Specify execution on the trailing edge of the timeout. * @return The new throttled function. **/ - throttle( - func: any, + throttle( + func: T, wait: number, - options?: ThrottleSettings): Function; + options?: ThrottleSettings): T; } interface ThrottleSettings { @@ -2784,7 +2784,7 @@ declare module _ { * @param thisArg The this binding of callback. * @return The destination object. **/ - assign( + assign( object: T, s1: S1, callback?: (objectValue: Value, sourceValue: Value) => Value, @@ -2793,7 +2793,7 @@ declare module _ { /** * @see _.assign **/ - assign( + assign( object: T, s1: S1, s2: S2, @@ -2803,7 +2803,7 @@ declare module _ { /** * @see _.assign **/ - assign( + assign( object: T, s1: S1, s2: S2, @@ -2814,7 +2814,7 @@ declare module _ { /** * @see _.assign **/ - assign( + assign( object: T, s1: S1, s2: S2, @@ -2826,7 +2826,7 @@ declare module _ { /** * @see _.assign **/ - extend( + extend( object: T, s1: S1, callback?: (objectValue: Value, sourceValue: Value) => Value, @@ -2835,7 +2835,7 @@ declare module _ { /** * @see _.assign **/ - extend( + extend( object: T, s1: S1, s2: S2, @@ -2845,7 +2845,18 @@ declare module _ { /** * @see _.assign **/ - extend( + extend( + object: T, + s1: S1, + s2: S2, + s3: S3, + callback?: (objectValue: Value, sourceValue: Value) => Value, + thisArg?: any): Result; + + /** + * @see _.assign + **/ + extend( object: T, s1: S1, s2: S2, @@ -3043,7 +3054,7 @@ declare module _ { * @see _.findKey * @param whereValue _.where style callback **/ - findKey, T extends W>( + findKey, T>( object: T, whereValue: W): string; } @@ -3074,7 +3085,7 @@ declare module _ { * @see _.findLastKey * @param whereValue _.where style callback **/ - findLastKey, T extends W>( + findLastKey, T>( object: T, whereValue: W): string; } @@ -3096,7 +3107,7 @@ declare module _ { thisArg?: any): Dictionary; } - interface LoDashObjectWrapper { + interface LoDashObjectWrapper { /** * @see _.forIn **/ @@ -3121,7 +3132,7 @@ declare module _ { thisArg?: any): Dictionary; } - interface LoDashObjectWrapper { + interface LoDashObjectWrapper { /** * @see _.forInRight **/ @@ -3147,7 +3158,7 @@ declare module _ { thisArg?: any): Dictionary; } - interface LoDashObjectWrapper { + interface LoDashObjectWrapper { /** * @see _.forOwn **/ @@ -3172,7 +3183,7 @@ declare module _ { thisArg?: any): Dictionary; } - interface LoDashObjectWrapper { + interface LoDashObjectWrapper { /** * @see _.forOwnRight **/ @@ -3197,7 +3208,7 @@ declare module _ { methods(object: any): string[]; } - interface LoDashObjectWrapper { + interface LoDashObjectWrapper { /** * @see _.functions **/ @@ -3300,6 +3311,11 @@ declare module _ { * @see _.isEmpty **/ isEmpty(value: string): boolean; + + /** + * @see _.isEmpty + **/ + isEmpty(value: any): boolean; } //_.isEqual @@ -3456,7 +3472,7 @@ declare module _ { * @param thisArg The this binding of callback. * @return The destination object. **/ - merge( + merge( object: T, s1: S1, callback?: (objectValue: Value, sourceValue: Value) => Value, @@ -3465,7 +3481,7 @@ declare module _ { /** * @see _.merge **/ - merge( + merge( object: T, s1: S1, s2: S2, @@ -3475,7 +3491,7 @@ declare module _ { /** * @see _.merge **/ - merge( + merge( object: T, s1: S1, s2: S2, @@ -3486,7 +3502,7 @@ declare module _ { /** * @see _.merge **/ - merge( + merge( object: T, s1: S1, s2: S2, @@ -3508,21 +3524,21 @@ declare module _ { * @param keys The properties to omit. * @return An object without the omitted properties. **/ - omit( + omit( object: T, ...keys: string[]): Omitted; /** * @see _.omit **/ - omit( + omit( object: T, keys: string[]): Omitted; /** * @see _.omit **/ - omit( + omit( object: T, callback: ObjectIterator, thisArg?: any): Omitted; @@ -3551,21 +3567,21 @@ declare module _ { * @param keys Property names to pick * @return An object composed of the picked properties. **/ - pick( + pick( object: T, ...keys: string[]): Picked; /** * @see _.pick **/ - pick( + pick( object: T, keys: string[]): Picked; /** * @see _.pick **/ - pick( + pick( object: T, callback: ObjectIterator, thisArg?: any): Picked; @@ -3764,7 +3780,7 @@ declare module _ { **/ times( n: number, - callback: Function, + callback: (num: number) => TResult, context?: any): TResult[]; } @@ -3825,3 +3841,7 @@ declare module _ { [index: string]: T; } } + +declare module "lodash" { + export = _; +} diff --git a/logg/logg.d.ts b/logg/logg.d.ts index a520c33df3..57ef3e4a8a 100644 --- a/logg/logg.d.ts +++ b/logg/logg.d.ts @@ -1,3 +1,8 @@ +// Type definitions for logg +// Project: https://github.com/dpup/node-logg +// Definitions by: Bret Little +// Definitions: https://github.com/borisyankov/DefinitelyTyped + interface Logger { setLogLevel: (level: number)=> void; getLogLevel: ()=> number; @@ -29,4 +34,4 @@ declare module "logg" { export var Level : loggingLevels; export var rootLogger: Logger; export var registerWatcher: (watcher: (logRecord: string)=> void)=> void; -} \ No newline at end of file +} diff --git a/mapsjs/mapsjs.d.ts b/mapsjs/mapsjs.d.ts index 29627eae92..a71cb1ad5b 100644 --- a/mapsjs/mapsjs.d.ts +++ b/mapsjs/mapsjs.d.ts @@ -1,3 +1,8 @@ +// Type definitions for Mapsjs 9.6.0 +// Project: https://github.com/mapsjs +// Definitions by: Matthew James Davis +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /** * Mapsjs 9.6.0 Copyright (c) 2013 ISC. All Rights Reserved. */ @@ -423,7 +428,7 @@ declare module 'mapsjs' { * @param {number} [idx] Index of the line for which to compute the distance. * @returns {number} Distance in meters of the line. */ - getActualDistance(idx: number): number; + getActualDistance(idx?: number): number; /** * Determines whether this polyline intersects a given geometry. @@ -504,7 +509,7 @@ declare module 'mapsjs' { * @param {number} [idx] Index of the ring for which to compute the area. * @returns {number} Area in square meters of the ring. */ - getActualArea(idx: number): number; + getActualArea(idx?: number): number; /** * Calculates perimeter of a ring in a polygon by index according @@ -513,7 +518,7 @@ declare module 'mapsjs' { * @param {number} [idx] Index of the ring for which to compute the perimeter. * @returns {number} Length in meters of the perimeter of the ring. */ - getActualPerimeter(idx: number): number; + getActualPerimeter(idx?: number): number; /** * Determines whether this polygon intersects a given geometry. @@ -543,7 +548,7 @@ declare module 'mapsjs' { * @class geometryStyle */ export class geometryStyle { - constructor(); + constructor(options?: styleObj); /** * Gets path outline thickness in pixels. @@ -894,8 +899,14 @@ declare module 'mapsjs' { * @class styledGeometry */ export class styledGeometry { - constructor(geom: geometry, gStyle: geometryStyle); + constructor(geom: geometry, gStyle?: geometryStyle); + /** + * Set this styledGeometry's geometry. + * @param {geometry} g A new Geometry. + */ + setGeometry(g: geometry): void; + /** * Set this styledGeometry's geometryStyle. * @param {geometryStyle} gs A new styledGeometry. @@ -907,6 +918,12 @@ declare module 'mapsjs' { * @returns {geometry} The underlying geometry. */ getGeometry(): geometry; + + /** + * Gets the styledGeometry's underlying geometryStyle object. + * @returns {geometryStyle} The underlying geometry style. + */ + getGeometryStyle(): geometryStyle; /** * Gets path outline thickness in pixels. @@ -928,7 +945,7 @@ declare module 'mapsjs' { /** * Gets path outline opacity in decimal format. - * @returns {number} Outline opacity. + * @param {number} Outline opacity. */ setOutlineColor(c: string): void; @@ -1317,6 +1334,11 @@ declare module 'mapsjs' { ulX: number; ulY: number; }; + + /** + * Unbind all associations with this tile layer to facilitate garbage collection + */ + dispose(): void; } /** @@ -2216,8 +2238,53 @@ declare module 'mapsjs' { * @returns {number} maxY coord as integer */ maxY: number; - } - + } + + interface extentChangeStatsObj { + + centerX: number; + centerY: number; + centerLat: number; + centerLon: number; + zoomLevel: number; + mapScale: number; + mapScaleProjected: number; + mapUnitsPerPixel: number; + extents: envelope; + } + + interface repositionStatsObj { + + centerX: number; + centerY: number; + zoomLevel: number; + mapUnitsPerPixel: number; + } + + interface beginDigitizeOptions { + key?: string; + shapeType: string; + geometryStyle?: geometryStyle; + styledGeometry?: styledGeometry; + nodeTapAndHoldAction?: (setIdx: number, idx: number) => boolean; + nodeMoveAction?: (x: number, y: number, actionType: string) => any; + shapeChangeAction?: () => void; + envelopeEndAction?: (env: envelope) => void; + circleEndAction?: (circle: geometry.polygon) => void; + suppressNodeAdd?: boolean; + leavePath?: boolean; + } + + + interface styleObj { + fillColor?: string; + fillOpacity?: number; + outlineColor?: string; + outlineOpacity?: number; + outlineThicknessPix?: number + dashArray?: string; + } + interface mapsjsWidget { /** @@ -2507,12 +2574,18 @@ declare module 'mapsjs' { * content area DOM. If an attempt to add a geometry is made with the same * key, the geometry is swapped out. You must remove using removePathGeometry * for resource cleanup. - * @param {styleGeometry} styledGeom THe styledGeometry to render. - * @param {string} key String used to tie a geometry to its SVG + * @param {styleGeometry} styledGeom The styledGeometry to render. + * @param {string} key String used to tie a geometry to its SVG + * @param {function} addAction optional function that is called when mapsjs adds an svg element to the DOM representing this styledGeometry. + * @param {function} removeAction optional function that is called when mapsjs adds an svg element to the DOM representing this styledGeometry. * rendering in the DOM. * @returns {element} The SVG element which was added to the DOM. */ - addPathGeometry(styledGeom: styledGeometry, key: string): void; + addPathGeometry( + styledGeom: styledGeometry, + key: string, + addAction?: (svg: SVGElement) => void, + removeAction?: (svg: SVGElement) => void): SVGElement; /** * Updates an existing path geometry to reflect a style change. @@ -2524,41 +2597,34 @@ declare module 'mapsjs' { /** * Removes a styledGeometry from display. * @param {string} key The key of the geometry to remove. + * @returns {element} The SVG element which was removed from the DOM. */ - removePathGeometry(key: string): void; + removePathGeometry(key?: string): SVGElement; /** * Initiates digitization on the map control. This creates a new * geometry and adds verticies to the geometry accord to mouse * click locations. * @param {object} options JavaScript object of the form { key, - * shapeType, geometryStyle, nodeTapAndHoldAction, nodeMoveAction, - * shapeChangeAction, envelopeEndAction, supressNodeAdd, leavePath } + * shapeType, geometryStyle, styledGeometry, nodeTapAndHoldAction, nodeMoveAction, + * shapeChangeAction, envelopeEndAction, circleEndAction, supressNodeAdd, leavePath } * where key is a a string associated with this geometry, shapeType - * is the type of shape this geometry is, one of 'point', 'path', or - * 'polygon', geometryStyle is a geometryStyle which should be applied - * to the digitized geometry, nodeTapAndHoldAction is a callback invoked + * is the type of shape this geometry is, one of 'polygon', 'polyline', 'multipoint', 'envelope' or 'circle', + * geometryStyle is a geometryStyle which should be applied + * to the digitized geometry, styledGeometry is an optional styledGeometry for existing paths to edit, set this to enter edit mode, + * nodeTapAndHoldAction is a callback invoked * when any point in the geometry is clicked and held and has the * signature nodeTapAndHoldAction(setIdx, idx), nodeMoveAction is a * callback invoked after any node is dragged to a new location and * has signature nodeMoveAction(x, y, actionType), shapeChangeAction * is a callback that is invoked after the geometry shape changes and, - * has signature shapeChangeAction(), envelopeEndAction is a callback + * has signature shapeChangeAction(shape), envelopeEndAction is a callback * invoked after an envelope is created and has signature envelopeEndAction(envelope), + * circleEndAction is similar to envelopeEndAction but takes a geometry.polygon representing the circle, * and leavePath is a flag that indicates whether the digitized shape * should be left on the map after digitization is complete. */ - beginDigitize(options: { - key?: string; - shapeType: string; - geometryStyle?: geometryStyle; - nodeTapAndHoldAction?: (setIdx: number, idx: number) => boolean; - nodeMoveAction?: (x: number, y: number, actionType: string) => any; - shapeChangeAction?: () => void; - envelopeEndAction?: (env: envelope) => void; - suppressNodeAdd?: boolean; - leavePath?: boolean; - }): void; + beginDigitize(options: beginDigitizeOptions): void; endDigitize(): void; /** @@ -2601,7 +2667,7 @@ declare module 'mapsjs' { * the form { centerX, centerY, centerLat, centerLon, zoomLevel, mapScale, * mapScaleProjected, mapUnitsPerPixel, extents }. */ - setExtentChangeCompleteAction(action: (vals: {}) => void): void; + setExtentChangeCompleteAction(action: (vals: extentChangeStatsObj) => void): void; /** * Set the function called when map content (map tiles and fixed elements) are @@ -2611,7 +2677,7 @@ declare module 'mapsjs' { * completes repositioning with signature action(object) where object * is of the form { centerX, centerY, zoomLevel, mapUnitsPerPixel }. */ - setContentRepositionAction(action: (vals: {}) => void): void; + setContentRepositionAction(action: (vals: repositionStatsObj) => void): void; /** * Sets function called when map is clicked or tapped. diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 52a1bb6ef9..3427d6de4e 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/marionettejs/ // Definitions by: Zeeshan Hamid // Definitions by: Natan Vivo +// Definitions by: Sven Tschui // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -111,8 +112,8 @@ declare module Marionette { function unbindEntityEvents(target, entity, bindings); class Callbacks { - add(callback, contextOverride): void; - run(options, context): void; + add(callback:Function, contextOverride:any): void; + run(options:any, context:any): void; reset(): void; } @@ -268,11 +269,18 @@ declare module Marionette { render(): Layout; removeRegion(name: string); } + + interface AppRouterOptions extends Backbone.RouterOptions { + appRoutes: any; + controller: any; + } class AppRouter extends Backbone.Router { - constructor(options?: any); - processAppRoutes(controller: Controller, appRoutes: any); + constructor(options?: AppRouterOptions); + processAppRoutes(controller: any, appRoutes: any); + appRoute(route:string, methodName:string):void; + } class Application extends Backbone.Events { @@ -287,7 +295,9 @@ declare module Marionette { addInitializer(initializer); start(options?); addRegions(regions); + closeRegions(): void; removeRegion(region: Region); + getRegion(regionName: string): Region; module(moduleNames, moduleDefinition); } @@ -306,3 +316,9 @@ declare module Marionette { addDefinition(moduleDefinition, customArgs); } } + +declare module 'backbone.marionette' { + import Backbone = require('backbone'); + + export = Marionette; +} diff --git a/messenger/messenger-tests.ts b/messenger/messenger-tests.ts new file mode 100644 index 0000000000..1f560e6e2d --- /dev/null +++ b/messenger/messenger-tests.ts @@ -0,0 +1,14 @@ +/// + +var message = Messenger().post({ + message: "message", + hideAfter: 5, + showCloseButton: true, + type: "error" +}); +message.update({ + type: "error", + message: "Error calculating position" +}); + +Messenger().hideAll(); diff --git a/messenger/messenger.d.ts b/messenger/messenger.d.ts new file mode 100644 index 0000000000..3aacf2f889 --- /dev/null +++ b/messenger/messenger.d.ts @@ -0,0 +1,119 @@ +// Type definitions for Messenger.js 1.4.0 +// Project: https://github.com/HubSpot/messenger +// Definitions by: Derek Cicerone +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface IMessenger { + (): Messenger; + options: MessengerOptions; +} + +interface Messenger { + /** + * Posts a message. + */ + post(options: MessageOptions): Message; + + /** + * Hides all messages. + */ + hideAll(): void; +} + +interface Message { + /** + * Show the message, if it's hidden. + */ + show(): void; + + /** + * Hide the message, if it's hidden. + */ + hide(): void; + + /** + * If the message is associated with an ajax request or is counting down to retry, cancel it. + */ + cancel(): void; + + /** + * Update the message with the provided options. + */ + update(options: MessageOptions): void; +} + +interface MessageOptions { + /** + * The text of the message. + */ + message: string; + + /** + * Hide the message after the provided number of seconds. + */ + hideAfter?: number; + + /** + * Hide the message if Backbone client-side navigation occurs. + */ + hideOnNavigate?: boolean; + + /** + * A unique id. If supplied, only one message with that ID will be shown at a time. + */ + id?: string; + + /** + * Should a close button be added to the message? + */ + showCloseButton?: boolean; + + /** + * Hide the newer message if there is an id collision, as opposed to the older message. + */ + singleton?: boolean; + + /** + * What theme class should be applied to the message? Defaults to the theme set for Messenger in general. + */ + theme?: string; + + /** + * "info", "error" or "success" are understood by the provided themes. You can also pass your own string, and that class will be added. + */ + type?: string; +} + +interface MessengerOptions { + + /** + * Extra classes to be appended to the container. + */ + extraClasses?: string; + + /** + * The maximum number of messages to show at once. + */ + maxMessages?: number; + + /** + * Default options for created messages. + */ + messageDefaults?: MessageOptions; + + /** + * Which locations should be tried when inserting the message container into the page. + * The default is ['body']. It accepts a list to allow you to try a variety of places + * when deciding what the optimal location is on any given page. This should generally + * not need to be changed unless you are inserting the messages into the flow of the + * document, rather than using messenger-fixed. + */ + parentLocations?: string[]; + + /** + * What theme are you using? Some themes have associated javascript, specifing this allows that js to run. + */ + theme?: string; +} + +declare var Messenger: IMessenger; diff --git a/microsoft-live-connect/microsoft-live-connect.d.ts b/microsoft-live-connect/microsoft-live-connect.d.ts new file mode 100644 index 0000000000..04ff3ef79b --- /dev/null +++ b/microsoft-live-connect/microsoft-live-connect.d.ts @@ -0,0 +1,2337 @@ +/// +// Type definitions for Microsoft Live Connect v5.0. +// Project: http://msdn.microsoft.com/en-us/library/live/hh243643.aspx +// Definitions by: John Vilk +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Microsoft.Live { + //#region REST Object Information + + /** + * Sub object of REST objects that contains information about a user. + */ + interface IUserInfo { + /** + * The name of the user. + */ + name: string; + /** + * The Live ID of the user. + */ + id: string; + } + + /** + * Sub object of REST objects that contains information about who the + * item is shared with. + */ + interface ISharedWith { + /** + * A localized string that contains info about who can access the + * item. The options are: + * - People I selected + * - Just me + * - Everyone (public) + * - Friends + * - My friends and their friends + * - People with a link + * The default is Just me. + */ + access: string; + } + + /** + * Convenience interface for when you have a bunch of objects of different + * types in a single collection. You discriminate between them using their + * 'type' field. + */ + interface IObject { + /** + * The object's type. + */ + type: string; + } + + /** + * Contains a collection of one type of object. + */ + interface IObjectCollection { + /** + * An array container for objects when a collection of objects is + * returned. + */ + data: T[]; + } + + /** + * The Album object contains info about a user's albums in Microsoft + * SkyDrive. Albums are stored at the root level of a user's SkyDrive + * directory, and can contain combinations of photos, videos, audio, files, + * and folders. The Live Connect REST API supports reading Album objects. + * Use the wl.photos scope to read a user's Album objects. Use the + * wl.skydrive scope to read a user's files. Use the wl.contacts_photos + * scope to read any albums, photos, videos, and audio that other users have + * shared with the user. + */ + interface IAlbum { + /** + * The Album object's ID. + */ + id: string; + /** + * Info about the user who authored the album. + */ + from: IUserInfo; + /** + * The name of the album. + */ + name: string; + /** + * A description of the album, or null if no description is specified. + */ + description: string; + /** + * The resource ID of the parent. + */ + parent_id: string; + /** + * The URL to upload items to the album, hosted in SkyDrive. Requires + * the wl.skydrive scope. + */ + upload_location: string; + /** + * A value that indicates whether this album can be embedded. If this + * album can be embedded, this value is true; otherwise, it is false. + */ + is_embeddable: boolean; + /** + * The total number of items in the album. + */ + count: number; + /** + * A URL of the album, hosted in SkyDrive. + */ + link: string; + /** + * The type of object; in this case, "album". + */ + type: string; + /** + * The object that contains permissions info for the album. Requires the + * wl.skydrive scope. + */ + shared_with: ISharedWith; + /** + * The time, in ISO 8601 format, at which the album was created. + */ + created_time: string; + /** + * The time, in ISO 8601 format, that the system updated the album last. + */ + updated_time: string; + /** + * The time, in ISO 8601 format, that the file was last updated. + */ + client_updated_time: string; + } + + /** + * Represents a new album. + */ + interface INewAlbum { + /** + * The name of the album. + */ + name: string; + /** + * A description of the album. + */ + description?: string; + } + + /** + * The Audio object contains info about a user's audio in SkyDrive. The Live + * Connect REST API supports creating, reading, updating, and deleting Audio + * objects. Use the wl.skydrive scope to read Audio objects. Use the + * wl.contacts_skydrive scope to read any audio that other users have shared + * with the user. Use the wl.skydrive_update scope to create, update, or + * delete Audio objects. + */ + interface IAudio { + /** + * The Audio object's ID. + */ + id: string; + /** + * Info about the user who uploaded the audio. + */ + from: IUserInfo; + /** + * The name of the audio. + */ + name: string; + /** + * A description of the audio, or null if no description is specified. + */ + description: string; + /** + * The id of the folder in which the audio is currently stored. + */ + parent_id: string; + /** + * The size, in bytes, of the audio. + */ + size: number; + /** + * The URL to use to upload a new audio to overwrite the existing audio. + */ + upload_location: string; + /** + * The number of comments associated with the audio. + */ + comments_count: number; + /** + * A value that indicates whether comments are enabled for the audio. If + * comments can be made, this value is true; otherwise, it is false. + */ + comments_enabled: boolean; + /** + * A value that indicates whether this audio can be embedded. If this + * audio can be embedded, this value is true; otherwise, it is false. + */ + is_embeddable: boolean; + /** + * The URL to use to download the audio from SkyDrive. + * Warning + * This value is not persistent. Use it immediately after making the + * request, and avoid caching. + */ + source: string; + /** + * A URL to view the item on SkyDrive. + */ + link: string; + /** + * The type of object; in this case, "audio". + */ + type: string; + /** + * The audio's title. + */ + title: string; + /** + * The audio's artist name. + */ + artist: string; + /** + * The audio's album name. + */ + album: string; + /** + * The artist name of the audio's album. + */ + album_artist: string; + /** + * The audio's genre. + */ + genre: string; + /** + * The audio's playing time, in milliseconds. + */ + duration: number; + /** + * A URL to view the audio's picture on SkyDrive. + */ + picture: string; + /** + * The object that contains permission info. + */ + shared_with: ISharedWith; + /** + * The time, in ISO 8601 format, at which the audio was created. + */ + created_time: string; + /** + * The time, in ISO 8601 format, at which the audio was last updated. + */ + updated_time: string; + } + + /** + * Represents a new audio item. + */ + interface INewAudio { + /** + * The name of the audio. + */ + name: string; + /** + * A description of the audio. + */ + description?: string; + /** + * The audio's title. + */ + title?: string; + /** + * The audio's artist name. + */ + artist?: string; + /** + * The audio's album name. + */ + album?: string; + /** + * The artist name of the audio's album. + */ + album_artist?: string; + /** + * The audio's genre. + */ + genre?: string; + } + + /** + * The Calendar object contains info about a user's Outlook.com calendar. + * The Live Connect REST API supports creating, reading, updating, and + * deleting calendars. Use the wl.calendars scope to read a user's Calendar + * objects. Use the wl.calendars_update scope to create Calendar objects for + * a user. Use the wl.contacts_calendars scope to read a user's friends' + * Calendar objects. + */ + interface ICalendar { + /** + * The Calendar object's ID. + */ + id: string; + /** + * Name of the calendar. + */ + name: string; + /** + * Description of the calendar. + */ + description: string; + /** + * The time, in ISO 8601 format, at which the calendar was created. + */ + created_time: string; + /** + * The time, in ISO 8601 format, that the calendar was last updated. + */ + updated_time: string; + /** + * Info about the user who owns the calendar. + */ + from: IUserInfo; + /** + * A value that indicates whether this calendar is the default calendar. + * If this calendar is the default calendar, this value is true; + * otherwise, it is false. + */ + is_default: boolean; + /** + * A public subscription URL with which Live Connect will synchronize + * properties and events periodically for this calendar. A NULL value + * indicates that this is not a subscribed calendar. + */ + subscription_location: string; + /** + * Role and permissions that are granted to the user for the calendar. + * The possible values are: + * - free_busy: The user can see only free/busy info. + * - limited_details: The user can see a subset of all details. + * - read: The user can only read the content of the calendar events. + * - read_write: The user can read and write calendar and events. + * - co_owner: The user is co-owner of this calendar. + * - owner: The user is the owner of this calendar. + */ + permissions: string; + } + + /** + * Represents a new calendar item. + */ + interface INewCalendar { + /** + * Name of the calendar. + */ + name: string; + /** + * Description of the calendar. + */ + description?: string; + } + + /** + * Represents a request to create a new calendar that subscribes to the + * given iCal calendar. + */ + interface INewCalendarSubscription { + /** + * Name of the calendar. + */ + name: string; + /** + * A public subscription URL with which Live Connect will synchronize + * properties and events periodically for this calendar. + */ + subscription_location: string; + } + + /** + * The Comment object contains info about comments that are associated with + * a photo, audio, or video on SkyDrive. The Live Connect REST API supports + * reading Comment objects. Use the wl.photos scope to read Comment objects. + * Use the wl.contacts_photos scope to read the Comment objects that are + * associated with any albums, photos, and videos that other users have + * shared with the user. + */ + interface IComment { + /** + * The Comment object's id. + */ + id: string; + /** + * Info about the user who created the comment. + */ + from: IUserInfo; + /** + * The text of the comment. The maximum length of a comment is 10,000 + * characters. + */ + message: string; + /** + * The time, in ISO 8601 format, at which the comment was created. + */ + created_time: string; + } + + /** + * Represents a new comment. + */ + interface INewComment { + /** + * The text of the comment. The maximum length of a comment is 10,000 + * characters. + */ + message: string; + } + + /** + * The Contact object contains info about a user's Outlook.com contacts. The + * Live Connect REST API supports reading Contact objects. + */ + interface IContact { + /** + * The Contact object's ID. + */ + id: string; + /** + * The contact's first name, or null if no first name is specified. + */ + first_name: string; + /** + * The contact's last name, or null if no last name is specified. + */ + last_name: string; + /** + * The contact's full name, formatted for location. + */ + name: string; + /** + * A value that indicates whether the contact is set as a friend. If the + * contact is a friend, this value is true; otherwise, it is false. + */ + is_friend: boolean; + /** + * A value that indicates whether the contact is set as a favorite + * contact. If the contact is a favorite, this value is true; otherwise, + * it is false. + */ + is_favorite: boolean; + /** + * The contact's ID, if the contact has one. If not, this value is null. + */ + user_id: string; + /** + * An array containing a SHA-256 hash for each of the contact's email + * addresses. For more info, see Friend finder. + */ + email_hashes: string[]; + /** + * The time, in ISO 8601 format, at which the user last updated the + * data. + */ + updated_time: string; + /** + * The day of the contact's birth date, or null if no birth date is + * specified. + */ + birth_day: number; + /** + * The month of the contact's birth date, or null if no birth date is + * specified. + */ + birth_month: number; + } + + /** + * Represents a new contact. + */ + interface INewContact { + /** + * The contact's first name. + */ + first_name?: string; + /** + * The contact's last name. + */ + last_name?: string; + /** + * An array that contains the contact's work info. + */ + work?: { + employer: { + name: string; + } + }[]; + /** + * The contact's email addresses. + */ + emails?: { + /** + * The contact's preferred email address. + */ + preferred?: string; + /** + * The contact's personal email address. + */ + personal?: string; + /** + * The contact's business email address. + */ + business?: string; + /** + * The contact's "alternate" email address. + */ + other?: string; + }; + } + + /** + * The Error object contains info about an error that is returned by the + * Live Connect APIs. + */ + interface IError { + /** + * Info about the error. + */ + error: { + /** + * The error code. + */ + code: string; + /** + * The error message. + */ + message: string; + }; + } + + /** + * The Event object contains info about events on a user's Outlook.com + * calendars. The Live Connect REST API supports creating Event objects. Use + * the wl.events_create scope to create Event objects on the user's default + * calendar only. Use the wl.calendars scope to read Event objects on the + * user's calendars. Use wl.calendars_update to create Event objects on any + * of the user's calendars. Use the wl.contacts_calendars scope to read + * Event objects from the user's friend's calendars. + */ + interface IEvent { + /** + * The ID of the event. + */ + id: string; + /** + * The name of the event, with a maximum length of 255 characters. This + * structure is required. + */ + name: string; + /** + * The time, in ISO 8601 format, at which the event was created. + */ + created_time: string; + /** + * The time, in ISO 8601 format, at which the event was updated. This + * structure is visible only in the Event object that is returned if the + * event was successfully created. + */ + updated_time: string; + /** + * A description of the event, with a maximum length of 32,768 + * characters. This structure is required. + */ + description: string; + /** + * The ID of the calendar that contains the event. + */ + calendar_id: string; + /** + * The object that contains the name and ID of the organizer. + */ + from: IUserInfo; + /** + * The start time, in ISO 8601 format, of the event. When the event is + * being read, the time will be the user's local time, in ISO 8601 + * format. + */ + start_time: string; + /** + * The end time, in ISO 8601 format, of the event. If no end time is + * specified, the default value is 30 minutes after start_time. This + * structure is optional when creating an event. When the event is being + * read, the time will be the user's local time, in ISO 8601 format. + */ + end_time: string; + /** + * The name of the location at which the event will take place. The + * maximum length is 1,000 characters. + */ + location: string; + /** + * A value that specifies whether the event is an all-day event. If the + * event is an all-day event, this value is true; otherwise, it is + * false. If this structure is missing, the default value is false. + */ + is_all_day_event: boolean; + /** + * A value that specifies whether the event is recurring. If the event + * is recurring, this value is true; otherwise, it is false. + */ + is_recurrent: boolean; + /** + * The text description of the recurrence pattern, for example, "Occurs + * every week on Tuesday". The value is Null if this is not a recurrent + * event. + */ + recurrence: string; + /** + * The time, in minutes, before the event for the reminder alarm. + */ + reminder_time: number; + /** + * The user's availability status for the event. Valid values are: + * - free + * - busy + * - tentative + * - out_of_office + * @default "free" + */ + availability: string; + /** + * A value that specifies whether the event is publicly visible. Valid + * values are: + * - publicthe event is visible to anyone who can view the calendar. + * - private"the event is visible only to the event owner. + * @default "public" + */ + visibility: string; + } + + /** + * Represents a new event. + */ + interface INewEvent { + /** + * The name of the event, with a maximum length of 255 characters. This + * structure is required. + */ + name: string; + /** + * A description of the event, with a maximum length of 32,768 + * characters. This structure is required. + */ + description: string; + /** + * The start time of the event. When the event is being read, the time + * will be the user's local time, in ISO 8601 format. + * Can be a date string, or a Date object. + */ + start_time: any; + /** + * The end time of the event. If no end time is specified, the default + * value is 30 minutes after start_time. This structure is optional when + * creating an event. When the event is being read, the time will be the + * user's local time, in ISO 8601 format. + * Can be a date string, or a Date object. + */ + end_time?: any; + /** + * The name of the location at which the event will take place. The + * maximum length is 1,000 characters. + */ + location?: string; + /** + * A value that specifies whether the event is an all-day event. If the + * event is an all-day event, this value is true; otherwise, it is + * false. If this structure is missing, the default value is false. + */ + is_all_day_event?: boolean; + /** + * The time, in minutes, before the event for the reminder alarm. + */ + reminder_time?: number; + /** + * The user's availability status for the event. Valid values are: + * - free + * - busy + * - tentative + * - out_of_office + * @default "free" + */ + availability?: string; + /** + * A value that specifies whether the event is publicly visible. Valid + * values are: + * - publicthe event is visible to anyone who can view the calendar. + * - private"the event is visible only to the event owner. + * @default "public" + */ + visibility?: string; + } + + /** + * Response received after successfully creating a new event. + */ + interface INewEventResponse { + /** + * The name of the event, with a maximum length of 255 characters. This + * structure is required. + */ + name: string; + /** + * A description of the event, with a maximum length of 32,768 + * characters. This structure is required. + */ + description: string; + /** + * The start time, in ISO 8601 format, of the event. When the event is + * being read, the time will be the user's local time, in ISO 8601 + * format. + */ + start_time: string; + /** + * The end time, in ISO 8601 format, of the event. If no end time is + * specified, the default value is 30 minutes after start_time. This + * structure is optional when creating an event. When the event is being + * read, the time will be the user's local time, in ISO 8601 format. + */ + end_time: string; + /** + * The name of the location at which the event will take place. The + * maximum length is 1,000 characters. + */ + location: string; + /** + * A value that specifies whether the event is an all-day event. If the + * event is an all-day event, this value is true; otherwise, it is + * false. If this structure is missing, the default value is false. + */ + is_all_day_event: boolean; + /** + * A value that specifies whether the event is recurring. If the event + * is recurring, this value is true; otherwise, it is false. + */ + is_recurrent: boolean; + /** + * The text description of the recurrence pattern, for example, "Occurs + * every week on Tuesday". The value is Null if this is not a recurrent + * event. + */ + recurrence: string; + /** + * The time, in minutes, before the event for the reminder alarm. + */ + reminder_time: number; + /** + * The user's availability status for the event. Valid values are: + * - free + * - busy + * - tentative + * - out_of_office + * @default "free" + */ + availability: string; + /** + * A value that specifies whether the event is publicly visible. Valid + * values are: + * - publicthe event is visible to anyone who can view the calendar. + * - private"the event is visible only to the event owner. + * @default "public" + */ + visibility: string; + /** + * The time, in ISO 8601 format, at which the event was updated. This + * structure is visible only in the Event object that is returned if the + * event was successfully created. + */ + updated_time: string; + } + + /** + * The File object contains info about a user's files in SkyDrive. The Live + * Connect REST API supports creating, reading, updating, and deleting File + * objects. Use the wl.skydrive scope to read File objects. Use the + * wl.contacts_skydrive scope to read any files that other users have shared + * with the user. Use the wl.skydrive_update scope to create, update, or + * delete File objects. + */ + interface IFile { + /** + * The File object's ID. + */ + id: string; + /** + * Info about the user who uploaded the file. + */ + from: IUserInfo; + /** + * The name of the file. + */ + name: string; + /** + * A description of the file, or null if no description is specified. + */ + description: string; + /** + * The ID of the folder the file is currently stored in. + */ + parent_id: string; + /** + * The size, in bytes, of the file. + */ + size: number; + /** + * The URL to upload file content hosted in SkyDrive. + * Note: This structure is not available if the file is an Microsoft + * Office OneNote notebook. + */ + upload_location: string; + /** + * The number of comments that are associated with the file. + */ + comments_count: number; + /** + * A value that indicates whether comments are enabled for the file. If + * comments can be made, this value is true; otherwise, it is false. + */ + comments_enabled: boolean; + /** + * A value that indicates whether this file can be embedded. If this + * file can be embedded, this value is true; otherwise, it is false. + */ + is_embeddable: boolean; + /** + * The URL to use to download the file from SkyDrive. + * Warning: This value is not persistent. Use it immediately after + * making the request, and avoid caching. + * Note: This structure is not available if the file is an Office + * OneNote notebook. + */ + source: string; + /** + * A URL to view the item on SkyDrive. + */ + link: string; + /** + * The type of object; in this case, "file". + * Note: If the file is a Office OneNote notebook, the type structure is + * set to "notebook". + */ + type: string; + /** + * Object that contains permission info. + */ + shared_with: ISharedWith; + /** + * The time, in ISO 8601 format, at which the file was created. + */ + created_time: string; + /** + * The time, in ISO 8601 format, that the system updated the file last. + */ + updated_time: string; + /** + * The time, in ISO 8601 format, that the client machine updated the + * file last. + */ + client_updated_time: string; + /** + * Sorts the items to specify the following criteria: updated, name, + * size, or default. + */ + sort_by: string; + } + + /** + * Success response to a new file creation request. + */ + interface INewFileResponse { + /** + * ID of the new item. + */ + id: string; + /** + * The file's name and file extension. + */ + name: string; + /** + * URL where the item can be downloaded from. + */ + source: string; + } + + /** + * Returns when you perform a GET request to /FILE_ID/content. + */ + interface IFileDownloadLink { + /** + * A URL download link for the file. + */ + location: string; + } + + /** + * The Folder object contains info about a user's folders in SkyDrive. + * Folders can contain combinations of photos, videos, audio, and + * subfolders. The Live Connect REST API supports reading Folder objects. + * Use the wl.photos scope to read Folder objects. Use the + * wl.contacts_photos scope to read any albums, photos, videos, and audio + * that other users have shared with the user. + */ + interface IFolder { + /** + * The Folder object's ID. + */ + id: string; + /** + * Info about the user who created the folder. + */ + from: IUserInfo; + /** + * The name of the folder. + */ + name: string; + /** + * A description of the folder, or null if no description is specified. + */ + description: string; + /** + * The total number of items in the folder. + */ + count: number; + /** + * The URL of the folder, hosted in SkyDrive. + */ + link: string; + /** + * The resource ID of the parent. + */ + parent_id: string; + /** + * The URL to upload items to the folder hosted in SkyDrive. Requires + * the wl.skydrive scope. + */ + upload_location: string; + /** + * A value that indicates whether this folder can be embedded. If this + * folder can be embedded, this value is true; otherwise, it is false. + */ + is_embeddable: boolean; + /** + * The type of object; in this case, "folder". + */ + type: string; + /** + * The time, in ISO 8601 format, at which the folder was created. + */ + created_time: string; + /** + * The time, in ISO 8601 format, that the system updated the file last. + */ + updated_time: string; + /** + * The time, in ISO 8601 format, that the client machine updated the + * file last. + */ + client_updated_time: string; + /** + * Permissions info for the folder. Requires the wl.skydrive scope. + */ + shared_with: ISharedWith; + /** + * Sorts the items to specify the following criteria: updated, name, + * size, or default. + */ + sort_by: string; + } + + /** + * Represents a new folder. + */ + interface INewFolder { + /** + * The name of the folder. + */ + name: string; + /** + * A description of the folder. + */ + description?: string; + /** + * Sorts the items to specify the following criteria: updated, name, + * size, or default. + */ + sort_by?: string; + } + + /** + * The Friend object contains info about a user's friends. A Friend object + * represents a user's contact whose is_friend value is set to true. The + * Live Connect REST API supports reading Friend objects. + */ + interface IFriend { + /** + * The friend's ID. + */ + id: string; + /** + * The friend's full name, formatted for locale. + */ + name: string; + } + + /** + * The Permissions object contains a list of scopes, showing those scopes to + * which the user has consented. The response body contains a JSON object + * that lists all consented scopes as a name/value pair. Each scope to which + * the user consented is present as a key. + */ + interface IPermissions { + [scope: string]: number; + } + + /** + * Information about an image. + */ + interface IImageInfo { + /** + * The height, in pixels, of this image of this particular size. + */ + height: number; + /** + * The width, in pixels, of this image of this particular size. + */ + width: number; + /** + * The width, in pixels, of this image of this particular size. + */ + source: string; + /** + * The type of this image of this particular size. Valid values are: + * full (maximum size: 2048 2048 pixels) + * - normal (maximum size 800 800 pixels) + * - album (maximum size 176 176 pixels) + * - small (maximum size 96 96 pixels) + */ + type: string; + } + + /** + * Represents location information. + */ + interface ILocation { + /** + * The latitude portion of the location, expressed as positive (north) + * or negative (south) degrees relative to the equator. + */ + latitude: number; + /** + * The longitude portion of the location expressed as positive (east) or + * negative (west) degrees relative to the Prime Meridian. + */ + longitude: number; + /** + * The altitude portion of the location, expressed as positive (above) + * or negative (below) values relative to sea level, in units of + * measurement as determined by the camera. + */ + altitude: number; + } + + /** + * The Photo object contains info about a user's photos on SkyDrive. The + * Live Connect REST API supports creating, reading, updating, and deleting + * Photo objects. Use the wl.photos scope to read Photo objects. Use the + * wl.contacts_photos scope to read any albums, photos, videos, and audio + * that other users have shared with the user. Use the wl.skydrive_update + * scope to create, update, or delete Photo objects. + */ + interface IPhoto { + /** + * The Photo object's ID. + */ + id: string; + /** + * Info about the user who uploaded the photo. + */ + from: IUserInfo; + /** + * The file name of the photo. + */ + name: string; + /** + * A description of the photo, or null if no description is specified. + */ + description: string; + /** + * The ID of the folder where the item is stored. + */ + parent_id: string; + /** + * The size, in bytes, of the photo. + */ + size: number; + /** + * The number of comments associated with the photo. + */ + comments_count: number; + /** + * A value that indicates whether comments are enabled for the photo. If + * comments can be made, this value is true; otherwise, it is false. + */ + comments_enabled: boolean; + /** + * The number of tags on the photo. + */ + tags_count: number; + /** + * A value that indicates whether tags are enabled for the photo. If + * users can tag the photo, this value is true; otherwise, it is false. + */ + tags_enabled: boolean; + /** + * A value that indicates whether this photo can be embedded. If this + * photo can be embedded, this value is true; otherwise, it is false. + */ + is_embeddable: boolean; + /** + * A URL of the photo's picture. + */ + picture: string; + /** + * The download URL for the photo. + * Warning: This value is not persistent. Use it immediately after + * making the request, and avoid caching. + */ + source: string; + /** + * The URL to upload photo content hosted in SkyDrive. This value is + * returned only if the wl.skydrive scope is present. + */ + upload_location: string; + /** + * Info about various sizes of the photo. + */ + images: IImageInfo[]; + /** + * A URL of the photo, hosted in SkyDrive. + */ + link: string; + /** + * The date, in ISO 8601 format, on which the photo was taken, or null + * if no date is specified. + */ + when_taken: string; + /** + * The height, in pixels, of the photo. + */ + height: number; + /** + * The width, in pixels, of the photo. + */ + width: number; + /** + * The type of object; in this case, "photo". + */ + type: string; + /** + * The location where the photo was taken. + * Note: The location object is not available for shared photos. + */ + location: ILocation; + /** + * The manufacturer of the camera that took the photo. + */ + camera_make: string; + /** + * The brand and model number of the camera that took the photo. + */ + camera_model: string; + /** + * The f-number that the photo was taken at. + */ + focal_ratio: number; + /** + * The focal length that the photo was taken at, typically expressed in + * millimeters for newer lenses. + */ + focal_length: number; + /** + * The numerator of the shutter speed (for example, the "1" in "1/15 s") + * that the photo was taken at. + */ + exposure_numerator: number; + /** + * The denominator of the shutter speed (for example, the "15" in "1/15 + * s") that the photo was taken at. + */ + exposure_denominator: number; + /** + * The object that contains permissions info for the photo. + */ + shared_with: ISharedWith; + /** + * The time, in ISO 8601 format, at which the photo was created. + */ + created_time: string; + /** + * The time, in ISO 8601 format, at which the photo was last updated. + */ + updated_time: string; + } + + /** + * The Search object contains info about the objects found in a user's + * SkyDrive that match the search query. See Search query parameters for + * info about formatting a search query request. + */ + interface ISearch { + /** + * An array of file and folder objects found in a user's SkyDrive that + * match the search query. + */ + data: IObject[]; + /** + * The path strings that reference the next and previous sets in a + * paginated response. + */ + paging?: { + /** + * Path string for the next set of results. + */ + next?: string; + /** + * Path string for the previous set of results. + */ + previous?: string; + }; + } + + /** + * The Tag object contains info about tags that are associated with a photo + * or a video on SkyDrive. The Live Connect REST API supports reading Tag + * objects. Use the wl.photos, and wl.skydrive scopes to read Tag objects. + * Use the wl.contacts_photos and wl.contacts_skydrive scopes to read the + * Tag objects that are associated with any photos that other users have + * shared with the user. + */ + interface ITag { + /** + * The Tag object's ID. + */ + id: string; + /** + * The user object for the tagged person. + */ + user: IUserInfo; + /** + * The center of the tag's horizontal position, measured as a + * floating-point percentage from 0 to 100, from the left edge of the + * photo. This value is not returned for Video objects. + */ + x: number; + /** + * The center of the tag's vertical position, measured as a + * floating-point percentage from 0 to 100, from the top edge of the + * photo. This value is not returned for Video objects. + */ + y: number; + /** + * The time, in ISO 8601 format, at which the tag was created. + */ + created_time: string; + } + + /** + * Contains work information for one employer. + */ + interface IWorkInfo { + /** + * Info about the user's employer. + */ + employer: { + /** + * The name of the user's employer, or null if the employer's name + * is not specified. + */ + name: string; + }; + /** + * Info about the user's work position. + */ + position: { + /** + * The name of the user's work position, or null if the name of the + * work position is not specified. + */ + name: string; + }; + } + + /** + * Information about one postal address. + */ + interface IPostalAddress { + /** + * The street address, or null if one is not specified. + */ + street: string; + /** + * The second line of the street address, or null if one is not + * specified. + */ + street_2: string; + /** + * The city of the address, or null if one is not specified. + */ + city: string; + /** + * The state of the address, or null if one is not specified. + */ + state: string; + /** + * The postal code of the address, or null if one is not specified. + */ + postal_code: string; + /** + * The region of the address, or null if one is not specified. + */ + region: string; + } + + /** + * The User object contains info about a user. The Live Connect REST API + * supports reading User objects. + */ + interface IUser { + /** + * The user's ID. + */ + id: string; + /** + * The user's full name. + */ + name: string; + /** + * The user's first name. + */ + first_name: string; + /** + * The user's last name. + */ + last_name: string; + /** + * The user's gender, or null if no gender is specified. + */ + gender: string; + /** + * The URL of the user's profile page. + */ + link: string; + /** + * The day of the user's birth date, or null if no birth date is + * specified. + */ + birth_day: number; + /** + * The month of the user's birth date, or null if no birth date is + * specified. + */ + birth_month: number; + /** + * The year of the user's birth date, or null if no birth date is + * specified. + */ + birth_year: number; + /** + * An array that contains the user's work info. + */ + work: IWorkInfo[]; + /** + * The user's email addresses. + */ + emails: { + /** + * The user's preferred email address, or null if one is not + * specified. + */ + preferred: string; + /** + * The email address that is associated with the account. + */ + account: string; + /** + * The user's personal email address, or null if one is not + * specified. + */ + personal: string; + /** + * The user's business email address, or null if one is not + * specified. + */ + business: string; + /** + * The user's "alternate" email address, or null if one is not + * specified. + */ + other: string; + }; + /** + * The user's postal addresses. + */ + addresses: { + /** + * The user's personal postal address. + */ + personal: IPostalAddress; + /** + * The user's business postal address. + */ + business: IPostalAddress; + }; + /** + * The user's phone numbers. + */ + phones: { + /** + * The user's personal phone number, or null if one is not + * specified. + */ + personal: string; + /** + * The user's business phone number, or null if one is not + * specified. + */ + business: string; + /** + * The user's mobile phone number, or null if one is not specified. + */ + mobile: string; + }; + /** + * The user's locale code. + */ + locale: string; + /** + * The time, in ISO 8601 format, at which the user last updated the + * object. + */ + updated_time: string; + } + + /** + * The Video object contains info about a user's videos on SkyDrive. The + * Live Connect REST API supports creating, reading, updating, and deleting + * Video objects. Use the wl.photos scope to read Video objects. Use the + * wl.contacts_photos scope to read albums, photos, and videos that other + * users have shared with the user. Use the wl.skydrive_update scope to + * create, update, or delete Video objects. + */ + interface IVideo { + /** + * The Video object's ID. + */ + id: string; + /** + * Info about the user who uploaded the video. + */ + from: IUserInfo; + /** + * The file name of the video. + */ + name: string; + /** + * A description of the video, or null if no description is specified. + */ + description: string; + /** + * The id of the folder where the item is stored. + */ + parent_id: string; + /** + * The size, in bytes, of the video. + */ + size: number; + /** + * The number of comments that are associated with the video. + */ + comments_count: number; + /** + * A value that indicates whether comments are enabled for the video. If + * comments can be made, this value is true; otherwise, it is false. + */ + comments_enabled: boolean; + /** + * The number of tags on the video. + */ + tags_count: number; + /** + * A value that indicates whether tags are enabled for the video. If + * tags can be set, this value is true; otherwise, it is false. + */ + tags_enabled: boolean; + /** + * A value that indicates whether this video can be embedded. If this + * video can be embedded, this value is true; otherwise, it is false. + */ + is_embeddable: boolean; + /** + * A URL of a picture that represents the video. + */ + picture: string; + /** + * The download URL for the video. + * Warning: This value is not persistent. Use it immediately after + * making the request, and avoid caching. + */ + source: string; + /** + * The URL to upload video content, hosted in SkyDrive. This value is + * returned only if the wl.skydrive scope is present. + */ + upload_location: string; + /** + * A URL of the video, hosted in SkyDrive. + */ + link: string; + /** + * The height, in pixels, of the video. + */ + height: number; + /** + * The width, in pixels, of the video. + */ + width: number; + /** + * The duration, in milliseconds, of the video run time. + */ + duration: number; + /** + * The bit rate, in bits per second, of the video. + */ + bitrate: number; + /** + * The type of object; in this case, "video". + */ + type: string; + /** + * The object that contains permission info. + */ + shared_with: ISharedWith; + /** + * The time, in ISO 8601 format, at which the video was created. + */ + created_time: string; + /** + * The time, in ISO 8601 format, at which the video was last updated. + */ + updated_time: string; + } + + //#endregion REST Object Information + + //#region API Properties Interfaces + + /** + * 'Properties' object passed into the WL.api method. + */ + interface IAPIProperties { + /** + * Contains the path to the REST API object. For information on + * specifying paths for REST objects, see REST reference. + * http://msdn.microsoft.com/en-us/library/live/hh243648.aspx + */ + path: string; + /** + * An HTTP method that specifies the action required for the API call. + * These actions are standard REST API actions: "COPY", "GET", "MOVE", + * "PUT", "POST", and "DELETE". + * @default "GET" + */ + method?: string; + /** + * A JSON object that specifies the REST API request body. The body + * property is used only for "POST" and "PUT" requests. + */ + body?: any; + } + + /** + * 'Properties' object passed into the WL.backgroundDownload method. + */ + interface IBackgroundDownloadProperties { + /** + * The path to the file to download. For information on specifying paths + * for REST objects, see REST reference. + * http://msdn.microsoft.com/en-us/library/live/hh243648.aspx + */ + path: string; + /** + * The file output object to which the downloaded file data is written. + */ + file_output?: Windows.Storage.StorageFile; + } + + /** + * 'Properties' object passed into the WL.backgroundUpload method. + */ + interface IBackgroundUploadProperties { + /** + * The path to the file to upload. + */ + path: string; + /** + * The name of the file to upload. + */ + file_name?: string; + /** + * The file input object to read the file from. Can be a + * Windows.Storage.StorageFile or an IFile. + */ + file_input?: any; + /** + * The file input stream to read the file from. + */ + stream_input?: Windows.Storage.Streams.IInputStream; + /** + * Indicates whether the uploaded file should overwrite an existing + * copy. Specify "true" to overwrite, "false" to not overwrite and for + * the WL.backgroundUpload method call to fail, or "rename" to not + * overwrite and enable SkyDrive to assign a new name to the uploaded + * file. + * @default "false". + */ + overwrite?: string; + } + + /** + * 'Properties' object passed into the WL.download method. + */ + interface IDownloadProperties { + /** + * The path to the file to download. For information on specifying paths + * for REST objects, see REST reference. + * http://msdn.microsoft.com/en-us/library/live/hh243648.aspx + */ + path: string; + } + + /** + * 'Properties' object passed into the WL.fileDialog method. + */ + interface IFileDialogProperties { + /** + * Specifies the type of SkyDrive file picker to display. Specify "open" + * to display the download version of the file picker. Specify "save" + * to display the upload version of the file picker. + */ + mode: string; + /** + * Specify only if the mode property is set to "open". Specifies how + * many files the user can select to download. Specify "single" for a + * single file. Specify "multi" for multiple files. + * @default "single" + */ + select?: string; + /** + * The color pallette to use for the file picker. Specify "white", + * "grey", or "transparent". + * @default "white" + */ + lightbox?: string; + } + + /** + * 'Properties' object passed into the WL.init method. + */ + interface IInitProperties { + /** + * Web apps: Required. + * Specifies your app's OAuth client ID for web apps. + * + * Windows Store apps using JavaScript: not needed. + */ + client_id?: string; + /** + * Contains the default redirect URI to be used for OAuth + * authentication. For web apps, the OAuth server redirects to this URI + * during the OAuth flow. + * + * For Windows Store apps using JavaScript, specifying this value will + * enable the library to return the authentication token. + */ + redirect_uri?: string; + /** + * The scope values used to determine which portions of user data the + * app has access to, if the user consents. + * + * For a single scope, use this format: scope: "wl.signin". For multiple + * scopes, use this format: scope: ["wl.signin", "wl.basic"]. + */ + scope?: any; + /** + * If set to "true", the library logs error info to the web browser + * console and notifies your app by means of the wl.log event. + * @default true + */ + logging?: boolean; + /** + * Web apps: optional. + * Windows Store apps using JavaScript: not applicable. + * If set to "true", the library attempts to retrieve the user's sign-in + * status from Live Connect. + * @default true + */ + status?: boolean; + /** + * Web apps: optional. + * Windows Store apps using JavaScript: not applicable. + * Specifies the OAuth response type value. If set to "token", the + * client receives the access token directly. If set to "code", the + * client receives an authorization code, and the app server that serves + * the redirect_uri page should retrieve the access_token from the OAuth + * server by using the authorization code and client secret. + * + * You can only set response_type to "code" for web apps. + * @default "token" + */ + response_type?: string; + /** + * Web apps: optional. + * Windows Store apps using JavaScript: not applicable. + * If set to "true", the library specifies a secure attribute when + * writing a cookie on an HTTPS page. + * @default "false" + */ + secure_cookie?: string; + } + + /** + * 'Properties' object passed into the WL.login method. + */ + interface ILoginProperties { + /** + * This parameter only applies to web apps. + * Contains the redirect URI to be used for OAuth authentication. This + * value overrides the default redirect URI that is provided in the call + * to WL.init. + */ + redirect_uri?: string; + /** + * Specifies the scopes to which the user who is signing in consents. + * + * For a single scope, use this format: scope: "wl.signin". For multiple + * scopes, use this format: scope: ["wl.signin", "wl.basic"]. + * + * If no scope is provided, the scope value of WL.init is used. If no + * scope is provided in WL.init or WL.login, WL.login returns an error. + * + * Note WL.login can request the "wl.offline_access" scope, but it + * requires a server-side implementation, and the WL.init function must + * set its response_type property to "code". For more info, see + * Server-side scenarios. + * http://msdn.microsoft.com/en-us/library/live/hh243649.aspx + */ + scope: any; + /** + * Windows Store apps using JavaScript: not applicable. + * Web apps: Optional. If the WL.init function's response_type object is + * set to "code" and the app uses server-flow authentication, the state + * object here can be used to track the web app's calling state on the + * web app server side. For more info, see the description of the state + * query parameter in the Server-side scenarios topic's "Getting an + * authorization code" section. + * http://msdn.microsoft.com/en-us/library/live/hh243649.aspx + */ + state?: string; + } + + /** + * 'Properties' object passed into the WL.ui method. + */ + interface IUIProperties { + /** + * Specifies the type of button to display. Specify "signin" to display + * the Live Connect sign-in button. Specify "skydrivepicker" to display + * the SkyDrive button. + */ + name: string; + /** + * The value of the id attribute of the
tag to display the button + * in. + */ + element: string; + /** + * Windows Store apps using JavaScript: not applicable. + * Web apps: Optional. If the name property is set to "signin", the + * WL.init function's response_type property is set to "code", and the + * app uses server-flow authentication, the state object here can be + * used to track the web app's calling state on the web app server side. + * For more info, see the description of the state query parameter in + * the Server-side scenarios topic's "Getting an authorization code" + * section. + * http://msdn.microsoft.com/en-us/library/live/hh243649.aspx + */ + state?: string; + } + + /** + * 'Properties' object passed into the WL.ui method when 'name' is set to + * 'skydrivepicker'. + */ + interface ISkyDrivePickerProperies extends IUIProperties { + /** + * The type of SkyDrive file picker button to display. Specify "save" to + * display the upload button. Specify "open" to display the download + * button. + */ + mode: string; + /** + * Required if the mode property is set to "open". Specifies how many + * files the user can select to download. Specify "single" for a single + * file. Specify "multi" for multiple files. + * @default "single" + */ + select?: string; + /** + * Defines the color pallette used for the file picker button. Valid + * values are "white" and "blue". + * @default "white" + */ + theme?: string; + /** + * Defines the color pallette used for the file picker dialog box. Valid + * values are "white", "gray", and "transparent". + * @default "white" + */ + lightbox?: string; + /** + * If the mode property is set to "save", specifies the function to call + * after the user clicks either Save or Cancel in the file picker. If + * the mode property is set to "open", specifies the function to call + * after the user clicks either Open or Cancel in the file picker. + */ + onselected?: Function; + /** + * Specifies the function to call if the selected files cannot be + * successfully uploaded or downloaded. + */ + onerror?: Function; + } + + /** + * 'Properties' object passed into the WL.ui method when 'name' is set to + * 'signin'. + */ + interface ISignInProperties extends IUIProperties { + /** + * Defines the brand, or type of icon, to be used with the Live Connect + * sign-in button. + * @default "windows" + */ + brand?: string; + /** + * Defines the color pallette used for the sign-in button. For Windows + * Store apps using JavaScript, valid values are "dark" and "light". + * For web apps, valid values are "blue" and "white". + */ + theme?: string; + /** + * Defines the type of button. + * @default "signin" + */ + type?: string; + /** + * If the value of the type property is set to "custom", this value + * specifies the sign-in text to be displayed in the button. + */ + sign_in_text?: string; + /** + * If the value of the type property is "custom", this value specifies + * the sign-out text to be displayed in the button. + */ + sign_out_text?: string; + /** + * Specifies the function to call after the user completes the sign-in + * process. + */ + onloggedin?: Function; + /** + * Specifies the function to call after the user completes the sign-out + * process. + */ + onloggedout?: Function; + /** + * Specifies the function to call whenever there is any error while the + * sign-in control is initializing or while the user is signing in. + */ + onerror?: Function; + } + + /** + * 'Properties' object passed into the WL.upload method. + */ + interface IUploadProperties { + /** + * The path to the file to upload. + */ + path: string; + /** + * The id attribute of the tag containing info about the file to + * upload. + */ + element: string; + /** + * Indicates whether the uploaded file should overwrite an existing + * copy. Specify true or "true" to overwrite, false or "false" to not + * overwrite and for the WL.upload method call to fail, or "rename" to + * not overwrite and enable SkyDrive to assign a new name to the + * uploaded file. + * @default "false" + */ + overwrite?: string; + } + + //#endregion API Properties Interfaces + + /** + * Represents the user's session. + */ + interface ISession { + /** + * The user's access token. + */ + access_token: string; + /** + * The authentication token. + */ + authentication_token: string; + /** + * A list of scopes that the app has requested and that the user has + * consented to. + * + * Note: This property is not available for Windows Store apps using + * JavaScript. + */ + scope?: string[]; + /** + * The amount of time remaining, in seconds, until the user's access + * token expires. + * + * Note: This property is not available for Windows Store apps using + * JavaScript. + */ + expires_in?: number; + /** + * The exact time when the session will expire. This time is expressed + * in the number of seconds since 1 January, 1970. + * + * Note: This property is not available for Windows Store apps using + * JavaScript. + */ + expires?: number; + } + + /** + * Represents the user's login status. + */ + interface ILoginStatus { + /** + * The sign-in status of the user. Valid values are "connected", + * "notConnected", or "unknown". + */ + status: string; + /** + * A JSON object that contains the properties of the current session. + */ + session: ISession; + } + + /** + * Represents the Microsoft.Live.API.Event object. + */ + interface IEventAPI { + /** + * Adds a handler to an event. + * @param event Required. The name of the event to which to add a + * handler. + * @param callback Required. Specifies the name of the callback function + * to handle the event. + * @returns This function can return the following errors: + * WL.Event.subscribe: The input parameter/property 'callback' must be + * included. + * WL.Event.subscribe: The input value for parameter/property 'event' + * is not valid. + */ + subscribe(event: string, callback: Function): void; + /** + * Removes a handler from an event. + * @param event Required. The name of the event from which to remove a + * handler. + * @param callback Optional. Removes the callback function from the + * event. If this parameter is omitted or is null, all callback + * functions that are registered to the event are removed. Removes the + * callback function from the specified event. + */ + unsubscribe(event: string, callback?: Function): void; + } + + /** + * Returned from a successful file picker operation. + */ + interface IFilePickerResult { + /** + * Contains data concerning the user's picked files. + */ + data: { + /** + * Information on files choden in the picker. + */ + files?: IFile[]; + /** + * Information on folders chosen in the picker. + */ + folders?: IFolder[]; + } + } + + /** + * The promise API implemented by this library. + */ + interface IPromise { + /** + * Adds event listeners for particular events. + * @param onSuccess Called when the promised event successfully occurs. + * @param onError Called when the promised event fails to occur. Could + * be an IError or an IJSError. + * @param onProgress Called to indicate that the promised event is + * making progress toward completion. + */ + then(onSuccess: (response: T) => void, + onError?: (error: any) => void, + onProgress?: (progress: any) => void): IPromise; + /** + * Cancels the pending request represented by the Promise, and triggers + * the error callback if the promised event has not yet occurred. + */ + cancel(): void; + } + + /** + * An error returned by the JavaScript library, as opposed to an error + * object from the REST API (which we represent with IError). + */ + interface IJSError { + /** + * The error code. + */ + error: string; + /** + * A description of the error. + */ + error_description: string; + } + + /** + * The Live Connect JavaScript API (Windows 8 and web), together with the + * REST API, enables apps to read, update, and share user data by using the + * JavaScript programming language. The JavaScript API (Windows 8 and web) + * provides methods for signing users in and out, getting user status, + * subscribing to events, creating UI controls, and calling the + * Representational State Transfer (REST) API. + */ + interface API { + /** + * Makes a call to the Live Connect Representational State Transfer + * (REST) API. This method encapsulates a REST API request, and then + * calls a callback function to process the response. + * @param properties Required. A JSON object that contains properties + * that are necessary to make the REST API call. + * @param callback Specifies a callback function that is executed when + * the REST API call is complete. The callback function takes the API + * response object as a parameter. The response object exposes the + * data returned from Live Connect, or, if an error occurs, an error + * property that contains the error code. + * @returns Returns a Promise object. This object's then method provides + * the onSuccess, onError, and onProgress parameters to enable your + * code to handle a successful, failed, and in-progress call to the + * corresponding WL.api method, respectively. + */ + api(properties: IAPIProperties, + callback?: (response: any) => void): IPromise; + /** + * Makes a call to download a file from Microsoft SkyDrive. + * + * **Important**: WL.backgroundDownload is supported only for use with + * Windows Store apps using JavaScript. If you are writing a web app, + * use WL.download instead. + * @param properties Required. A JSON object that contains properties + * that are necessary to make the REST API call. + * @param Optional. Specifies a callback function that is executed when + * the REST API call is complete. The callback function takes the API + * response object as a parameter. The response object exposes the + * data that is returned from Live Connect, or, if an error occurs, an + * error property that contains the error code. + * @returns Returns a Promise object. This object's then method accepts + * callback functions for onSuccess, onError, and onProgress to enable + * your code to handle a successful, failed, and in-progress call to + * the corresponding WL.download method, respectively. + * The onSuccess callback is passed a response object that contains + * content_type and stream properties, representing the downloaded + * file's content type and file stream, respectively. + */ + backgroundDownload(properties: IBackgroundDownloadProperties, + callback?: (response: any) => void): IPromise; + /** + * Makes a call to upload a file to Microsoft SkyDrive. + * + * **Important**: WL.backgroundUpload is supported only for use with + * Windows Store apps using JavaScript. If you are writing a web app, + * use WL.upload instead. + * @param properties Required. A JSON object that contains properties + * that are necessary to make the REST API call. + * @param callback Optional. Specifies a callback function that is + * executed when the REST API call is complete. The callback function + * takes the API response object as a parameter. The response object + * exposes the data returned from Live Connect, or if an error occurs, + * an error property that contains the error code. + * @returns Returns a Promise object. For Windows Store apps using + * JavaScript, this object's then method accepts callback functions + * for onSuccess, onError, and onProgress to enable your code to + * handle a successful, failed, and in-progress call to the + * corresponding WL.backgroudUpload method, respectively. + */ + backgroundUpload(properties: IBackgroundUploadProperties, + callback?: (response: any) => void): IPromise; + /** + * Specifies whether the current user can be signed out of his or her + * Microsoft account. + * + * For Windows Store apps using JavaScript, you can use this function to + * determine whether you should display a control to the user to enable + * him or her to sign out of his or her Microsoft account. If this + * function returns true, you should display the control. However, if + * this function returns false, you should not display this control, as + * attempting to sign out the user in this case will have no effect. + * + * For web apps, this function always returns true. + * @returns Returns true if the user can be signed out; otherwise, + * returns false if the user can't be signed out. + */ + canLogout(): boolean; + /** + * Makes a call to download a file from Microsoft SkyDrive. + * + * **Important**: WL.download is supported only for use with web apps. + * If you are writing a Windows Store app using JavaScript, use + * WL.backgroundDownload instead. + * @param properties Required. A JSON object that contains properties + * that are necessary to make the REST API call. + * @param callback Specifies a callback function that is executed when + * the REST API call is complete. The callback function takes the API + * response object as a parameter. The response object exposes the + * data that is returned from Live Connect, or, if an error occurs, an + * error property that contains the error code. + * @returns Returns a Promise object. This object's then method provides + * the onError parameter to enable your code to handle a failed call + * to the corresponding WL.download method. + */ + download(properties: IDownloadProperties, + callback?: (response: any) => void): IPromise; + Event: IEventAPI; + /** + * Displays the Microsoft SkyDrive file picker, which enables + * JavaScript-based web apps to display a pre-built, consistent user + * interface that enables a user to select files to upload and download + * to and from his or her SkyDrive storage location. + * @param properties Required. A JSON object containing properties for + * displaying the button. + * @param callback Optional. A callback function that is executed after + * the user finishes interacting with the SkyDrive file picker. + * @returns Returns a Promise object. This object's then method provides + * the onSuccess and onError parameters to enable your code to handle + * a successful and failed call to the corresponding WL.fileDialog + * method, respectively. + */ + fileDialog(properties: IFileDialogProperties, + callback?: (response: any) => void): IPromise; + /** + * Returns the sign-in status of the current user. If the user is signed + * in and connected to your app, this function returns the session + * object. This is an asynchronous function that returns the user's + * status by contacting the Live Connect authentication web service. + * @param callback Returns the sign-in status of the current user. If + * the user is signed in and connected to your app, this function + * returns the session object. This is an asynchronous function that + * returns the user's status by contacting the Live Connect + * authentication web service. + * @param force Optional. If set to "true", the function contacts the + * Live Connect authentication web service to determine the user's + * status. If set to "false" (the default), the function can return + * the user status that is currently in memory, if there is one. If + * the user's status has already been retrieved, the library can + * return the cached value. However, you can force the library to + * retrieve current status by setting the force parameter to "true". + * @returns Returns a Promise object. This object's then method provides + * the onSuccess and onError parameters to enable your code to handle + * a successful and failed call to the corresponding WL.getLoginStatus + * method, respectively. + * In the body of the onSuccess function, a status object is returned, + * which contains the user's sign-in status and the session object. + */ + getLoginStatus(callback?: (status: ILoginStatus) => void, + force?: boolean): IPromise; + /** + * Retrieves the current session object synchronously, if a session + * object exists. For situations in which performance is critical, such + * as page loads, use the asynchronous WL.getLoginStatus method instead. + * @returns Returns the current session as a session object instance. + */ + getSession(): ISession; + /** + * Initializes the JavaScript library. An app must call this function on + * every page before making other function calls in the library. The app + * should call this function before making function calls that subscribe + * to events. If the JavaScript library has already been initialized on + * the page, calling this function succeeds silently; the client_id and + * redirect_uri parameters are not validated. + * @param properties Required. A JSON object with initialization + * properties. + * @returns Returns a Promise object. This object's then method provides + * the onSuccess and onError parameters to enable your code to handle + * a successful and failed call to the corresponding WL.init method, + * respectively. + * When the onSuccess callback is invoked, a login status object is + * passed in as parameter that indicates the current user's login + * status. + */ + init(properties: IInitProperties): IPromise; + /** + * Signs in the user or expands the user's list of scopes. Because this + * function can result in launching the consent page prompt, you should + * call it only in response to a user action, such as clicking a button. + * Otherwise, the user's web browser might block the popup. + * + * Typically, this function is used by apps that define their own + * sign-in controls, or by apps that ask users to grant additional + * permissions during an activity. For example, to enable a user to post + * his or her status to Live Connect, your app may have to prompt the + * user for permission and call this function with an expanded scope. + * + * If you call this function when the user has already consented to the + * requested scope and is already signed in, the callback function is + * invoked immediately with the current session. + * This function logs errors to the web browser console. + * @param properties Required. A JSON object with login properties. + * @param callback Optional. Specifies a callback function to execute + * when sign-in is complete. The callback function takes the status + * object as a parameter. For a description of the status object, see + * WL.getLoginStatus. If you do not specify a callback function, your + * app can still get the sign-in callback info by listening for an + * auth.sessionChange or auth.statusChange event. + * @returns Returns a Promise object. This object's then method provides + * the onSuccess, onError, and onProgress parameters to enable your + * code to handle a successful, failed, and in-progress call to the + * corresponding WL.login method, respectively. + */ + login(properties: ILoginProperties, + callback?: (status: any) => void): IPromise; + /** + * Signs the user out of Live Connect and clears any user state that is + * maintained by the JavaScript library, such as cookies. If the user + * account is connected, this function logs out the user from the app, + * but not from the PC. This function is useful primarily for websites + * that do not use the sign-in control. + * @param callback Optional. Specifies a callback function that is + * executed when sign-out is complete. The callback function takes the + * status object as a parameter. For a description of the status + * object, see WL.getLoginStatus. If you do not specify a callback + * function, your app can still get the sign-out callback info by + * listening for an auth.sessionChange or auth.statusChange event. + * @returns Returns a Promise object. This object's then method provides + * the onSuccess, onError, and onProgress parameters to enable your + * code to handle a successful, failed, and in-progress call to the + * corresponding WL.logout method, respectively. + */ + logout(callback?: (status: ILoginStatus) => void): IPromise; + /** + * Displays either the Live Connect sign-in button or the Microsoft + * SkyDrive file picker button. The sign-in button either prompts the + * user for his or her Microsoft account credentials if he or she is not + * signed in or else signs out the user if he or she is signed in. The + * file picker button displays the SkyDrive file picker to help the user + * select files to upload or download to or from his or her SkyDrive + * storage location. + * @param properties Required. A JSON object containing properties for + * displaying the button. + * @param callback Optional. A callback function that is executed after + * the sign-in button or file picker button is displayed. + * Note: Do not use the callback parameter to run code after the user + * finishes interacting with the sign-in button or file picker. Use a + * combination of the onselected, onloggedin, onloggedout, and onerror + * properties as previously described. + */ + ui(properties: IUIProperties, callback?: () => void): void; + /** + * Makes a call to upload a file to Microsoft SkyDrive. + * + * **Important**: WL.upload is supported only for use with web apps. If + * you are writing a Windows Store app using JavaScript, use + * WL.backgroundUpload instead. + * @param properties Required. A JSON object that contains properties + * that are necessary to make the REST API call. + * @param callback Optional. Specifies a callback function that is + * executed when the REST API call is complete. The callback function + * takes the API response object as a parameter. The response object + * exposes the data returned from Live Connect, or if an error occurs, + * an error property that contains the error code. + * @returns Returns a Promise object. This object's then method provides + * the onSuccess, onError, and onProgress parameters to enable your + * code to handle a successful, failed, and in-progress call to the + * corresponding WL.upload method, respectively; however, the + * onProgress parameter applies to newer web browsers such as Internet + * Explorer 10 only. + */ + upload(properties: IUploadProperties, + callback?: (response: any) => void): IPromise; + } +} + +/** + * The WL object is a global object that encapsulates all functions of the + * JavaScript API (Windows 8 and web). Your app uses the WL object to call all + * of the JavaScript API (Windows 8 and web) functions. + */ +declare var WL: Microsoft.Live.API; diff --git a/microsoft-live-connect/microsoft-live-connect.ts b/microsoft-live-connect/microsoft-live-connect.ts new file mode 100644 index 0000000000..98fcf5a3b7 --- /dev/null +++ b/microsoft-live-connect/microsoft-live-connect.ts @@ -0,0 +1,1048 @@ +/// + +/** + * From: http://msdn.microsoft.com/en-us/library/live/hh550838.aspx + */ +function createFolder_onClick() { + var login_props: Microsoft.Live.ILoginProperties = { + scope: "wl.skydrive_update" + }; + WL.login(login_props).then( + function (response) { + var newFolder: Microsoft.Live.INewFolder = { + "name": "This is a new folder", + "description": "A new folder" + }, api_properties: Microsoft.Live.IAPIProperties = { + path: "me/skydrive", + method: "POST", + body: newFolder + }; + WL.api(api_properties).then( + function (response) { + document.getElementById("infoArea").innerText = + "Created folder. Name: " + response.name + ", ID: " + response.id; + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("infoArea").innerText = + "Error calling API: " + responseFailed.error.message; + } + ); + }, + function (responseFailed: Microsoft.Live.IJSError) { + document.getElementById("infoArea").innerText = + "Error signing in: " + responseFailed.error_description; + } + ); +} + +/** + * From: http://msdn.microsoft.com/en-us/library/live/jj219386.aspx + */ +function downloadFile_onClick() { + var picker = setupSavePicker(); + picker.pickSaveFileAsync().then( + function (file) { + if (file && (file instanceof Windows.Storage.StorageFile)) { + WL.login({ + scope: "wl.skydrive" + }).then( + function (response) { + WL.backgroundDownload({ + path: "file.8c8ce076ca27823f.8C8CE076CA27823F!129/picture?type=thumbnail", + file_output: file + }).then( + function (response) { + document.getElementById("infoLabel").innerText = "Downloaded file."; + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("infoLabel").innerText = + "Error calling API: " + responseFailed.error.message; + } + ); + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("infoLabel").innerText = + "Error signing in: " + responseFailed.error.message; + } + ); + } + else { + document.getElementById("infoLabel").innerText = "Cannot download file."; + } + }, + function (fileFailed) { + document.getElementById("infoLabel").innerText = "Cannot download file."; + } + ); +} + +function setupSavePicker() { + var savepicker = new Windows.Storage.Pickers.FileSavePicker(); + savepicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary; + // XXX: Type hack for other typings. Apparently string[] isn't an IVector. + (savepicker.fileTypeChoices).insert("Picture", [".jpg"]); + return savepicker; +} + +/** + * From: http://msdn.microsoft.com/en-us/library/live/jj219387.aspx + */ +function uploadFile_onClick() { + var picker = setupOpenPicker(); + var filePickOp = picker.pickSingleFileAsync().then( + function (file) { + WL.login({ + scope: "wl.skydrive_update" + }).then( + function (response) { + WL.backgroundUpload({ + path: "me/skydrive", + file_name: file.name, + file_input: file, + overwrite: "rename" + }).then( + function (response) { + document.getElementById("infoLabel").innerText = "Uploaded file."; + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("infoLabel").innerText = + "Error calling API: " + responseFailed.error.message; + } + ); + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("infoLabel").innerText = + "Error signing in: " + responseFailed.error.message; + } + ); + }, + function (fileFailed) { + document.getElementById("infoLabel").innerText = "Cannot upload file."; + } + ); +} + +function setupOpenPicker() { + var openpicker = new Windows.Storage.Pickers.FileOpenPicker(); + openpicker.fileTypeFilter.replaceAll(["*"]); + return openpicker; +} + +/** + * From: http://msdn.microsoft.com/en-us/library/live/hh550839.aspx + */ +function downloadFile() { + WL.login({ + scope: "wl.skydrive" + }).then( + function (response) { + WL.download({ + path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/content" + }).then( + function (response) { + // Will not be called for web apps. + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("info").innerText = + "Error downloading file: " + responseFailed.error.message; + } + ); + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("info").innerText = + "Error signing in: " + responseFailed.error.message; + } + ); +} + +WL.Event.subscribe("auth.login", function () { }); +WL.Event.unsubscribe("auth.logout"); + +/** + * From: http://msdn.microsoft.com/en-us/library/live/jj219389.aspx + */ +function uploadFile_fileDialog() { + WL.fileDialog({ + mode: "save" + }).then( + function (response) { + WL.upload({ + path: response.data.folders[0].id, + element: "file", + overwrite: "rename" + }).then( + function (response) { + document.getElementById("info").innerText = + "File uploaded."; + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("info").innerText = + "Error uploading file: " + responseFailed.error.message; + } + ); + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("info").innerText = + "Error getting folder info: " + responseFailed.error.message; + } + ); +} + +/** + * From: http://msdn.microsoft.com/en-us/library/live/hh550842.aspx + */ +function loginStatus() { + WL.getLoginStatus(function (response) { alert("Your status is: " + response.status) }); +} + +/** + * From http://msdn.microsoft.com/en-us/library/live/hh550843.aspx + */ +function onSessionChange() { + var session = WL.getSession(); + if (session) { + document.getElementById("infoLabel").innerText = + "Something about the session changed."; + } + else { + document.getElementById("infoLabel").innerText = + "Signed out or session error."; + } +} + +/** + * From: http://msdn.microsoft.com/en-us/library/live/hh550844.aspx + */ +WL.init({ + client_id: "APP_CLIENT_ID", + redirect_uri: "REDIRECT_URL", + scope: "wl.signin", + response_type: "token" +}); +WL.init({ scope: "wl.signin" }); + +/** + * From: http://msdn.microsoft.com/en-us/library/live/hh550845.aspx + */ +function streamlineAccountReg_onClick() { + WL.login({ + scope: ["wl.signin", "wl.basic", "wl.birthday", "wl.emails"] + }).then( + function (response) { + WL.api({ + path: "me", + method: "GET" + }).then( + function (response) { + document.getElementById("first_name").innerText = response.first_name; + document.getElementById("last_name").innerText = response.last_name; + document.getElementById("email").innerText = response.emails.preferred; + document.getElementById("gender").innerText = response.gender; + document.getElementById("birthday").innerText = + response.birth_month + " " + response.birth_day + " " + response.birth_year; + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("infoArea").innerText = + "Error calling API: " + responseFailed.error.message; + } + ); + }, + function (responseFailed: Microsoft.Live.IJSError) { + document.getElementById("infoArea").innerText = + "Error signing in: " + responseFailed.error_description; + } + ); +} + +/** + * From: http://msdn.microsoft.com/en-us/library/live/hh550846.aspx + */ +function signUserOut() { + WL.logout(); +} + +/** + * From: http://msdn.microsoft.com/en-us/library/live/hh550847.aspx + */ +var signInProps: Microsoft.Live.ISignInProperties = { + name: "signin", + element: "signin" +}; +WL.ui(signInProps); +var skyDriveProps: Microsoft.Live.ISkyDrivePickerProperies = { + name: "skydrivepicker", + element: "uploadFile_div", + mode: "save", + onselected: onUploadFileCompleted, + onerror: onUploadFileError +}; +WL.ui(skyDriveProps); + +function onUploadFileCompleted(response: Microsoft.Live.IFilePickerResult) { + WL.upload({ + path: response.data.folders[0].id, + element: "file", + overwrite: "rename" + }).then( + function (response) { + document.getElementById("info").innerText = + "File uploaded."; + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("info").innerText = + "Error uploading file: " + responseFailed.error.message; + } + ); +}; + +function onUploadFileError(response: Microsoft.Live.IError) { + document.getElementById("info").innerText = + "Error getting folder info: " + response.error.message; +} +skyDriveProps = { + name: "skydrivepicker", + element: "downloadFile_div", + mode: "open", + select: "multi", + onselected: onDownloadFileCompleted, + onerror: onDownloadFileError +}; +WL.ui(skyDriveProps); + +function onDownloadFileCompleted(response: Microsoft.Live.IFilePickerResult) { + var msg = "", folder, file; + // For each folder selected... + if (response.data.folders.length > 0) { + for (folder = 0; folder < response.data.folders.length; folder++) { + // Use folder IDs to iterate through child folders and files as needed. + msg += "\n" + response.data.folders[folder].id; + } + } + // For each file selected... + if (response.data.files.length > 0) { + for (file = 0; file < response.data.files.length; file++) { + // Use file IDs to iterate through files as needed. + msg += "\n" + response.data.files[file].id; + } + } + document.getElementById("info").innerText = + "Selected folders/files:" + msg; +}; + +function onDownloadFileError(responseFailed: Microsoft.Live.IError) { + document.getElementById("info").innerText = + "Error getting folder/file info: " + responseFailed.error.message; +} + +/** + * From: http://msdn.microsoft.com/en-us/library/live/hh550848.aspx + */ +function uploadFile() { + WL.login({ + scope: "wl.skydrive_update" + }).then( + function (response) { + WL.upload({ + path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!170", + element: "file", + overwrite: "rename" + }).then( + function (response) { + document.getElementById("info").innerText = + "File uploaded."; + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("info").innerText = + "Error uploading file: " + responseFailed.error.message; + } + ); + }, + function (responseFailed: Microsoft.Live.IError) { + document.getElementById("info").innerText = + "Error signing in: " + responseFailed.error.message; + } + ); +} + + +//#region From: http://msdn.microsoft.com/en-us/library/live/hh243648.aspx +/** + * This region contains REST object examples, and verifies that they pass + * type checking. + */ +var albumCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "album.8c8ce076ca27823f.8C8CE076CA27823F!126", + "from": { + "name": "Roberto Tamburello", + "id": "8c8ce076ca27823f" + }, + "name": "My Sample Album 1", + "description": "", + "parent_id": "folder.de57f4126ed7e411", + "upload_location": "https://apis.live.net/v5.0/folder.de57f4126ed7e411.DE57F4126ED7E411!126/files/", + "is_embeddable": true, + "count": 4, + "link": "https://cid-8c8ce076ca27823f.skydrive.live.com/redir.aspx?page\u003dself\u0026resid\u003d8C8CE076CA27823F!126\u0026type\u003d5", + "type": "album", + "shared_with": { + "access": "Everyone (public)" + }, + "created_time": "2011-04-21T23:19:47+0000", + "updated_time": "2011-04-22T19:18:12+0000", + // XXX: The API example documentation missed this property, but it has been wrong in the past... + "client_updated_time": "2011-04-22T19:18:12+0000", + } + ] +}; +var newAlbum: Microsoft.Live.INewAlbum = { + "name": "Vacation 2011", + "description": "Photos from our fun vacation." +}; +var audioCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!144", + "from": { + "name": "Stig Struve-Christensen", + "id": "a6b2a7e8f2515e5e" + }, + "name": "SampleAudio.mp3", + "description": null, + "parent_id": "folder.a6b2a7e8f2515e5e", + "size": 8414449, + "upload_location": "https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!144/content/", + "comments_count": 0, + "comments_enabled": false, + "is_embeddable": false, + "source": "http://storage.live.com/s1p60U8Xs4UzIXTScrTioalE-ZaVFiDQBA15MS2BwcsuNjfG64Z2fw-DAjXnPuqC47YR40_xAoPD8aRGhtna9ZFZ9_oO4BTz4CWF973DTXMxc5U3TntcQ9qEA/SampleAudio.mp3:Binary", + "link": "https://skydrive.live.com/redir.aspx?cid\u003d22688711f5410e6c\u0026page\u003dview\u0026resid\u003d22688711F5410E6C!582\u0026parid\u003d22688711F5410E6C!581", + "type": "audio", + "title": "My Sample Audio", + "artist": "My Favorite Artist", + "album": "My Favorite Album", + "album_artist": "My Favorite Artist", + "genre": "Easy Listening", + "duration": 225000, + "picture": "https://storage.live.com/items/A6B2A7E8F2515E5E!144:MobileReady/SampleAudio.mp3?psid=1&ck=0&ex=720", + "shared_with": { + "access": "Just me" + }, + "created_time": "2012-09-23T22:00:57+0000", + "updated_time": "2012-09-03T22:00:57+0000" + } + ] +}; + +var newAudioResponse: Microsoft.Live.INewFileResponse = { + "id": "ID of the new audio", + "name": "The file's name and file extension", + "source": "URL where the audio can be downloaded from" +}; + +var newAudio: Microsoft.Live.INewAudio = { + "name": "SampleAudioChanged.wav", + "description": "Holiday Concert" +}; + +var calendarCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "calendar.42d4dbc866f94c83849c88c6eb9985bc", + "name": "Birthday calendar", + "description": "If you have birthdays listed for your contacts, they'll appear on this calendar. You can add more birthdays, but you can't add other types of events.", + "created_time": "2011-08-05T19:41:04+0000", + "updated_time": "2011-08-05T19:41:04+0000", + "from": { + "name": null, + "id": null + }, + "is_default": false, + "subscription_location": null, + "permissions": "read" + } + ] +}; + +var newCalendar: Microsoft.Live.INewCalendar = { + "name": "Summer Events", + "summary": "Things we are doing this summer." +}; + +var newCalendarSub: Microsoft.Live.INewCalendarSubscription = { + "name": "Soccer League", + "subscription_location": "ical.sharedcalendars.com/98754auv" +}; + +var commentCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "comment.22688711f5410e6c.22688711f0410e6c!818.22688711F5410E6C!979", + "from": { + "name": "Roberto Tamburello", + "id": "8c8ce076ca27823f" + }, + "message": "A lighthouse built on some rocks.", + "created_time": "2011-04-21T23:21:28+0000" + } + ] +}; + +var newContact: Microsoft.Live.INewContact = { + "first_name": "", + "last_name": "", + "emails": { + "preferred": "", + "personal": "", + "business": "", + "other": "" + }, + "work": [ + { + "employer": { + "name": "" + } + } + ] +}; + +var contactCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "contact.b4466224b2ca42798c3d4ea90c75aa56", + "first_name": "Henrik", + "last_name": "Jensen", + "name": "Henrik Jensen", + "is_friend": false, + "is_favorite": false, + "user_id": null, + "email_hashes": [ + "9ecdb19f4eb8e04304c5d1280368c42e85b6e4fe39f08b0c837ec592b905a620", + "fc05492f50da6488aa14dcf221d395bcb29a4e43b43b250d60c68df4f831cad3" + ], + "updated_time": "2011-04-22T00:11:13+0000", + "birth_day": 29, + "birth_month": 3 + + } + ] +}; + +var errorObj: Microsoft.Live.IError = { + "error": { + "code": "request_token_expired", + "message": "The provided access token has expired." + } +}; + +var event: Microsoft.Live.IEvent = { + "id": "event.611afb17fa9448f28cdb8277e8ffeb77.e9f015000d0249ce847c5306a25d7d75", + "name": "Global Project Risk Management Meeting", + "description": "Generate and assess risks for the project", + "calendar_id": "calendar.611afb17fa9448f28cdb8277e8ffeb77", + "from": { + "name": "William Flash", + "id": "de57f4126ed7e411" + }, + "start_time": "2011-04-20T01:00:00+0000", + "end_time": "2011-04-20T02:00:00+0000", + "location": "Building 81, Room 9981, 123 Anywhere St., Redmond WA 19599", + "is_all_day_event": false, + "is_recurrent": false, + "recurrence": null, + "reminder_time": null, + "availability": "busy", + "visibility": "public", + "created_time": "2011-03-14T23:01:31+0000", + "updated_time": "2011-04-19T20:23:03+0000" +}; + +var newEvent: Microsoft.Live.INewEvent = { + "name": "Global Project Risk Management Meeting", + "description": "Generate and assess risks for the project", + "start_time": "2011-04-20T01:00:00-07:00", + "end_time": "2011-04-20T02:00:00-07:00", + "location": "Building 81, Room 9981, 123 Anywhere St., Redmond WA 19599", + "is_all_day_event": false, + "availability": "busy", + "visibility": "public" +}; + +var eventResponse: Microsoft.Live.INewEventResponse = { + "name": "Global Project Risk Management Meeting", + "description": "Generate and assess risks for the project", + "start_time": "2011-04-20T01:00:00+0000", + "end_time": "2011-04-20T02:00:00+0000", + "location": "Building 81, Room 9981, 123 Anywhere St., Redmond WA 19599", + "is_all_day_event": false, + "is_recurrent": false, + "recurrence": null, + "reminder_time": null, + "availability": "busy", + "visibility": "public", + "updated_time": "2011-04-19T20:23:03+0000" +}; + +var file: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "file.22688711f5410e6c.22688711F5410E6C!942", + "from": { + "name": "William Flash", + "id": "22688711f5410e6c" + }, + "name": "Processing.docx", + "description": null, + "parent_id": "folder.22688711f5410e6c.22688711F5410E6C!479", + "size": 12692, + "upload_location": "https://apis.live.net/v5.0/file.22688711f5410e6c.22688711F5410E6C!942/content/", + "comments_count": 0, + "comments_enabled": true, + "is_embeddable": false, + "source": "http://storage.live.com/s1pEwo9qzyT4_BJZqMNm-aVzgLo-WRsQGzjzFsXjyREuQG5pDYr237vKz3i2pmqFuniYPzsuIZAOCUMB_gdfKCUpLpVcaAMXGrk4T7jOWenRniCv9vex7GWfSvy-XCVBVnU/Processing.docx:Binary", + "link": "https://skydrive-df.live.com/redir.aspx?cid\u003d22688711f5410e6c\u0026page\u003dview\u0026resid\u003d22688711F5410E6C!942\u0026parid\u003d22688711F5410E6C!479", + "type": "file", + "shared_with": { + "access": "Everyone (public)" + }, + "created_time": "2011-10-12T23:18:23+0000", + "updated_time": "2011-10-12T23:18:23+0000", + // XXX: Not specified in example. Could be a bug in documentation, or maybe these are optional fields. + "client_updated_time": "2011-10-12T23:18:23+0000", + "sort_by": null + } + ] +}; + +var fileDownload: Microsoft.Live.IFileDownloadLink = { + "location": "..." +}; + +var newFileResponse: Microsoft.Live.INewFileResponse = { + "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!184", + "name":"MyNewFile.txt", + "source": "http://storage.live.com/s1pasGKzgXFvuEQCbxGtOyIpboUVH1OCHoRzUJNDDwL0zVoidb0RRrNVk88hUrOEve5OMT7eCkuxPbop7dV9tMJQ-eE8SCQ28vFv9ZgPnDGwQMRm-0FeG3-KEY4HL9dQSw9/MyNewFile.txt:Binary,Default/MyNewFile.txt" +}; + +var folderCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "folder.8c8ce076ca27823f.8C8CE076CA27823F!142", + "from": { + "name": "Roberto Tamburello", + "id": "8c8ce076ca27823f" + }, + "name": "My Sample Folder in Album 1", + "description": "", + "parent_id": "folder.de57f4126ed7e411", + "upload_location": "https://apis.live.net/v5.0/folder.de57f4126ed7e411.DE57F4126ED7E411!126/files/", + "is_embeddable": true, + "count": 3, + "link": "https://cid-8c8ce076ca27823f.skydrive.live.com/redir.aspx?page\u003dself\u0026resid\u003d8C8CE076CA27823F!142\u0026parid\u003d8C8CE076CA27823F!126\u0026type\u003d5", + "type": "folder", + "shared_with": { + "access": "Just me" + }, + "created_time": "2011-04-22T00:36:30+0000", + "updated_time": "2011-04-22T19:18:12+0000", + // XXX: Omitted in the example. + "client_updated_time": "???", + "sort_by": "???" + } + ] +}; + +var newFolder: Microsoft.Live.INewFolder = { + "name": "Informative Spreadsheets", + "description": "A folder full of useful data visualizations." +}; + +var friendCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "d09ea18fafc39a0c", + "name": "Henrik Jensen" + } + ] +}; + +var permissionsCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "wl.basic": 1, + "wl.offline_access": 1, + "wl.signin": 1 + } + ] +}; + +var photoCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "file.de57f4126ed7e411.DE57F4126ED7E411!128", + "from": { + "name": "Nuno Bento", + "id": "de57f4126ed7e411" + }, + "name": "Maui-2012_0034.JPG", + "description": null, + "parent_id": "folder.de57f4126ed7e411.DE57F4126ED7E411!126", + "size": 561683, + "comments_count": 1, + "comments_enabled": true, + "tags_count": 0, + "tags_enabled": true, + "is_embeddable": true, + "picture": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:Thumbnail", + "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:HighRes", + "upload_location": "https://apis.live.net/v5.0/file.de57f4126ed7e411.DE57F4126ED7E411!128/content/", + "images": [ + { + "height": 450, + "width": 600, + "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:WebReady", + "type": "normal" + }, { + "height": 132, + "width": 176, + "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:MobileReady", + "type": "album" + }, { + "height": 72, + "width": 96, + "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:Thumbnail", + "type": "thumbnail" + }, { + "height": 1200, + "width": 1600, + "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:HighRes", + "type": "full" + } + ], + "link": "https://skydrive.live.com/redir.aspx?cid\u003dde57f4126ed7e411\u0026page\u003dview\u0026resid\u003dDE57F4126ED7E411!128\u0026parid\u003dDE57F4126ED7E411!126", + "when_taken": "2008-03-24T23:41:53+0000", + "height": 1200, + "width": 1600, + "type": "photo", + "location": { + "latitude": 47.65316, + "longitude": -122.135911, + "altitude": 43 + }, + "camera_make": "MyManufacturer", + "camera_model": "MyModel", + "focal_ratio": 2.8, + "focal_length": 3.85, + "exposure_numerator": 1, + "exposure_denominator": 15, + "shared_with": { + "access": "Everyone (public)" + }, + "created_time": "2012-12-03T18:14:03+0000", + "updated_time": "2012-12-03T18:31:01+0000" + } + ] +}; + +var tag: Microsoft.Live.ITag = { + "id": "tag.22688711f5410e6c.22688711f5410e6c!767.PRaXZrdHI1uYGQYi9CU0StrzHak", + "user": { + "name": "Roberto Tamburello", + "id": "8c8ce076ca27823f" + }, + "x": 43.8986, + "y": 54.4138, + "created_time": "2011-04-22T01:17:00+0000" +}; + +var user: Microsoft.Live.IUser = { + "id": "8c8ce076ca27823f", + "name": "Roberto Tamburello", + "first_name": "Roberto", + "last_name": "Tamburello", + // XXX: Not in the REST API example, but is included in the WL.ui example. + "gender": null, + "link": "http://cid-8c8ce076ca27823f.profile.live.com/", + "birth_day": 20, + "birth_month": 4, + "birth_year": 2010, + "work": [ + { + "employer": { + "name": "Microsoft Corporation" + }, + "position": { + "name": "Software Development Engineer" + } + } + ], + "emails": { + "preferred": "Roberto@contoso.com", + "account": "Roberto@contoso.com", + "personal": "Roberto@fabrikam.com", + "business": "Robert@adatum.com", + "other": "Roberto@adventure-works.com" + }, + "addresses": { + "personal": { + "street": "123 Main St.", + "street_2": "Apt. A", + "city": "Redmond", + "state": "WA", + "postal_code": "12990", + "region": "United States" + }, + "business": { + "street": "456 Anywhere St.", + "street_2": "Suite 1", + "city": "Redmond", + "state": "WA", + "postal_code": "12399", + "region": "United States" + } + }, + "phones": { + "personal": "(555) 555-1212", + "business": "(555) 111-1212", + "mobile": null + }, + "locale": "en_US", + "updated_time": "2011-04-21T23:55:34+0000" +}; + +var videoCollection: Microsoft.Live.IObjectCollection = { + "data": [ + { + "id": "file.de57f4126ed7e411.DE57F4126ED7E411!135", + "from": { + "name": "Nuno Bento", + "id": "de57f4126ed7e411" + }, + "name": "Wildlife.wmv", + "description": null, + "parent_id": "folder.de57f4126ed7e411.DE57F4126ED7E411!126", + "size": 26246026, + "comments_count": 0, + "comments_enabled": true, + "tags_count": 0, + "tags_enabled": true, + "is_embeddable": true, + "picture": "http://storage.live.com/s1pKk5vzd-gdPaJ5Q1MKN34itsyRlUkAYzD_zsr0Dg-5r4bH8Qo8XRgsunA0M-V4G-XPpu1spowx4xwfjCuDcWQVa7aWld2WCdfeWjBK_coPqaQqzoE26BJP3OZAITB5i_DRPK8jK3ZLilSbNJd-onrOA/Wildlife.wmv:Thumbnail", + "source": "http://storage.live.com/s1pKk5vzd-gdPaJ5Q1MKN34itsyRlUkAYzD_zsr0Dg-5r4bH8Qo8XRgsunA0M-V4G-XPpu1spowx4xwfjCuDcWQVa7aWld2WCdfeWjBK_coPqaQqzoE26BJP3OZAITB5i_DRPK8jK3ZLilSbNJd-onrOA/Wildlife.wmv:VideoMain", + "upload_location": "https://apis.live.net/v5.0/file.de57f4126ed7e411.DE57F4126ED7E411!135/content/", + "link": "https://skydrive.live.com/redir.aspx?cid\u003dde57f4126ed7e411\u0026page\u003dview\u0026resid\u003dDE57F4126ED7E411!135\u0026parid\u003dDE57F4126ED7E411!126", + "height": 720, + "width": 1280, + "duration": 30093, + "bitrate": 5942130, + "type": "video", + "shared_with": { + "access": "Everyone (public)" + }, + "created_time": "2011-08-23T23:41:18+0000", + "updated_time": "2011-08-23T23:41:32+0000" + } + ] +}; +//#endregion From: http://msdn.microsoft.com/en-us/library/live/hh243648.aspx + +//#region From http://isdk.dev.live.com/dev/isdk/Default.aspx +/** + * The following code snippets were lifted from the Interactive Live SDK + * sandbox. We only include snippets that exercise portions of the API not + * already exercised above. + */ + +function log(message) { + var child = document.createTextNode(message); + var parent = document.getElementById('JsOutputDiv') || document.body; + parent.appendChild(child); + parent.appendChild(document.createElement("br")); +} + +function openFromSkyDrive() { + WL.fileDialog({ + mode: 'open', + select: 'single' + }).then( + function (response) { + log("The following file is being downloaded:"); + log(""); + + var files = response.data.files; + for (var i = 0; i < files.length; i++) { + var file = files[i]; + log(file.name); + WL.download({ "path": file.id + "/content" }); + } + }, + function (errorResponse) { + log("WL.fileDialog errorResponse = " + JSON.stringify(errorResponse)); + } + ); +} + +function saveToSkyDrive() { + WL.fileDialog({ mode: 'save' }).then( + function (response) { + var folder = response.data.folders[0]; + + WL.upload({ + path: folder.id, + element: 'save-to-skydrive-file-input', + overwrite: 'rename' + }).then( + function (response) { + log("You saved to " + response.source + ". " + + "Below is the result of the upload."); + log(""); + log(JSON.stringify(response)); + }, + function (errorResponse) { + log("WL.upload errorResponse = " + JSON.stringify(errorResponse)); + }, + function (progress) { + // progress events for the upload are raised here + } + ); + }, function (errorResponse) { + log("WL.fileDialog errorResponse = " + JSON.stringify(errorResponse)); + } + ); +} + +function getFiles() { + var files_path = "/me/skydrive/files"; + WL.api>({ path: files_path, method: "GET" }).then( + onGetFilesComplete, + function (response) { + log("Cannot get files and folders: " + + JSON.stringify(response.error).replace(/,/g, ",\n")); + } + ); +} + +// should have an interface that captures the fact that it only has type. +function onGetFilesComplete(response: Microsoft.Live.IObjectCollection) { + var items = response.data; + var foundFolder = 0; + for (var i = 0; i < items.length; i++) { + if (items[i].type === "folder") { + log("Found a folder with the following information: " + + JSON.stringify(items[i]).replace(/,/g, ",\n")); + foundFolder = 1; + break; + } + } + + if (foundFolder == 0) { + log("Unable to find any folders"); + } +} + +function registerUser() { + WL.api({ path: "/me", method: "GET" }).then( + function (response) { + fillRegistrationForm(response); + }, + function (response) { + log("API call failed: " + JSON.stringify(response.error).replace(/,/g, "\n")); + } + ); +} + +function fillRegistrationForm(user: Microsoft.Live.IUser) { + // NOTE: Assign these values to your form elements to streamline registration. + log("First name: " + user.first_name); + log("Last name: " + user.last_name); + log("Preferred email: " + user.emails.preferred); + log("Gender: " + user.gender); + log("Birthday: " + user.birth_month + "/" + user.birth_day + "/" + user.birth_year); +} + +function showUserContactInfo() { + WL.api({ path: "/me", method: "GET" }).then( + function (response) { + log("Addresses: " + JSON.stringify(response.addresses).replace(/,/g, "\n")); + log("Phone Numbers: " + JSON.stringify(response.phones).replace(/,/g, "\n")); + log("Email Addresses: " + JSON.stringify(response.emails).replace(/,/g, "\n")); + }, + function (response) { + log("API call failed: " + JSON.stringify(response.error).replace(/,/g, "\n")); + } + ); +} + +function enablePurchase(response) { + var date = new Date(); + var year = date.getFullYear(); + + WL.api({ path: "/me", method: "GET" }).then( + function (response) { + var user = response; + if (year - user.birth_year >= 18) { + log("Purchase enabled."); + } else { + log("Purchase disabled. You are only " + user.birth_year + " year(s) old."); + } + }, + function (response) { + log("API call failed: " + JSON.stringify(response.error).replace(/,/g, "\n")); + } + ); +} + +function createContact() { + var contact: Microsoft.Live.INewContact = { + first_name: "William", + last_name: "Flash" + }; + WL.api({ + path: "/me/contacts", + method: "POST", + body: contact + }).then( + function (response) { + log(JSON.stringify(response).replace(/,/g, ",\n")); + }, + function (response) { + log("Cannot create contact: " + + JSON.stringify(response.error).replace(/,/g, ",\n")); + } + ); +} + +function createEvent() { + var startTime = new Date(); + var endTime = new Date(startTime.getTime() + (60 * 60 * 1000)); + + log("Start time: " + startTime); + log("End time: " + endTime); + var newEvent: Microsoft.Live.INewEvent = { + name: "Family Dinner", + description: "Dinner with Cynthia's family", + start_time: startTime, + end_time: endTime, + location: "Coho Vineyard and Winery, 123 Main St., Redmond WA 98052", + is_all_day_event: false, + availability: "busy", + visibility: "public" + }; + + WL.api({ + path: "/me/events", + method: "POST", + body: newEvent + }).then( + function (response) { + log("Successfully created event. Response: " + + JSON.stringify(response).replace(/,/g, "\n")); + }, + function (response) { + log("Could not create event: " + + JSON.stringify(response.error).replace(/,/g, "\n")); + } + ); +} +//#endregion From http://isdk.dev.live.com/dev/isdk/Default.aspx diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index 19c869c136..597d9cbe2c 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -1,7 +1,5 @@ /// -var mocha: Mocha; - function test_describe() { describe('something', () => { }); diff --git a/mocha/mocha.d.ts b/mocha/mocha.d.ts index bf930d3b07..9b55761c6f 100644 --- a/mocha/mocha.d.ts +++ b/mocha/mocha.d.ts @@ -1,4 +1,4 @@ -// Type definitions for mocha 1.9.0 +// Type definitions for mocha 1.17.1 // Project: http://visionmedia.github.io/mocha/ // Definitions by: Kazi Manzur Rashid // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped @@ -46,12 +46,12 @@ interface MochaSetupOptions { grep?: any; } -declare module mocha { - interface Done { - (error?: Error): void; - } +interface MochaDone { + (error?: Error): void; } +declare var mocha: Mocha; + declare var describe : { (description: string, spec: () => void): void; only(description: string, spec: () => void): void; @@ -61,42 +61,42 @@ declare var describe : { declare var it: { (expectation: string, assertion?: () => void): void; - (expectation: string, assertion?: (done: mocha.Done) => void): void; + (expectation: string, assertion?: (done: MochaDone) => void): void; only(expectation: string, assertion?: () => void): void; - only(expectation: string, assertion?: (done: mocha.Done) => void): void; + only(expectation: string, assertion?: (done: MochaDone) => void): void; skip(expectation: string, assertion?: () => void): void; - skip(expectation: string, assertion?: (done: mocha.Done) => void): void; + skip(expectation: string, assertion?: (done: MochaDone) => void): void; timeout(ms: number): void; }; declare function before(action: () => void): void; -declare function before(action: (done: mocha.Done) => void): void; +declare function before(action: (done: MochaDone) => void): void; declare function setup(action: () => void): void; -declare function setup(action: (done: mocha.Done) => void): void; +declare function setup(action: (done: MochaDone) => void): void; declare function after(action: () => void): void; -declare function after(action: (done: mocha.Done) => void): void; +declare function after(action: (done: MochaDone) => void): void; declare function teardown(action: () => void): void; -declare function teardown(action: (done: mocha.Done) => void): void; +declare function teardown(action: (done: MochaDone) => void): void; declare function beforeEach(action: () => void): void; -declare function beforeEach(action: (done: mocha.Done) => void): void; +declare function beforeEach(action: (done: MochaDone) => void): void; declare function suiteSetup(action: () => void): void; -declare function suiteSetup(action: (done: mocha.Done) => void): void; +declare function suiteSetup(action: (done: MochaDone) => void): void; declare function afterEach(action: () => void): void; -declare function afterEach(action: (done: mocha.Done) => void): void; +declare function afterEach(action: (done: MochaDone) => void): void; declare function suiteTeardown(action: () => void): void; -declare function suiteTeardown(action: (done: mocha.Done) => void): void; +declare function suiteTeardown(action: (done: MochaDone) => void): void; diff --git a/moment/moment-tests.ts b/moment/moment-tests.ts index e86989eed5..de51252d98 100644 --- a/moment/moment-tests.ts +++ b/moment/moment-tests.ts @@ -21,6 +21,14 @@ var array = [2010, 1, 14, 15, 25, 50, 125]; var day11 = moment(Date.UTC.apply({}, array)); var day12 = moment.unix(1318781876); +moment({ years: 2010, months: 3, days: 5, hours: 15, minutes: 10, seconds: 3, milliseconds: 123 }); +moment("20140101", "YYYYMMDD", true); +moment("20140101", "YYYYMMDD", "en"); +moment("20140101", "YYYYMMDD", "en", true); +moment("20140101", ["YYYYMMDD"], true); +moment("20140101", ["YYYYMMDD"], "en"); +moment("20140101", ["YYYYMMDD"], "en", true); + var a = moment([2012]); var b = moment(a); a.year(2000); @@ -29,8 +37,16 @@ b.year(); // 2012 moment.utc(); moment.utc(12345); moment.utc([12, 34, 56]); +moment.utc({ years: 2010, months: 3, days: 5, hours: 15, minutes: 10, seconds: 3, milliseconds: 123 }); moment.utc("1-2-3"); moment.utc("1-2-3", "3-2-1"); +moment.utc("1-2-3", "3-2-1", true); +moment.utc("1-2-3", "3-2-1", "en"); +moment.utc("1-2-3", "3-2-1", "en", true); +moment.utc("01-01-2014", ["DD-MM-YYYY", "MM-DD-YYYY"]); +moment.utc("01-01-2014", ["DD-MM-YYYY", "MM-DD-YYYY"], true); +moment.utc("01-01-2014", ["DD-MM-YYYY", "MM-DD-YYYY"], "en"); +moment.utc("01-01-2014", ["DD-MM-YYYY", "MM-DD-YYYY"], "en", true); var a2 = moment.utc([2011, 0, 1, 8]); a.hours(); diff --git a/moment/moment.d.ts b/moment/moment.d.ts index 20e921c324..0d7affcb2d 100644 --- a/moment/moment.d.ts +++ b/moment/moment.d.ts @@ -1,11 +1,10 @@ // Type definitions for Moment.js 2.5.0 // Project: https://github.com/timrwood/moment // Definitions by: Michael Lakerveld -// 2.4.0 Aaron King -// 2.5.0 Hiroki Horiuchi +// Definitions by: Aaron King (2.4.0) +// Definitions by: Hiroki Horiuchi (2.5.0) // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped - interface MomentInput { years?: number; y?: number; @@ -257,25 +256,29 @@ interface MomentRelativeTime { interface MomentStatic { (): Moment; - (dateObject: Object, language?: string, strict?: boolean): Moment; - (date: number, language?: string, strict?: boolean): Moment; - (date: string, language?: string, strict?: boolean): Moment; - (date: string, format: string, language?: string, strict?: boolean): Moment; - (date: string, formats: string[], language?: string, strict?: boolean): Moment; - (date: Date, language?: string, strict?: boolean): Moment; - (date: number[], language?: string, strict?: boolean): Moment; - (clone: Moment): Moment; + (date: number): Moment; + (date: number[]): Moment; + (date: string, format?: string, strict?: boolean): Moment; + (date: string, format?: string, language?: string, strict?: boolean): Moment; + (date: string, formats: string[], strict?: boolean): Moment; + (date: string, formats: string[], language?: string, strict?: boolean): Moment; + (date: Date): Moment; + (date: Moment): Moment; + (date: Object): Moment; + + utc(): Moment; + utc(date: number): Moment; + utc(date: number[]): Moment; + utc(date: string, format?: string, strict?: boolean): Moment; + utc(date: string, format?: string, language?: string, strict?: boolean): Moment; + utc(date: string, formats: string[], strict?: boolean): Moment; + utc(date: string, formats: string[], language?: string, strict?: boolean): Moment; + utc(date: Date): Moment; + utc(date: Moment): Moment; + utc(date: Object): Moment; unix(timestamp: number): Moment; - utc(): Moment; // current date/time in UTC mode - utc(Number: number): Moment; // milliseconds since the Unix Epoch in UTC mode - utc(array: number[]): Moment; // parse an array of numbers matching Date.UTC() parameters - utc(String: string): Moment; // parse string into UTC mode - utc(String1: string, String2: string): Moment; // parse a string and format into UTC mode - utc(date: Date): Moment; - utc(clone: Moment): Moment; - isMoment(): boolean; isMoment(m: any): boolean; lang(language: string): any; @@ -321,3 +324,7 @@ interface MomentStatic { } declare var moment: MomentStatic; + +declare module "moment" { + export = moment; +} diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index 0275e1f878..0805e832ab 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -1,6 +1,9 @@ -// Project : https://github.com/mongodb/node-mongodb-native -// Documentation : http://mongodb.github.io/node-mongodb-native/ +// Type definitions for MongoDB +// Project: https://github.com/mongodb/node-mongodb-native +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Documentation : http://mongodb.github.io/node-mongodb-native/ /// @@ -106,7 +109,7 @@ declare module "mongodb" { // Class documentation : http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html // Last update: doc. version 1.3.13 (28.08.2013) export class ObjectID { - constructor (s: string); + constructor (s?: string); // Returns the ObjectID id as a 24 byte hex string representation public toHexString() : string; @@ -413,4 +416,4 @@ declare module "mongodb" { pkFactory?: any; readPreferences?: string; } -} \ No newline at end of file +} diff --git a/msnodesql/msnodesql.d.ts b/msnodesql/msnodesql.d.ts index 744db70f24..cadb323dbc 100644 --- a/msnodesql/msnodesql.d.ts +++ b/msnodesql/msnodesql.d.ts @@ -55,5 +55,5 @@ declare module "msnodesql" { close(immediately: boolean, callback?: ErrorCallback); } - interface StreamEvents extends EventEmitter { } + interface StreamEvents extends NodeEventEmitter { } } \ No newline at end of file diff --git a/ng-grid/ng-grid.d.ts b/ng-grid/ng-grid.d.ts index bd23c047f7..48eec367a3 100644 --- a/ng-grid/ng-grid.d.ts +++ b/ng-grid/ng-grid.d.ts @@ -1,6 +1,6 @@ // Type definitions for ng-grid // Project: http://angular-ui.github.io/ng-grid/ -// Initial definitions by: Ken Smith +// Definitions by: Ken Smith // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped // These are very definitely preliminary. Please feel free to improve. @@ -188,4 +188,4 @@ declare module ngGrid { /** currentPage: the uhm... current page. */ currentPage?: number; } -} \ No newline at end of file +} diff --git a/node-azure/azure.d.ts b/node-azure/azure.d.ts index ed1b246e7f..95ff46c25b 100644 --- a/node-azure/azure.d.ts +++ b/node-azure/azure.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Azure SDK for Node - v0.6.10 +// Type definitions for Azure SDK for Node - v0.6.10 // Project: https://github.com/WindowsAzure/azure-sdk-for-node -// Definitions by: Andrew Gaspar and Anti Veeranna +// Definitions by: Andrew Gaspar , Anti Veeranna // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/node/node-0.8.8.d.ts b/node/node-0.8.8.d.ts index f796dfb1c1..39f02a53a6 100644 --- a/node/node-0.8.8.d.ts +++ b/node/node-0.8.8.d.ts @@ -1,3 +1,7 @@ +// Type definitions for Node.js v0.8.8 +// Project: http://nodejs.org/ +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /************************************************ * * * Node.js v0.8.8 API * diff --git a/node/node-tests.ts b/node/node-tests.ts index 8d67db311e..49b43302b1 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1,4 +1,4 @@ -/// +/// import assert = require("assert"); import fs = require("fs"); diff --git a/node/node.d.ts b/node/node.d.ts index b8fff3e275..fe7fbd324d 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1,3 +1,7 @@ +// Type definitions for Node.js v0.10.1 +// Project: http://nodejs.org/ +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /************************************************ * * * Node.js v0.10.1 API * @@ -74,38 +78,44 @@ interface ErrnoException extends Error { syscall?: string; } -interface EventEmitter { - addListener(event: string, listener: Function): EventEmitter; - on(event: string, listener: Function): EventEmitter; - once(event: string, listener: Function): EventEmitter; - removeListener(event: string, listener: Function): EventEmitter; - removeAllListeners(event?: string): EventEmitter; +interface NodeEventEmitter { + addListener(event: string, listener: Function): NodeEventEmitter; + on(event: string, listener: Function): NodeEventEmitter; + once(event: string, listener: Function): NodeEventEmitter; + removeListener(event: string, listener: Function): NodeEventEmitter; + removeAllListeners(event?: string): NodeEventEmitter; setMaxListeners(n: number): void; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; } -interface WritableStream extends EventEmitter { - writable: boolean; - write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; - end(): void; - end(str: string, enconding: string): void; - end(buffer: NodeBuffer): void; - destroy(): void; - destroySoon(): void; -} - -interface ReadableStream extends EventEmitter { +interface ReadableStream extends NodeEventEmitter { readable: boolean; + read(size?: number): any; setEncoding(encoding: string): void; pause(): void; resume(): void; - destroy(): void; pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: NodeBuffer): void; + wrap(oldStream: ReadableStream): ReadableStream; } -interface NodeProcess extends EventEmitter { +interface WritableStream extends NodeEventEmitter { + writable: boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; +} + +interface ReadWriteStream extends ReadableStream, WritableStream { } + +interface NodeProcess extends NodeEventEmitter { stdout: WritableStream; stderr: WritableStream; stdin: ReadableStream; @@ -222,17 +232,6 @@ declare module "querystring" { } declare module "events" { - export interface NodeEventEmitter { - addListener(event: string, listener: Function): NodeEventEmitter; - on(event: string, listener: Function): NodeEventEmitter; - once(event: string, listener: Function): NodeEventEmitter; - removeListener(event: string, listener: Function): NodeEventEmitter; - removeAllListeners(event?: string): NodeEventEmitter; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - } - export class EventEmitter implements NodeEventEmitter { static listenerCount(emitter: EventEmitter, event: string): number; @@ -252,14 +251,14 @@ declare module "http" { import net = require("net"); import stream = require("stream"); - export interface Server extends events.NodeEventEmitter { + export interface Server extends NodeEventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; listen(path: string, callback?: Function): void; listen(handle: any, listeningListener?: Function): void; close(cb?: any): void; maxHeadersCount: number; } - export interface ServerRequest extends events.NodeEventEmitter, stream.ReadableStream { + export interface ServerRequest extends NodeEventEmitter, ReadableStream { method: string; url: string; headers: any; @@ -270,10 +269,13 @@ declare module "http" { resume(): void; connection: net.NodeSocket; } - export interface ServerResponse extends events.NodeEventEmitter, stream.WritableStream { + export interface ServerResponse extends NodeEventEmitter, WritableStream { // Extended base methods - write(str: string, encoding?: string, fd?: string): boolean; write(buffer: NodeBuffer): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; writeContinue(): void; writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; @@ -285,21 +287,36 @@ declare module "http" { removeHeader(name: string): void; write(chunk: any, encoding?: string): any; addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientRequest extends events.NodeEventEmitter, stream.WritableStream { + export interface ClientRequest extends NodeEventEmitter, WritableStream { // Extended base methods - write(str: string, encoding?: string, fd?: string): boolean; write(buffer: NodeBuffer): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; write(chunk: any, encoding?: string): void; - end(data?: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; setNoDelay(noDelay?: Function): void; setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + // Extended base methods + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; } - export interface ClientResponse extends events.NodeEventEmitter, stream.ReadableStream { + export interface ClientResponse extends NodeEventEmitter, ReadableStream { statusCode: number; httpVersion: string; headers: any; @@ -362,13 +379,13 @@ declare module "zlib" { import stream = require("stream"); export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - export interface Gzip extends stream.ReadWriteStream { } - export interface Gunzip extends stream.ReadWriteStream { } - export interface Deflate extends stream.ReadWriteStream { } - export interface Inflate extends stream.ReadWriteStream { } - export interface DeflateRaw extends stream.ReadWriteStream { } - export interface InflateRaw extends stream.ReadWriteStream { } - export interface Unzip extends stream.ReadWriteStream { } + export interface Gzip extends ReadWriteStream { } + export interface Gunzip extends ReadWriteStream { } + export interface Deflate extends ReadWriteStream { } + export interface Inflate extends ReadWriteStream { } + export interface DeflateRaw extends ReadWriteStream { } + export interface InflateRaw extends ReadWriteStream { } + export interface Unzip extends ReadWriteStream { } export function createGzip(options?: ZlibOptions): Gzip; export function createGunzip(options?: ZlibOptions): Gunzip; @@ -484,8 +501,8 @@ declare module "https" { }; export interface Server extends tls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: events.NodeEventEmitter) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: events.NodeEventEmitter) =>void ): http.ClientRequest; + export function request(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; export var globalAgent: NodeAgent; } @@ -508,8 +525,8 @@ declare module "repl" { export interface ReplOptions { prompt?: string; - input?: stream.ReadableStream; - output?: stream.WritableStream; + input?: ReadableStream; + output?: WritableStream; terminal?: boolean; eval?: Function; useColors?: boolean; @@ -517,14 +534,14 @@ declare module "repl" { ignoreUndefined?: boolean; writer?: Function; } - export function start(options: ReplOptions): events.NodeEventEmitter; + export function start(options: ReplOptions): NodeEventEmitter; } declare module "readline" { import events = require("events"); import stream = require("stream"); - export interface ReadLine extends events.NodeEventEmitter { + export interface ReadLine extends NodeEventEmitter { setPrompt(prompt: string, length: number): void; prompt(preserveCursor?: boolean): void; question(query: string, callback: Function): void; @@ -534,8 +551,8 @@ declare module "readline" { write(data: any, key?: any): void; } export interface ReadLineOptions { - input: stream.ReadableStream; - output: stream.WritableStream; + input: ReadableStream; + output: WritableStream; completer?: Function; terminal?: boolean; } @@ -559,10 +576,10 @@ declare module "child_process" { import events = require("events"); import stream = require("stream"); - export interface ChildProcess extends events.NodeEventEmitter { - stdin: stream.WritableStream; - stdout: stream.ReadableStream; - stderr: stream.ReadableStream; + export interface ChildProcess extends NodeEventEmitter { + stdin: WritableStream; + stdout: ReadableStream; + stderr: ReadableStream; pid: number; kill(signal?: string): void; send(message: any, sendHandle: any): void; @@ -652,17 +669,19 @@ declare module "dns" { declare module "net" { import stream = require("stream"); - export interface NodeSocket extends stream.ReadWriteStream { + export interface NodeSocket extends ReadWriteStream { // Extended base methods - write(str: string, encoding?: string, fd?: string): boolean; write(buffer: NodeBuffer): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; connect(port: number, host?: string, connectionListener?: Function): void; connect(path: string, connectionListener?: Function): void; bufferSize: number; setEncoding(encoding?: string): void; write(data: any, encoding?: string, callback?: Function): void; - end(data?: any, encoding?: string): void; destroy(): void; pause(): void; resume(): void; @@ -674,6 +693,13 @@ declare module "net" { remotePort: number; bytesRead: number; bytesWritten: number; + + // Extended base methods + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; } export var Socket: { @@ -707,7 +733,7 @@ declare module "dgram" { export function createSocket(type: string, callback?: Function): Socket; - interface Socket extends events.NodeEventEmitter { + interface Socket extends NodeEventEmitter { send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; bind(port: number, address?: string): void; close(): void; @@ -746,12 +772,12 @@ declare module "fs" { ctime: Date; } - interface FSWatcher extends EventEmitter { + interface FSWatcher extends NodeEventEmitter { close(): void; } - export interface ReadStream extends stream.ReadableStream { } - export interface WriteStream extends stream.WritableStream { } + export interface ReadStream extends ReadableStream { } + export interface WriteStream extends WritableStream { } export function rename(oldPath: string, newPath: string, callback?: (err?: ErrnoException) => void): void; export function renameSync(oldPath: string, newPath: string): void; @@ -940,7 +966,7 @@ declare module "tls" { connections: number; } - export interface ClearTextStream extends stream.ReadWriteStream { + export interface ClearTextStream extends ReadWriteStream { authorized: boolean; authorizationError: Error; getPeerCertificate(): any; @@ -1038,26 +1064,6 @@ declare module "crypto" { declare module "stream" { import events = require("events"); - export interface WritableStream extends events.NodeEventEmitter { - writable: boolean; - write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; - end(): void; - end(str: string, enconding: string): void; - end(buffer: NodeBuffer): void; - destroy(): void; - destroySoon(): void; - } - - export interface ReadableStream extends events.NodeEventEmitter { - readable: boolean; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - destroy(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - } - export interface ReadableOptions { highWaterMark?: number; encoding?: string; @@ -1067,16 +1073,87 @@ declare module "stream" { export class Readable extends events.EventEmitter implements ReadableStream { readable: boolean; constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; setEncoding(encoding: string): void; pause(): void; resume(): void; - destroy(): void; pipe(destination: T, options?: { end?: boolean; }): T; - _read(): void; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: NodeBuffer): void; + wrap(oldStream: ReadableStream): ReadableStream; push(chunk: any, encoding?: string): boolean; } - export interface ReadWriteStream extends ReadableStream, WritableStream { } + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + } + + export class Writable extends events.EventEmitter implements WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(data: NodeBuffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements ReadWriteStream { + writable: boolean; + constructor(opts?: DuplexOptions); + _write(data: NodeBuffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions {} + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: NodeBuffer, encoding: string, callback: Function): void; + _transform(chunk: string, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: NodeBuffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform {} } declare module "util" { @@ -1141,7 +1218,7 @@ declare module "assert" { export function ifError(value: any): void; } - + export = internal; } @@ -1164,8 +1241,8 @@ declare module "domain" { export class Domain extends events.EventEmitter { run(fn: Function): void; - add(emitter: events.NodeEventEmitter): void; - remove(emitter: events.NodeEventEmitter): void; + add(emitter: NodeEventEmitter): void; + remove(emitter: NodeEventEmitter): void; bind(cb: (err: Error, data: any) => any): any; intercept(cb: (data: any) => any): any; dispose(): void; diff --git a/nodemailer/nodemailer.d.ts b/nodemailer/nodemailer.d.ts index 38f1804e7e..7d77a58ae5 100644 --- a/nodemailer/nodemailer.d.ts +++ b/nodemailer/nodemailer.d.ts @@ -1,9 +1,10 @@ // Type definitions for Nodemailer -// Nodemailer is an easy to use module to send e-mails with Node.JS (using SMTP or sendmail or Amazon SES) and is unicode friendly . // Project: https://github.com/andris9/Nodemailer // Definitions by: Vincent Bortone // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Nodemailer is an easy to use module to send e-mails with Node.JS (using SMTP or sendmail or Amazon SES) and is unicode friendly . + declare class Transport { static transports: { SMTP: Transport; diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 43ba32473e..6be401f715 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -1,4 +1,4 @@ -// Type definitions for OpenLayers.js 2.10 +// Type definitions for OpenLayers.js 2.10 // Project: https://github.com/openlayers/openlayers // Definitions by: Ilya Bolkhovsky // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/package.json b/package.json index 61c1dc6cdd..aded689516 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,37 @@ { - "name": "DefinitelyTyped", - "version": "0.0.0", - "scripts": { - "test": "node ./_infrastructure/tests/runner.js --tsc-version 0.9.5" + "private": true, + "name": "DefinitelyTyped", + "version": "0.0.1", + "homepage": "https://github.com/borisyankov/DefinitelyTyped", + "repository": { + "type": "git", + "url": "https://github.com/borisyankov/DefinitelyTyped.git" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/borisyankov/DefinitelyTyped/blob/master/LICENSE" } + ], + "bugs": { + "url": "https://github.com/borisyankov/DefinitelyTyped/issues" + }, + "engines": { + "node": ">= 0.10.0" + }, + "scripts": { + "test": "node ./_infrastructure/tests/runner.js --tsc-version 0.9.7 --test-changes", + "all": "node ./_infrastructure/tests/runner.js --tsc-version 0.9.7", + "dry": "node ./_infrastructure/tests/runner.js --tsc-version 0.9.7 --skip-tests --test-changes", + "list": "node ./_infrastructure/tests/runner.js --tsc-version 0.9.7 --skip-tests --print-files --print-refmap", + "help": "node ./_infrastructure/tests/runner.js -h" + }, + "dependencies": { + "source-map-support": "~0.2.5", + "git-wrapper": "~0.1.1", + "glob": "~3.2.9", + "bluebird": "~1.0.7", + "lazy.js": "~0.3.2", + "optimist": "~0.6.1" + } } diff --git a/parallel/parallel.d.ts b/parallel/parallel.d.ts index 06c8979e46..049ecda7d9 100644 --- a/parallel/parallel.d.ts +++ b/parallel/parallel.d.ts @@ -1,3 +1,8 @@ +// Type definitions for parallel.js +// Project: http://adambom.github.io/parallel.js/ +// Definitions by: Josh Baldwin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /* Copyright(c) 2013 Josh Baldwin https://github.com/jbaldwin/parallel.d.ts diff --git a/pdf/pdf.d.ts b/pdf/pdf.d.ts index 6641000bc7..bd66604f40 100644 --- a/pdf/pdf.d.ts +++ b/pdf/pdf.d.ts @@ -1,3 +1,8 @@ +// Type definitions for PDF.js +// Project: https://github.com/mozilla/pdf.js +// Definitions by: Josh Baldwin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /* Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/pdf.d.ts diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index f23b473a92..01935142ee 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -257,6 +257,7 @@ interface Contacts { } interface Device { + available: boolean; name: string; cordova: string; platform: string; diff --git a/pixi/webgl.d.ts b/pixi/webgl.d.ts index 63172ad92e..ebf1204dce 100644 --- a/pixi/webgl.d.ts +++ b/pixi/webgl.d.ts @@ -1,10 +1,7 @@ -interface WebGLContextAttributes { - alpha : boolean; - depth : boolean; - stencil : boolean; - antialias : boolean; - premultipliedAlpha : boolean; -} +// Type definitions for WebGL +// Project: https://www.khronos.org/webgl/ +// Definitions by: xperiments +// Definitions: https://github.com/borisyankov/DefinitelyTyped interface WebGLObject { $__dummyprop__WebGLObject : any; @@ -38,314 +35,11 @@ interface WebGLUniformLocation { $__dummyprop__WebGLUniformLocation : any; } -interface WebGLActiveInfo { - size : number; - type : number; - name : string; -} - interface WebGLRenderingContext { - DEPTH_BUFFER_BIT : number; - STENCIL_BUFFER_BIT : number; - COLOR_BUFFER_BIT : number; - POINTS : number; - LINES : number; - LINE_LOOP : number; - LINE_STRIP : number; - TRIANGLES : number; - TRIANGLE_STRIP : number; - TRIANGLE_FAN : number; - ZERO : number; - ONE : number; - SRC_COLOR : number; - ONE_MINUS_SRC_COLOR : number; - SRC_ALPHA : number; - ONE_MINUS_SRC_ALPHA : number; - DST_ALPHA : number; - ONE_MINUS_DST_ALPHA : number; - DST_COLOR : number; - ONE_MINUS_DST_COLOR : number; - SRC_ALPHA_SATURATE : number; - FUNC_ADD : number; - BLEND_EQUATION : number; - BLEND_EQUATION_RGB : number; - BLEND_EQUATION_ALPHA : number; - FUNC_SUBTRACT : number; - FUNC_REVERSE_SUBTRACT : number; - BLEND_DST_RGB : number; - BLEND_SRC_RGB : number; - BLEND_DST_ALPHA : number; - BLEND_SRC_ALPHA : number; - CONSTANT_COLOR : number; - ONE_MINUS_CONSTANT_COLOR : number; - CONSTANT_ALPHA : number; - ONE_MINUS_CONSTANT_ALPHA : number; - BLEND_COLOR : number; - ARRAY_BUFFER : number; - ELEMENT_ARRAY_BUFFER : number; - ARRAY_BUFFER_BINDING : number; - ELEMENT_ARRAY_BUFFER_BINDING : number; - STREAM_DRAW : number; - STATIC_DRAW : number; - DYNAMIC_DRAW : number; - BUFFER_SIZE : number; - BUFFER_USAGE : number; - CURRENT_VERTEX_ATTRIB : number; - FRONT : number; - BACK : number; - FRONT_AND_BACK : number; - TEXTURE_2D : number; - CULL_FACE : number; - BLEND : number; - DITHER : number; - STENCIL_TEST : number; - DEPTH_TEST : number; - SCISSOR_TEST : number; - POLYGON_OFFSET_FILL : number; - SAMPLE_ALPHA_TO_COVERAGE : number; - SAMPLE_COVERAGE : number; - NO_ERROR : number; - INVALID_ENUM : number; - INVALID_VALUE : number; - INVALID_OPERATION : number; - OUT_OF_MEMORY : number; - CW : number; - CCW : number; - LINE_WIDTH : number; - ALIASED_POINT_SIZE_RANGE : number; - ALIASED_LINE_WIDTH_RANGE : number; - CULL_FACE_MODE : number; - FRONT_FACE : number; - DEPTH_RANGE : number; - DEPTH_WRITEMASK : number; - DEPTH_CLEAR_VALUE : number; - DEPTH_FUNC : number; - STENCIL_CLEAR_VALUE : number; - STENCIL_FUNC : number; - STENCIL_FAIL : number; - STENCIL_PASS_DEPTH_FAIL : number; - STENCIL_PASS_DEPTH_PASS : number; - STENCIL_REF : number; - STENCIL_VALUE_MASK : number; - STENCIL_WRITEMASK : number; - STENCIL_BACK_FUNC : number; - STENCIL_BACK_FAIL : number; - STENCIL_BACK_PASS_DEPTH_FAIL : number; - STENCIL_BACK_PASS_DEPTH_PASS : number; - STENCIL_BACK_REF : number; - STENCIL_BACK_VALUE_MASK : number; - STENCIL_BACK_WRITEMASK : number; - VIEWPORT : number; - SCISSOR_BOX : number; - COLOR_CLEAR_VALUE : number; - COLOR_WRITEMASK : number; - UNPACK_ALIGNMENT : number; - PACK_ALIGNMENT : number; - MAX_TEXTURE_SIZE : number; - MAX_VIEWPORT_DIMS : number; - SUBPIXEL_BITS : number; - RED_BITS : number; - GREEN_BITS : number; - BLUE_BITS : number; - ALPHA_BITS : number; - DEPTH_BITS : number; - STENCIL_BITS : number; - POLYGON_OFFSET_UNITS : number; - POLYGON_OFFSET_FACTOR : number; - TEXTURE_BINDING_2D : number; - SAMPLE_BUFFERS : number; - SAMPLES : number; - SAMPLE_COVERAGE_VALUE : number; - SAMPLE_COVERAGE_INVERT : number; NUM_COMPRESSED_TEXTURE_FORMATS : number; - COMPRESSED_TEXTURE_FORMATS : number; - DONT_CARE : number; - FASTEST : number; - NICEST : number; - GENERATE_MIPMAP_HINT : number; - BYTE : number; - UNSIGNED_BYTE : number; - SHORT : number; - UNSIGNED_SHORT : number; - INT : number; - UNSIGNED_INT : number; - FLOAT : number; - DEPTH_COMPONENT : number; - ALPHA : number; - RGB : number; - RGBA : number; - LUMINANCE : number; - LUMINANCE_ALPHA : number; - UNSIGNED_SHORT_4_4_4_4 : number; - UNSIGNED_SHORT_5_5_5_1 : number; - UNSIGNED_SHORT_5_6_5 : number; - FRAGMENT_SHADER : number; - VERTEX_SHADER : number; - MAX_VERTEX_ATTRIBS : number; - MAX_VERTEX_UNIFORM_VECTORS : number; - MAX_VARYING_VECTORS : number; - MAX_COMBINED_TEXTURE_IMAGE_UNITS : number; - MAX_VERTEX_TEXTURE_IMAGE_UNITS : number; - MAX_TEXTURE_IMAGE_UNITS : number; - MAX_FRAGMENT_UNIFORM_VECTORS : number; - SHADER_TYPE : number; - DELETE_STATUS : number; - LINK_STATUS : number; - VALIDATE_STATUS : number; - ATTACHED_SHADERS : number; - ACTIVE_UNIFORMS : number; ACTIVE_UNIFORM_MAX_LENGTH : number; - ACTIVE_ATTRIBUTES : number; - ACTIVE_ATTRIBUTE_MAX_LENGTH : number; - SHADING_LANGUAGE_VERSION : number; - CURRENT_PROGRAM : number; - NEVER : number; - LESS : number; - EQUAL : number; - LEQUAL : number; - GREATER : number; - NOTEQUAL : number; - GEQUAL : number; - ALWAYS : number; - KEEP : number; - REPLACE : number; - INCR : number; - DECR : number; - INVERT : number; - INCR_WRAP : number; - DECR_WRAP : number; - VENDOR : number; - RENDERER : number; - VERSION : number; - NEAREST : number; - LINEAR : number; - NEAREST_MIPMAP_NEAREST : number; - LINEAR_MIPMAP_NEAREST : number; - NEAREST_MIPMAP_LINEAR : number; - LINEAR_MIPMAP_LINEAR : number; - TEXTURE_MAG_FILTER : number; - TEXTURE_MIN_FILTER : number; - TEXTURE_WRAP_S : number; - TEXTURE_WRAP_T : number; - TEXTURE : number; - TEXTURE_CUBE_MAP : number; - TEXTURE_BINDING_CUBE_MAP : number; - TEXTURE_CUBE_MAP_POSITIVE_X : number; - TEXTURE_CUBE_MAP_NEGATIVE_X : number; - TEXTURE_CUBE_MAP_POSITIVE_Y : number; - TEXTURE_CUBE_MAP_NEGATIVE_Y : number; - TEXTURE_CUBE_MAP_POSITIVE_Z : number; - TEXTURE_CUBE_MAP_NEGATIVE_Z : number; - MAX_CUBE_MAP_TEXTURE_SIZE : number; - TEXTURE0 : number; - TEXTURE1 : number; - TEXTURE2 : number; - TEXTURE3 : number; - TEXTURE4 : number; - TEXTURE5 : number; - TEXTURE6 : number; - TEXTURE7 : number; - TEXTURE8 : number; - TEXTURE9 : number; - TEXTURE10 : number; - TEXTURE11 : number; - TEXTURE12 : number; - TEXTURE13 : number; - TEXTURE14 : number; - TEXTURE15 : number; - TEXTURE16 : number; - TEXTURE17 : number; - TEXTURE18 : number; - TEXTURE19 : number; - TEXTURE20 : number; - TEXTURE21 : number; - TEXTURE22 : number; - TEXTURE23 : number; - TEXTURE24 : number; - TEXTURE25 : number; - TEXTURE26 : number; - TEXTURE27 : number; - TEXTURE28 : number; - TEXTURE29 : number; - TEXTURE30 : number; - TEXTURE31 : number; - ACTIVE_TEXTURE : number; - REPEAT : number; - CLAMP_TO_EDGE : number; - MIRRORED_REPEAT : number; - FLOAT_VEC2 : number; - FLOAT_VEC3 : number; - FLOAT_VEC4 : number; - INT_VEC2 : number; - INT_VEC3 : number; - INT_VEC4 : number; - BOOL : number; - BOOL_VEC2 : number; - BOOL_VEC3 : number; - BOOL_VEC4 : number; - FLOAT_MAT2 : number; - FLOAT_MAT3 : number; - FLOAT_MAT4 : number; - SAMPLER_2D : number; - SAMPLER_CUBE : number; - VERTEX_ATTRIB_ARRAY_ENABLED : number; - VERTEX_ATTRIB_ARRAY_SIZE : number; - VERTEX_ATTRIB_ARRAY_STRIDE : number; - VERTEX_ATTRIB_ARRAY_TYPE : number; - VERTEX_ATTRIB_ARRAY_NORMALIZED : number; - VERTEX_ATTRIB_ARRAY_POINTER : number; - VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : number; - COMPILE_STATUS : number; INFO_LOG_LENGTH : number; SHADER_SOURCE_LENGTH : number; - LOW_FLOAT : number; - MEDIUM_FLOAT : number; - HIGH_FLOAT : number; - LOW_INT : number; - MEDIUM_INT : number; - HIGH_INT : number; - FRAMEBUFFER : number; - RENDERBUFFER : number; - RGBA4 : number; - RGB5_A1 : number; - RGB565 : number; - DEPTH_COMPONENT16 : number; - STENCIL_INDEX : number; - STENCIL_INDEX8 : number; - DEPTH_STENCIL : number; - RENDERBUFFER_WIDTH : number; - RENDERBUFFER_HEIGHT : number; - RENDERBUFFER_INTERNAL_FORMAT : number; - RENDERBUFFER_RED_SIZE : number; - RENDERBUFFER_GREEN_SIZE : number; - RENDERBUFFER_BLUE_SIZE : number; - RENDERBUFFER_ALPHA_SIZE : number; - RENDERBUFFER_DEPTH_SIZE : number; - RENDERBUFFER_STENCIL_SIZE : number; - FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : number; - FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : number; - FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : number; - FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : number; - COLOR_ATTACHMENT0 : number; - DEPTH_ATTACHMENT : number; - STENCIL_ATTACHMENT : number; - DEPTH_STENCIL_ATTACHMENT : number; - NONE : number; - FRAMEBUFFER_COMPLETE : number; - FRAMEBUFFER_INCOMPLETE_ATTACHMENT : number; - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : number; - FRAMEBUFFER_INCOMPLETE_DIMENSIONS : number; - FRAMEBUFFER_UNSUPPORTED : number; - FRAMEBUFFER_BINDING : number; - RENDERBUFFER_BINDING : number; - MAX_RENDERBUFFER_SIZE : number; - INVALID_FRAMEBUFFER_OPERATION : number; - UNPACK_FLIP_Y_WEBGL : number; - UNPACK_PREMULTIPLY_ALPHA_WEBGL : number; - CONTEXT_LOST_WEBGL : number; - UNPACK_COLORSPACE_CONVERSION_WEBGL : number; - BROWSER_DEFAULT_WEBGL : number; - canvas : HTMLCanvasElement; getContextAttributes() : WebGLContextAttributes; isContextLost() : boolean; getSupportedExtensions() : string[]; @@ -508,7 +202,6 @@ interface WebGLRenderingContext { } interface WebGLContextEvent extends Event { - statusMessage : string; initWebGLContextEvent(typeArg : string, canBubbleArg : boolean, cancelableArg : boolean, statusMessageArg : string) : void; } @@ -531,4 +224,4 @@ interface WindowAnimationTiming { //To make WebGL work interface HTMLCanvasElement { getContext(contextId: string, params : {}): WebGLRenderingContext; -} \ No newline at end of file +} diff --git a/preloadjs/preloadjs.d.ts b/preloadjs/preloadjs.d.ts index 418103b54b..f5904fa8c7 100644 --- a/preloadjs/preloadjs.d.ts +++ b/preloadjs/preloadjs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for PreloadJS 0.4.0 +// Type definitions for PreloadJS 0.4.1 // Project: http://www.createjs.com/#!/PreloadJS // Definitions by: Pedro Ferreira // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -22,16 +22,15 @@ declare module createjs { progress: number; // methods - buildPath(src: string, basePath?: string, data?: Object): string; + buildPath(src: string, data?: Object): string; close(): void; load(): void; - toString(): string; - } export class LoadQueue extends AbstractLoader { - constructor(useXHR?: boolean, basePath?: string); - + constructor(useXHR?: boolean, basePath?: string, crossOrigin?: string); + constructor(useXHR?: boolean, basePath?: string, crossOrigin?: boolean); + // properties static BINARY: string; static CSS: string; @@ -39,8 +38,9 @@ declare module createjs { static JAVASCRIPT: string; static JSON: string; static JSONP: string; - static LOAD_TIMEOUT: number; + static loadTimeout: number; maintainScriptOrder: boolean; + static MANIFEST: string; next: LoadQueue; static SOUND: string; stopOnError: boolean; @@ -55,8 +55,9 @@ declare module createjs { installPlugin(plugin: any): void; loadFile(file: Object, loadNow?: boolean, basePath?: string): void; loadFile(file: string, loadNow?: boolean, basePath?: string): void; - loadManifest(manifest: Object[], loadNow?: boolean, basePath?: string): void; - loadManifest(manifest: string[], loadNow?: boolean, basePath?: string): void; + loadManifest(manifest: Object, loadNow?: boolean, basePath?: string): void; + loadManifest(manifest: string, loadNow?: boolean, basePath?: string): void; + loadManifest(manifest: any[], loadNow?: boolean, basePath?: string): void; remove(idsOrUrls: string): void; remove(idsOrUrls: any[]): void; removeAll(): void; @@ -71,18 +72,21 @@ declare module createjs { static version: string; } + export class SamplePlugin { + static fileLoadHandler(event: Object): void; + static getPreloadHandlers(): Object; + static preloadHandler(src: string, type: string, id: string, data: any, basePath: string, queue: LoadQueue): any; + } + export class TagLoader extends AbstractLoader { constructor (item: Object); - // properties - _isAudio: boolean; - // methods getResult(): any; } export class XHRLoader extends AbstractLoader { - constructor (item: Object); + constructor (item: Object, crossOrigin?: string); // methods getAllResponseHeaders(): string; diff --git a/pubsubjs/pubsub.d.ts b/pubsubjs/pubsub.d.ts index 68208cdbdb..40158c79b8 100644 --- a/pubsubjs/pubsub.d.ts +++ b/pubsubjs/pubsub.d.ts @@ -1,4 +1,7 @@ // Type definitions for PubSubJS 1.3.5 +// Project: https://github.com/mroderick/PubSubJS +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped declare module PubSubJS { interface Base extends Publish, Subscribe, Unsubscribe { @@ -24,4 +27,4 @@ declare module PubSubJS { } } -declare var PubSub: PubSubJS.Base; \ No newline at end of file +declare var PubSub: PubSubJS.Base; diff --git a/q-io/Q-io-tests.ts b/q-io/Q-io-tests.ts new file mode 100644 index 0000000000..f4ac32e9e5 --- /dev/null +++ b/q-io/Q-io-tests.ts @@ -0,0 +1,200 @@ +/// +/// + +var fs:typeof QioFS = require('q-io/fs'); +var http:typeof QioHTTP = require('q-io/http'); + +var bool:boolean; +var num:number; +var x:any; +var path:string; +var buffer:NodeBuffer; +var str:string; +var strArr:string[]; +var source:string; +var target:string; +var type:string; + +var options:any; +var strArrQ:Q.Promise; +var voidQ:Q.Promise; +var anyQ:Q.Promise; +var strQ:Q.Promise; +var boolQ:Q.Promise; +var dateQ:Q.Promise; +var bufferQ:Q.Promise; + +var statsQ:Q.Promise; +var readQ:Q.Promise; +var writeQ:Q.Promise; + +var headers:QioHTTP.Headers; +var reader:Qio.Reader; +var writer:Qio.Writer; +var stream:Qio.Stream; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fs.open(path, options).then((x) => { +}); +//fs.open(path, options):Q.Promise; +//fs.open(path, options):Q.Promise; +//fs.open(path, options):Q.Promise; + +//TODO how to define the multiple return types? use any for now? +anyQ = fs.read(path, options); +//strQ = fs.read(path, options); +//fs.read(path, options):Q.Promise; + +voidQ = fs.write(path, buffer, options); +voidQ = fs.write(path, str, options); + +voidQ = fs.append(path, buffer, options); +voidQ = fs.append(path, str, options); + +voidQ = fs.copy(source, target); +voidQ = fs.copyTree(source, target); + +strArrQ = fs.list(path); +strArrQ = fs.listTree(path, (path, x) => { + return true; +}); +strArrQ = fs.listDirectoryTree(path); + +voidQ = fs.makeDirectory(path, str); +voidQ = fs.makeDirectory(path, num); +voidQ = fs.makeTree(path, str); +voidQ = fs.makeTree(path, num); + +voidQ = fs.remove(path); +voidQ = fs.removeTree(path); + +voidQ = fs.rename(source, target); +voidQ = fs.move(source, target); + +voidQ = fs.link(source, target); + +voidQ = fs.symbolicCopy(source, target, type); +voidQ = fs.symbolicLink(target, str, type); + +voidQ = fs.chown(path, num, num); +voidQ = fs.chmod(path, str); +voidQ = fs.chmod(path, num); + +statsQ = fs.stat(path) +statsQ = fs.statLink(path); +statsQ = fs.statFd(num); + +boolQ = fs.exists(path); + +boolQ = fs.isFile(path); +boolQ = fs.isDirectory(path); +boolQ = fs.isSymbolicLink(path); + +dateQ = fs.lastModified(path); +dateQ = fs.lastAccessed(path); + +strArr = fs.split(path); +str = fs.join(str, str); +str = fs.join(strArr); +str = fs.resolve(str, str); +str = fs.resolve(strArr); +str = fs.normal(str, str); +str = fs.normal(strArr); +str = fs.absolute(path); + +strQ = fs.canonical(path); +strQ = fs.readLink(path); + +bool = fs.contains(str, str); + +strQ = fs.relative(source, target); + +str = fs.relativeFromFile(source, target); +str = fs.relativeFromDirectory(source, target); + +bool = fs.isAbsolute(path); +bool = fs.isRelative(path); +bool = fs.isRoot(path); + +str = fs.root(path); +str = fs.directory(path); +str = fs.base(path, str); +str = fs.extension(path); + +//this should return a q-io/fs-mock MockFS +//fs = fs.reroot(str); +x = fs.toObject(str); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var request:QioHTTP.Request; +var headers:QioHTTP.Headers; + +str = request.url; +str = request.path; +str = request.scriptName; +str = request.pathInfo; +strArr = request.version; +str = request.method; +str = request.scheme; + +str = request.host; +num = request.port; +str = request.remoteHost; +num = request.remotePort; + +headers = request.headers; +x = request.agent; +x = request.body; +x = request.node; + +str = headers['foo']; + +var response:QioHTTP.Response; +var responseQ:Q.Promise; + +responseQ = http.request(request); +responseQ = http.request(str); + +strQ = http.read(request); +strQ = http.read(str); + +request = http.normalizeRequest(request); +request = http.normalizeRequest(str); +response = http.normalizeResponse(response); + +num = response.status; +headers = response.headers; +reader = response.body; +response.onclose = () => { + +}; +x = response.node; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +strQ = reader.read(str); +bufferQ = reader.read(); +reader.close(); +x = reader.node; +voidQ = reader.forEach((chunk:any) => { + return anyQ; +}); + +writer.write(str); +writer.write(buffer); +writer.flush(); +writer.close(); +x = writer.node; + +strQ = stream.read(str); +bufferQ = stream.read(); +stream.write(str); +stream.write(buffer); +stream.flush(); +stream.close(); +x = stream.node; +voidQ = reader.forEach((chunk:any) => { + return anyQ; +}); diff --git a/q-io/Q-io.d.ts b/q-io/Q-io.d.ts new file mode 100644 index 0000000000..cbe37214e7 --- /dev/null +++ b/q-io/Q-io.d.ts @@ -0,0 +1,257 @@ +// Type definitions for Q-io +// Project:https://github.com/kriskowal/q-io +// Definitions by:Bart van der Schoor +// Definitions:https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +//TODO add support for q-io/http-apps +//TODO add verified support for q-io/fs-mock +//TODO fix Readers/Writers properly +//TODO find solution for overloaded return types (QioFS.open/QioFS.read) +// for some ideas see https://typescript.codeplex.com/discussions/461587#post1105930 + +declare module QioFS { + + //TODO how to define the multiple return types? use any for now? + export function open(path:string, options?:any):Q.Promise; + //export function open(path:string, options?:any):Q.Promise; + //export function open(path:string, options?:any):Q.Promise; + //export function open(path:string, options?:any):Q.Promise; + + //TODO how to define the multiple return types? use any for now? + export function read(path:string, options?:any):Q.Promise; + //export function read(path:string, options?:any):Q.Promise; + //export function read(path:string, options?:any):Q.Promise; + + export function write(path:string, content:NodeBuffer, options?:any):Q.Promise; + export function write(path:string, content:string, options?:any):Q.Promise; + + export function append(path:string, content:NodeBuffer, options?:any):Q.Promise; + export function append(path:string, content:string, options?:any):Q.Promise; + + export function copy(source:string, target:string):Q.Promise; + export function copyTree(source:string, target:string):Q.Promise; + + export function list(path:string):Q.Promise; + export function listTree(path:string, guard?:(path:string, stat:any) => boolean):Q.Promise; + export function listDirectoryTree(path:string):Q.Promise; + + export function makeDirectory(path:string, mode?:string):Q.Promise; + export function makeDirectory(path:string, mode?:number):Q.Promise; + export function makeTree(path:string, mode?:string):Q.Promise; + export function makeTree(path:string, mode?:number):Q.Promise; + + export function remove(path:string):Q.Promise; + export function removeTree(path:string):Q.Promise; + + export function rename(source:string, target:string):Q.Promise; + export function move(source:string, target:string):Q.Promise; + + export function link(source:string, target:any):Q.Promise; + + export function symbolicCopy(source:string, target:string, type:string):Q.Promise; + export function symbolicLink(target:string, link:string, type:string):Q.Promise; + + export function chown(path:string, uid:number, gid:number):Q.Promise; + export function chmod(path:string, mode?:string):Q.Promise; + export function chmod(path:string, mode?:number):Q.Promise; + + export function stat(path:string):Q.Promise; + export function statLink(path:string):Q.Promise; + export function statFd(fd:number):Q.Promise; + + export function exists(path:string):Q.Promise; + + export function isFile(path:string):Q.Promise; + export function isDirectory(path:string):Q.Promise; + export function isSymbolicLink(path:string):Q.Promise; + + export function lastModified(path:string):Q.Promise; + export function lastAccessed(path:string):Q.Promise; + + export function split(path:string):string[]; + export function join(...paths:string[]):string; + export function join(paths:string[]):string; + export function resolve(...path:string[]):string; + export function resolve(paths:string[]):string; + export function normal(...path:string[]):string; + export function normal(paths:string[]):string; + export function absolute(path:string):string; + + export function canonical(path:string):Q.Promise; + export function readLink(path:string):Q.Promise; + + export function contains(parent:string, child:string):boolean; + + export function relative(source:string, target:string):Q.Promise; + + export function relativeFromFile(source:string, target:string):string; + export function relativeFromDirectory(source:string, target:string):string; + + export function isAbsolute(path:string):boolean; + export function isRelative(path:string):boolean; + export function isRoot(path:string):boolean; + + export function root(path:string):string; + export function directory(path:string):string; + export function base(path:string, extension:string):string; + export function extension(path:string):string; + + //this should return a q-io/fs-mock MockFS + export function reroot(path:string):typeof QioFS; + + export function toObject(path:string):{[path:string]:NodeBuffer}; + + //listed but not implemented by Q-io + //export function glob(pattern):Q.Promise; + //export function match(pattern, path:string):Q.Promise; + + //TODO link this to node.js FS module (no lazy clones) + interface Stats { + node:NodeStats; + size:number; + } + interface NodeStats { + isFile():boolean; + isDirectory():boolean; + isBlockDevice():boolean; + isCharacterDevice():boolean; + isSymbolicLink():boolean; + isFIFO():boolean; + isSocket():boolean; + node:NodeStats; + dev:number; + ino:number; + mode:number; + nlink:number; + uid:number; + gid:number; + rdev:number; + size:number; + blksize:number; + blocks:number; + atime:Date; + mtime:Date; + ctime:Date; + } +} + +declare module QioHTTP { + export function request(request:Request):Q.Promise; + export function request(url:string):Q.Promise; + + export function read(request:Request):Q.Promise; + export function read(url:string):Q.Promise; + + export function normalizeRequest(request:Request):Request; + export function normalizeRequest(url:string):Request; + export function normalizeResponse(response:Response):Response; + + interface Request { + url:string; + path:string; + scriptName:string; + pathInfo:string; + version:string[]; + method:string; + scheme:string; + + host:string; + port:number; + remoteHost:string; + remotePort:number; + + headers:Headers; + agent:any; + body:any; + node:any; + } + interface Response { + status:number; + headers:Headers; + body:Qio.Reader + onclose:() => void; + node:any; + } + interface Headers { + [name:string]:any; + // [name:string]:any[]; + } + interface Body extends Qio.Stream { + + } + interface Application { + (req:Request):Q.Promise; + } +} + +declare module Qio { + interface ForEachCallback { + (chunk:NodeBuffer):Q.Promise; + (chunk:string):Q.Promise; + } + interface ForEach { + forEach(callback:ForEachCallback):Q.Promise; + } + + interface Reader extends ForEach { + read(charset:string):Q.Promise; + read():Q.Promise; + close():void; + node:ReadableStream; + } + interface Writer { + write(content:string):void; + write(content:NodeBuffer):void; + flush():Q.Promise; + close():void; + destroy():void; + node:WritableStream; + } + + interface Stream { + read(charset:string):Q.Promise; + read():Q.Promise; + write(content:string):void; + write(content:NodeBuffer):void; + flush():Q.Promise; + close():void; + destroy():void; + node:any; + } + + interface BufferReader extends QioBufferReader { + + } +} +interface QioBufferReader { + new ():Qio.Reader; + read(stream:Qio.Reader, charset:string):string; + read(stream:Qio.Reader):NodeBuffer; + join(buffers:NodeBuffer[]):NodeBuffer; +} +interface QioBufferWriter { + (writer:NodeBuffer):Qio.Writer; + Writer:Qio.Writer; +} +interface QioBufferStream { + (buffer:NodeBuffer, encoding:string):Qio.Stream +} + +declare module "q-io/http" { +export = QioHTTP; +} +declare module "q-io/fs" { +export = QioFS; +} +declare module "q-io/reader" { +export = QioBufferReader; +} +declare module "q-io/writer" { +export = QioBufferWriter; +} +declare module "q-io/buffer-stream" { +export = QioBufferStream; +} diff --git a/raphael/raphael.d.ts.tscparams b/raphael/raphael.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/raphael/raphael.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/requirejs/require.d.ts b/requirejs/require.d.ts index bb58e5143f..a85699c779 100644 --- a/requirejs/require.d.ts +++ b/requirejs/require.d.ts @@ -1,3 +1,8 @@ +// Type definitions for RequireJS 2.1.8 +// Project: http://requirejs.org/ +// Definitions by: Josh Baldwin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /* require-2.1.8.d.ts may be freely distributed under the MIT license. @@ -244,6 +249,12 @@ interface Require { **/ (modules: string[], ready: Function): void; + /** + * @see http://requirejs.org/docs/api.html#errbacks + * @param ready Called when required modules are ready. + **/ + (modules: string[], ready: Function, errback: Function): void; + /** * Generate URLs from require module * @param module Module to URL diff --git a/restangular/restangular-tests.ts b/restangular/restangular-tests.ts index 1bb4b01ee7..22473e13e2 100644 --- a/restangular/restangular-tests.ts +++ b/restangular/restangular-tests.ts @@ -136,3 +136,10 @@ function test_config() { }); }); } + +function test_withHttpConfig() { + var $scope; + Restangular.one('accounts', 123).withHttpConfig({timeout: 100}).getList('buildings'); + $scope.account = Restangular.one('accounts', 123); + $scope.account.withHttpConfig({timeout: 100}).put(); +} diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index a329b20bfe..a5b7de20d9 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Restangular v1.2.2 - 2014-01-10 +// Type definitions for Restangular v1.2.2 // Project: https://github.com/mgonto/restangular // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -6,49 +6,64 @@ /// +interface RestangularRequestConfig { + params?: any; + headers?: any; + cache?: any; + withCredentials?: boolean; + data?: any; + transformRequest?: any; + transformResponse?: any; + timeout?: any; // number | promise +} + interface Restangular extends RestangularCustom { one(route: string, id?: number): RestangularElement; one(route: string, id?: string): RestangularElement; + oneUrl(route: string, url: string): RestangularElement; all(route: string): RestangularCollection; + allUrl(route: string, url: string): RestangularCollection; copy(fromElement: any): RestangularElement; - withConfig(configurer: (RestangularProvider) => any): Restangular; - restangularizeElement(parent: any, element: any, route: string, collection?, reqParams?): RestangularElement; + withConfig(configurer: (RestangularProvider: RestangularProvider) => any): Restangular; + restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): RestangularElement; restangularizeCollection(parent: any, element: any, route: string): RestangularCollection; stripRestangular(element: any): any; } interface RestangularElement extends Restangular { - get (queryParams?: any, headers?: any): ng.IPromise; + get(queryParams?: any, headers?: any): ng.IPromise; getList(subElement: any, queryParams?: any, headers?: any): ng.IPromise; put(queryParams?: any, headers?: any): ng.IPromise; - post(subElement, elementToPost, queryParams?, headers?): ng.IPromise; - remove(queryParams?, headers?): ng.IPromise; - head(queryParams?, headers?): ng.IPromise; - trace(queryParams?, headers?): ng.IPromise; - options(queryParams?, headers?): ng.IPromise; - patch(queryParams?, headers?): ng.IPromise; + post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): ng.IPromise; + remove(queryParams?: any, headers?: any): ng.IPromise; + head(queryParams?: any, headers?: any): ng.IPromise; + trace(queryParams?: any, headers?: any): ng.IPromise; + options(queryParams?: any, headers?: any): ng.IPromise; + patch(queryParams?: any, headers?: any): ng.IPromise; + withHttpConfig(httpConfig: RestangularRequestConfig): RestangularElement; getRestangularUrl(): string; } interface RestangularCollection extends Restangular { - getList(queryParams?, headers?): ng.IPromise; - post(elementToPost, queryParams?, headers?): ng.IPromise; - head(queryParams?, headers?): ng.IPromise; - trace(queryParams?, headers?): ng.IPromise; - options(queryParams?, headers?): ng.IPromise; - patch(queryParams?, headers?): ng.IPromise; - putElement(idx, params, headers): ng.IPromise; + getList(queryParams?: any, headers?: any): ng.IPromise; + post(elementToPost: any, queryParams?: any, headers?: any): ng.IPromise; + head(queryParams?: any, headers?: any): ng.IPromise; + trace(queryParams?: any, headers?: any): ng.IPromise; + options(queryParams?: any, headers?: any): ng.IPromise; + patch(queryParams?: any, headers?: any): ng.IPromise; + putElement(idx: any, params: any, headers: any): ng.IPromise; + withHttpConfig(httpConfig: RestangularRequestConfig): RestangularCollection; getRestangularUrl(): string; } interface RestangularCustom { - customGET(path, params?, headers?): ng.IPromise; - customGETLIST(path, params?, headers?): ng.IPromise; - customDELETE(path, params?, headers?): ng.IPromise; - customPOST(path, params?, headers?, elem?): ng.IPromise; - customPUT(path, params?, headers?, elem?): ng.IPromise; - customOperation(operation, path, params?, headers?, elem?): ng.IPromise; - addRestangularMethod(name, operation, path?, params?, headers?, elem?): ng.IPromise; + customGET(path: string, params?: any, headers?: any): ng.IPromise; + customGETLIST(path: string, params?: any, headers?: any): ng.IPromise; + customDELETE(path: string, params?: any, headers?: any): ng.IPromise; + customPOST(path: string, params?: any, headers?: any, elem?: any): ng.IPromise; + customPUT(path: string, params?: any, headers?: any, elem?: any): ng.IPromise; + customOperation(operation: string, path: string, params?: any, headers?: any, elem?: any): ng.IPromise; + addRestangularMethod(name: string, operation: string, path?: string, params?: any, headers?: any, elem?: any): ng.IPromise; } interface RestangularProvider { @@ -61,8 +76,8 @@ interface RestangularProvider { setOnElemRestangularized(callback: (elem: any, isCollection: boolean, what: string, restangular: Restangular) => any): void; setResponseInterceptor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: RestangularResponse, deferred: ng.IDeferred) => any): void; setResponseExtractor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: RestangularResponse, deferred: ng.IDeferred) => any): void; - setRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string) => any); - setFullRequestInterceptor(fullRequestInterceptor: (element: any, operation: string, what: string, url: string, headers: any, params: any) => {element: any; headers: any; params: any}); + setRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string) => any): void; + setFullRequestInterceptor(fullRequestInterceptor: (element: any, operation: string, what: string, url: string, headers: any, params: any) => {element: any; headers: any; params: any}): void; setErrorInterceptor(errorInterceptor: (response: RestangularResponse) => any): void; setRestangularFields(fields: {[fieldName: string]: string}): void; setMethodOverriders(overriders: string[]): void; diff --git a/rethinkdb/rethinkdb.d.ts b/rethinkdb/rethinkdb.d.ts index da63550941..2c65a7cf4d 100644 --- a/rethinkdb/rethinkdb.d.ts +++ b/rethinkdb/rethinkdb.d.ts @@ -26,6 +26,12 @@ declare module "rethinkdb" { export function row(name:string):Expression; export function expr(stuff:any):Expression; + export function now():Time; + + // Control Structures + export function branch(test:Expression, trueBranch:Expression, falseBranch:Expression):Expression; + + export class Cursor { hasNext():boolean; each(cb:(err:Error, row:any)=>void, done?:()=>void); @@ -83,9 +89,9 @@ declare module "rethinkdb" { insert(obj:any[], options?:InsertOptions):Operation; insert(obj:any, options?:InsertOptions):Operation; - get(key:string):Expression; // primary key - getAll(key:string, index?:Index):Selection; // without index defaults to primary key - getAll(...keys:string[]):Selection; + get(key:string):Sequence; // primary key + getAll(key:string, index?:Index):Sequence; // without index defaults to primary key + getAll(...keys:string[]):Sequence; } interface Sequence extends Operation, Writeable { @@ -98,8 +104,8 @@ declare module "rethinkdb" { // Join // these return left, right - innerJoin(sequence:Sequence, join:ExpressionFunction):Sequence; - outerJoin(sequence:Sequence, join:ExpressionFunction):Sequence; + innerJoin(sequence:Sequence, join:JoinFunction):Sequence; + outerJoin(sequence:Sequence, join:JoinFunction):Sequence; eqJoin(leftAttribute:string, rightSequence:Sequence, index?:Index):Sequence; eqJoin(leftAttribute:ExpressionFunction, rightSequence:Sequence, index?:Index):Sequence; zip():Sequence; @@ -120,10 +126,10 @@ declare module "rethinkdb" { sample(n:number):Sequence; // Aggregate - reduce(r:Reduce, base?:any):Expression; + reduce(r:ReduceFunction, base?:any):Expression; count():Expression; distinct():Sequence; - groupedMapReduce(group:ExpressionFunction, map:ExpressionFunction, reduce:Reduce, base?:any):Expression; + groupedMapReduce(group:ExpressionFunction, map:ExpressionFunction, reduce:ReduceFunction, base?:any):Sequence; groupBy(...aggregators:Aggregator[]):Expression; // TODO: reduction object contains(prop:string):Expression; @@ -133,11 +139,15 @@ declare module "rethinkdb" { } interface ExpressionFunction { - (...docs:Expression[]):Expression; + (doc:Expression):Expression; } - interface Reduce { - (acc:any, val:any):any; + interface JoinFunction { + (left:Expression, right:Expression):Expression; + } + + interface ReduceFunction { + (acc:Expression, val:Expression):Expression; } interface InsertOptions { @@ -178,8 +188,8 @@ declare module "rethinkdb" { interface Index { index: string; - left_bound: string; // 'closed' - right_bound: string; // 'open' + left_bound?: string; // 'closed' + right_bound?: string; // 'open' } interface Expression extends Writeable, Operation { @@ -204,6 +214,10 @@ declare module "rethinkdb" { mul(n:number):Expression; div(n:number):Expression; mod(n:number):Expression; + + hasFields(...fields:string[]):Expression; + + default(value:T):Expression; } interface Operation { @@ -213,6 +227,8 @@ declare module "rethinkdb" { interface Aggregator {} interface Sort {} + interface Time {} + // http://www.rethinkdb.com/api/#js // TODO control structures diff --git a/rx.js/rx.aggregates.d.ts b/rx.js/rx.aggregates.d.ts index 24ed13f1d4..4ba03b4c60 100644 --- a/rx.js/rx.aggregates.d.ts +++ b/rx.js/rx.aggregates.d.ts @@ -1,11 +1,11 @@ -/// - // Type definitions for RxJS-Aggregates package // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy -// Revision by: Igor Oleinikov +// Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module Rx { export interface Observable { aggregate(accumulator: (acc: T, value: T) => T): Observable; diff --git a/rx.js/rx.async-tests.ts b/rx.js/rx.async-tests.ts index 636aa30de9..b71f8bd775 100644 --- a/rx.js/rx.async-tests.ts +++ b/rx.js/rx.async-tests.ts @@ -18,9 +18,9 @@ module Rx.Tests.Async { function toAsync() { obsNum = Rx.Observable.toAsync(()=> 1, sch)(); obsNum = Rx.Observable.toAsync((a1: number)=> a1)(1); - obsStr = Rx.Observable.toAsync((a1: string, a2: number)=> a1 + a2.toFixed(0))("", 1); - obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date)=> a1 + a2.toFixed(0) + a3.toDateString())("", 1, new Date()); - obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date, a4: boolean)=> a1 + a2.toFixed(0) + a3.toDateString() + (a4 ? 1 : 0))("", 1, new Date(), false); + obsStr = Rx.Observable.toAsync((a1: string, a2: number)=> a1 + a2.toFixed(0))("", 1); + obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date)=> a1 + a2.toFixed(0) + a3.toDateString())("", 1, new Date()); + obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date, a4: boolean)=> a1 + a2.toFixed(0) + a3.toDateString() + (a4 ? 1 : 0))("", 1, new Date(), false); } function fromCallback() { diff --git a/rx.js/rx.async.d.ts b/rx.js/rx.async.d.ts index cdd93b9a86..f6e15c50a3 100644 --- a/rx.js/rx.async.d.ts +++ b/rx.js/rx.async.d.ts @@ -1,11 +1,11 @@ -/// - // Type definitions for RxJS-Async package 2.2.11 // Project: http://rx.codeplex.com/ // Definitions by: zoetrope -// Revision by: Igor Oleinikov +// Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module Rx { interface ObservableStatic { start(func: () => T, scheduler?: IScheduler, context?: any): Observable; diff --git a/rx.js/rx.binding.d.ts b/rx.js/rx.binding.d.ts index 22624cc236..6d0f1db3c1 100644 --- a/rx.js/rx.binding.d.ts +++ b/rx.js/rx.binding.d.ts @@ -1,11 +1,11 @@ -/// - // Type definitions for RxJS-Binding package // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy -// Revision by: Igor Oleinikov +// Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module Rx { export interface BehaviorSubject extends Subject { } diff --git a/rx.js/rx.coincidence.d.ts b/rx.js/rx.coincidence.d.ts index 2afa5cfe90..02883ff542 100644 --- a/rx.js/rx.coincidence.d.ts +++ b/rx.js/rx.coincidence.d.ts @@ -1,11 +1,11 @@ -/// - // Type definitions for RxJS-Coincidence package // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy -// Revision by: Igor Oleinikov +// Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module Rx { interface Observable { diff --git a/rx.js/rx.d.ts b/rx.js/rx.d.ts index 949baa68ee..a0f27b1bb5 100644 --- a/rx.js/rx.d.ts +++ b/rx.js/rx.d.ts @@ -1,7 +1,7 @@ // Type definitions for RxJS v2.2.13 // Project: http://rx.codeplex.com/ // Definitions by: gsino -// Revision by: Igor Oleinikov +// Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module Rx { diff --git a/rx.js/rx.joinpatterns.d.ts b/rx.js/rx.joinpatterns.d.ts index d23264f8e4..a1ec9f952d 100644 --- a/rx.js/rx.joinpatterns.d.ts +++ b/rx.js/rx.joinpatterns.d.ts @@ -1,10 +1,10 @@ -/// - // Type definitions for RxJS-Join package // Project: http://rx.codeplex.com/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module Rx { interface Pattern1 { diff --git a/rx.js/rx.jquery.d.ts b/rx.js/rx.jquery.d.ts index fd9311ee49..f2dcb284a7 100644 --- a/rx.js/rx.jquery.d.ts +++ b/rx.js/rx.jquery.d.ts @@ -1,17 +1,23 @@ -// Type definitions for bridging RxJS with jQuery. +// Type definitions for bridging RxJS with jQuery. // Project: https://github.com/Reactive-Extensions/RxJS-jQuery/ -// Revision by: Igor Oleinikov +// Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// /// +interface RxJQueryAjaxResult { + data: T; + textStatus: string; + jqXHR: JQueryXHR; +} + interface JQueryStatic { - ajaxAsObservable(settings: JQueryAjaxSettings): Rx.Observable; - getAsObservable(url: string, data: any, dataType: string): Rx.Observable; - getJSONAsObservable(url: string, data: any): Rx.Observable; - getScriptAsObservable(url: string, data: any): Rx.Observable; - postAsObservable(url: string, data: any, dataType: string): Rx.Observable; + ajaxAsObservable(settings: JQueryAjaxSettings): Rx.Observable>; + getAsObservable(url: string, data: any, dataType: string): Rx.Observable>; + getJSONAsObservable(url: string, data: any): Rx.Observable>; + getScriptAsObservable(url: string, data: any): Rx.Observable>; + postAsObservable(url: string, data: any, dataType: string): Rx.Observable>; } interface JQuery { diff --git a/rx.js/rx.testing.d.ts b/rx.js/rx.testing.d.ts index 8a2dc35e5f..69fcf2c131 100644 --- a/rx.js/rx.testing.d.ts +++ b/rx.js/rx.testing.d.ts @@ -1,11 +1,11 @@ -/// -/// - // Type definitions for RxJS-Testing // Project: https://github.com/Reactive-Extensions/RxJS/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// +/// + declare module Rx { export class TestScheduler extends VirtualTimeScheduler { constructor(); diff --git a/rx.js/rx.time.d.ts b/rx.js/rx.time.d.ts index 2d5f1d14f8..013665517d 100644 --- a/rx.js/rx.time.d.ts +++ b/rx.js/rx.time.d.ts @@ -1,11 +1,11 @@ -/// - // Type definitions for RxJS "Aggregates" // Project: http://rx.codeplex.com/ // Definitions by: Carl de Billy -// Revision by: Igor Oleinikov +// Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module Rx { export interface TimeInterval { @@ -25,12 +25,12 @@ declare module Rx { delay(dueTime: number, scheduler?: IScheduler): Observable; throttle(dueTime: number, scheduler?: IScheduler): Observable; - windowWithTime(timeSpan: number, timeShift: number, scheduler?: IScheduler): Observable; - windowWithTime(timeSpan: number, scheduler?: IScheduler): Observable; - windowWithTimeOrCount(timeSpan: number, count: number, scheduler?: IScheduler): Observable; - bufferWithTime(timeSpan: number, timeShift: number, scheduler?: IScheduler): Observable; - bufferWithTime(timeSpan: number, scheduler?: IScheduler): Observable; - bufferWithTimeOrCount(timeSpan: number, count: number, scheduler?: IScheduler): Observable; + windowWithTime(timeSpan: number, timeShift: number, scheduler?: IScheduler): Observable>; + windowWithTime(timeSpan: number, scheduler?: IScheduler): Observable>; + windowWithTimeOrCount(timeSpan: number, count: number, scheduler?: IScheduler): Observable>; + bufferWithTime(timeSpan: number, timeShift: number, scheduler?: IScheduler): Observable; + bufferWithTime(timeSpan: number, scheduler?: IScheduler): Observable; + bufferWithTimeOrCount(timeSpan: number, count: number, scheduler?: IScheduler): Observable; timeInterval(scheduler?: IScheduler): Observable>; timestamp(scheduler?: IScheduler): Observable>; sample(interval: number, scheduler?: IScheduler): Observable; @@ -80,4 +80,4 @@ declare module Rx { timeSelector: (state: TState) => number, scheduler?: IScheduler): Observable; } -} \ No newline at end of file +} diff --git a/rx.js/rx.virtualtime.d.ts b/rx.js/rx.virtualtime.d.ts index 293343fda2..376057964e 100644 --- a/rx.js/rx.virtualtime.d.ts +++ b/rx.js/rx.virtualtime.d.ts @@ -1,11 +1,11 @@ -/// - // Type definitions for RxJS-VirtualTime package 2.2 // Project: http://rx.codeplex.com/ // Definitions by: gsino -// Revision by: Igor Oleinikov +// Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module Rx { // Virtual IScheduler export /*abstract*/ class VirtualTimeScheduler extends Scheduler { diff --git a/sammyjs/sammyjs-tests.ts b/sammyjs/sammyjs-tests.ts index da0da616e8..1aa151d6ea 100644 --- a/sammyjs/sammyjs-tests.ts +++ b/sammyjs/sammyjs-tests.ts @@ -422,7 +422,7 @@ function test_misc() { }); store = new Sammy.Store({ name: 'kvo' }); - $('body').bind('set-kvo-foo', function (e, data) { + $('body').bind('set-kvo-foo', function (e, data?) { Sammy.log(data.key + ' changed to ' + data.value); }); store.set('foo', 'bar'); diff --git a/sammyjs/sammyjs.d.ts b/sammyjs/sammyjs.d.ts index b4fd408807..136362fbf9 100644 --- a/sammyjs/sammyjs.d.ts +++ b/sammyjs/sammyjs.d.ts @@ -1,7 +1,7 @@ // Type definitions for Sammy.js // Project: http://sammyjs.org/ // Definitions by: Boris Yankov -// - Updated for TypeScript 0.9.x by: Oisin Grehan +// Definitions by: Oisin Grehan // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -279,4 +279,4 @@ declare module Sammy { interface JQueryStatic { sammy: Sammy.SammyFunc; log: Function; -} \ No newline at end of file +} diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts new file mode 100644 index 0000000000..52b317d961 --- /dev/null +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -0,0 +1,917 @@ +/// + +function TestAbstractBuilder() { + var builder: webdriver.AbstractBuilder = new webdriver.AbstractBuilder(); + var driver: webdriver.WebDriver = builder.build(); + var capabilities: webdriver.Capabilities = builder.getCapabilities(); + url = builder.getServerUrl(); + var otherBuilder: webdriver.AbstractBuilder = builder.usingServer(url); + otherBuilder = builder.withCapabilities(webdriver.Capabilities.android()); + var objCapabilities: { [index: string]: string; } = {}; + objCapabilities[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.PHANTOM_JS; + otherBuilder = builder.withCapabilities(objCapabilities); + var url: string = webdriver.AbstractBuilder.DEFAULT_SERVER_URL; + var env: string = webdriver.AbstractBuilder.SERVER_URL_ENV; +} + +function TestBuilder() { + var builder: webdriver.Builder = new webdriver.Builder(); + var abstractBuilder: webdriver.AbstractBuilder = builder; + + var driver: webdriver.WebDriver = builder.build(); + var session: string = builder.getSession(); + abstractBuilder = builder.usingSession("ID"); + + var env: string = webdriver.Builder.SESSION_ID_ENV; +} + +function TestActionSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'id'); + + // Click + sequence = sequence.click(); + sequence = sequence.click(webdriver.Button.LEFT); + sequence = sequence.click(element); + sequence = sequence.click(element, webdriver.Button.LEFT); + + // DoubleClick + sequence = sequence.doubleClick(); + sequence = sequence.doubleClick(webdriver.Button.LEFT); + sequence = sequence.doubleClick(element); + sequence = sequence.doubleClick(element, webdriver.Button.LEFT); + + // DragAndDrop + sequence = sequence.dragAndDrop(element, element); + sequence = sequence.dragAndDrop(element, {x: 1, y: 2}); + + // KeyDown + sequence = sequence.keyDown(webdriver.Key.ADD); + + // KeyUp + sequence = sequence.keyUp(webdriver.Key.ADD); + + // MouseDown + sequence = sequence.mouseDown(); + sequence = sequence.mouseDown(webdriver.Button.LEFT); + sequence = sequence.mouseDown(element); + sequence = sequence.mouseDown(element, webdriver.Button.LEFT); + + // MouseMove + sequence = sequence.mouseMove(element); + sequence = sequence.mouseMove({x: 1, y: 1}); + sequence = sequence.mouseMove(element, {x: 1, y: 2}); + + // MouseUp + sequence = sequence.mouseUp(); + sequence = sequence.mouseUp(webdriver.Button.LEFT); + sequence = sequence.mouseUp(element); + sequence = sequence.mouseUp(element, webdriver.Button.LEFT); + + // SendKeys + sequence = sequence.sendKeys("A", "B", "C"); + sequence = sequence.sendKeys(["A", "B", "C"]); + + var promise: webdriver.promise.Promise = sequence.perform(); +} + +function TestAlert() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + + var alert: webdriver.Alert = new webdriver.Alert(driver, 'ABC'); + alert = new webdriver.Alert(driver, promise); + var deferred: webdriver.promise.Deferred = alert; + + promise = alert.accept(); + promise = alert.dismiss(); + promise = alert.getText(); + promise = alert.sendKeys("ABC"); +} + +function TestBrowser() { + var browser: string; + + browser = webdriver.Browser.ANDROID; + browser = webdriver.Browser.CHROME; + browser = webdriver.Browser.FIREFOX; + browser = webdriver.Browser.HTMLUNIT; + browser = webdriver.Browser.INTERNET_EXPLORER; + browser = webdriver.Browser.IPAD; + browser = webdriver.Browser.IPHONE; + browser = webdriver.Browser.OPERA; + browser = webdriver.Browser.PHANTOM_JS; + browser = webdriver.Browser.SAFARI; +} + +function TestButton() { + var button: number; + + button = webdriver.Button.LEFT; + button = webdriver.Button.MIDDLE; + button = webdriver.Button.RIGHT; +} + +function TestCapabilities() { + var capabilities: webdriver.Capabilities = new webdriver.Capabilities(); + capabilities = new webdriver.Capabilities(webdriver.Capabilities.chrome()); + var objCapabilities: any = {}; + objCapabilities[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.PHANTOM_JS; + capabilities = new webdriver.Capabilities(objCapabilities); + + var anything: any = capabilities.get(webdriver.Capability.SECURE_SSL); + var check: boolean = capabilities.has(webdriver.Capability.SECURE_SSL); + capabilities = capabilities.merge(capabilities); + capabilities = capabilities.merge(objCapabilities); + capabilities = capabilities.set(webdriver.Capability.VERSION, { abc: 'def' }); + capabilities = capabilities.set(webdriver.Capability.VERSION, null); + + anything = capabilities.toJSON(); + + capabilities = webdriver.Capabilities.android(); + capabilities = webdriver.Capabilities.chrome(); + capabilities = webdriver.Capabilities.firefox(); + capabilities = webdriver.Capabilities.htmlunit(); + capabilities = webdriver.Capabilities.htmlunitwithjs(); + capabilities = webdriver.Capabilities.ie(); + capabilities = webdriver.Capabilities.ipad(); + capabilities = webdriver.Capabilities.iphone(); + capabilities = webdriver.Capabilities.opera(); + capabilities = webdriver.Capabilities.phantomjs(); + capabilities = webdriver.Capabilities.safari(); +} + +function TestCapability() { + var capability: string; + + capability = webdriver.Capability.ACCEPT_SSL_CERTS; + capability = webdriver.Capability.BROWSER_NAME; + capability = webdriver.Capability.HANDLES_ALERTS; + capability = webdriver.Capability.LOGGING_PREFS; + capability = webdriver.Capability.PLATFORM; + capability = webdriver.Capability.PROXY; + capability = webdriver.Capability.ROTATABLE; + capability = webdriver.Capability.SECURE_SSL; + capability = webdriver.Capability.SUPPORTS_APPLICATION_CACHE; + capability = webdriver.Capability.SUPPORTS_BROWSER_CONNECTION; + capability = webdriver.Capability.SUPPORTS_CSS_SELECTORS; + capability = webdriver.Capability.SUPPORTS_JAVASCRIPT; + capability = webdriver.Capability.SUPPORTS_LOCATION_CONTEXT; + capability = webdriver.Capability.TAKES_SCREENSHOT; + capability = webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR; + capability = webdriver.Capability.VERSION; +} + +function TestCommand() { + var command: webdriver.Command = new webdriver.Command(webdriver.CommandName.ADD_COOKIE); + + var name: string = command.getName(); + var param: any = command.getParameter("param"); + + var params: any = command.getParameters(); + + command = command.setParameter("param", 123); + command = command.setParameters({ param: 123 }); +} + +function TestCommandExecutor() { + var c: webdriver.CommandExecutor = { execute: function(command: webdriver.Command, callback: (error: Error, obj: any) => any) {} }; +} + +function TestCommandName() { + var command: string; + + command = webdriver.CommandName.ACCEPT_ALERT; + command = webdriver.CommandName.ADD_COOKIE; + command = webdriver.CommandName.CLEAR_APP_CACHE; + command = webdriver.CommandName.CLEAR_ELEMENT; + command = webdriver.CommandName.CLEAR_LOCAL_STORAGE; + command = webdriver.CommandName.CLEAR_SESSION_STORAGE; + command = webdriver.CommandName.CLICK; + command = webdriver.CommandName.CLICK_ELEMENT; + command = webdriver.CommandName.CLOSE; + command = webdriver.CommandName.DELETE_ALL_COOKIES; + command = webdriver.CommandName.DELETE_COOKIE; + command = webdriver.CommandName.DESCRIBE_SESSION; + command = webdriver.CommandName.DISMISS_ALERT; + command = webdriver.CommandName.DOUBLE_CLICK; + command = webdriver.CommandName.ELEMENT_EQUALS; + command = webdriver.CommandName.EXECUTE_ASYNC_SCRIPT; + command = webdriver.CommandName.EXECUTE_SCRIPT; + command = webdriver.CommandName.EXECUTE_SQL; + command = webdriver.CommandName.FIND_CHILD_ELEMENT; + command = webdriver.CommandName.FIND_CHILD_ELEMENTS; + command = webdriver.CommandName.FIND_ELEMENT; + command = webdriver.CommandName.FIND_ELEMENTS; + command = webdriver.CommandName.GET; + command = webdriver.CommandName.GET_ACTIVE_ELEMENT; + command = webdriver.CommandName.GET_ALERT_TEXT; + command = webdriver.CommandName.GET_ALL_COOKIES; + command = webdriver.CommandName.GET_APP_CACHE; + command = webdriver.CommandName.GET_APP_CACHE_STATUS; + command = webdriver.CommandName.GET_AVAILABLE_LOG_TYPES; + command = webdriver.CommandName.GET_COOKIE; + command = webdriver.CommandName.GET_CURRENT_URL; + command = webdriver.CommandName.GET_CURRENT_WINDOW_HANDLE; + command = webdriver.CommandName.GET_ELEMENT_ATTRIBUTE; + command = webdriver.CommandName.GET_ELEMENT_LOCATION; + command = webdriver.CommandName.GET_ELEMENT_LOCATION_IN_VIEW; + command = webdriver.CommandName.GET_ELEMENT_SIZE; + command = webdriver.CommandName.GET_ELEMENT_TAG_NAME; + command = webdriver.CommandName.GET_ELEMENT_TEXT; + command = webdriver.CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY; + command = webdriver.CommandName.GET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.GET_LOCAL_STORAGE_KEYS; + command = webdriver.CommandName.GET_LOCAL_STORAGE_SIZE; + command = webdriver.CommandName.GET_LOCATION; + command = webdriver.CommandName.GET_LOG; + command = webdriver.CommandName.GET_PAGE_SOURCE; + command = webdriver.CommandName.GET_SCREEN_ORIENTATION; + command = webdriver.CommandName.GET_SERVER_STATUS; + command = webdriver.CommandName.GET_SESSION_LOGS; + command = webdriver.CommandName.GET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.GET_SESSION_STORAGE_KEYS; + command = webdriver.CommandName.GET_SESSION_STORAGE_SIZE; + command = webdriver.CommandName.GET_SESSIONS; + command = webdriver.CommandName.GET_TITLE; + command = webdriver.CommandName.GET_WINDOW_HANDLES; + command = webdriver.CommandName.GET_WINDOW_POSITION; + command = webdriver.CommandName.GET_WINDOW_SIZE; + command = webdriver.CommandName.GO_BACK; + command = webdriver.CommandName.GO_FORWARD; + command = webdriver.CommandName.IMPLICITLY_WAIT; + command = webdriver.CommandName.IS_BROWSER_ONLINE; + command = webdriver.CommandName.IS_ELEMENT_DISPLAYED; + command = webdriver.CommandName.IS_ELEMENT_ENABLED; + command = webdriver.CommandName.IS_ELEMENT_SELECTED; + command = webdriver.CommandName.MAXIMIZE_WINDOW; + command = webdriver.CommandName.MOUSE_DOWN; + command = webdriver.CommandName.MOUSE_UP; + command = webdriver.CommandName.MOVE_TO; + command = webdriver.CommandName.NEW_SESSION; + command = webdriver.CommandName.QUIT; + command = webdriver.CommandName.REFRESH; + command = webdriver.CommandName.REMOVE_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.REMOVE_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SCREENSHOT; + command = webdriver.CommandName.SEND_KEYS_TO_ACTIVE_ELEMENT; + command = webdriver.CommandName.SEND_KEYS_TO_ELEMENT; + command = webdriver.CommandName.SET_ALERT_TEXT; + command = webdriver.CommandName.SET_BROWSER_ONLINE; + command = webdriver.CommandName.SET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.SET_LOCATION; + command = webdriver.CommandName.SET_SCREEN_ORIENTATION; + command = webdriver.CommandName.SET_SCRIPT_TIMEOUT; + command = webdriver.CommandName.SET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SET_TIMEOUT; + command = webdriver.CommandName.SET_WINDOW_POSITION; + command = webdriver.CommandName.SET_WINDOW_SIZE; + command = webdriver.CommandName.SUBMIT_ELEMENT; + command = webdriver.CommandName.SWITCH_TO_FRAME; + command = webdriver.CommandName.SWITCH_TO_WINDOW; + command = webdriver.CommandName.TOUCH_DOUBLE_TAP; + command = webdriver.CommandName.TOUCH_DOWN; + command = webdriver.CommandName.TOUCH_FLICK; + command = webdriver.CommandName.TOUCH_LONG_PRESS; + command = webdriver.CommandName.TOUCH_MOVE; + command = webdriver.CommandName.TOUCH_SCROLL; + command = webdriver.CommandName.TOUCH_SINGLE_TAP; + command = webdriver.CommandName.TOUCH_UP; +} + +function TestEventEmitter() { + var emitter: webdriver.EventEmitter = new webdriver.EventEmitter(); + + var callback = function (a: number, b: number, c: number) {}; + + emitter = emitter.addListener('ABC', callback); + + emitter.emit('ABC', 1, 2, 3); + + var listeners = emitter.listeners('ABC'); + var length: number = listeners.length; + var listenerInfo = listeners[0]; + if (listenerInfo.oneshot) { + listenerInfo.fn.apply(listenerInfo.scope, [1, 2, 3]); + } + + emitter = emitter.on('ABC', callback); + + emitter = emitter.once('ABC', callback); + + emitter = emitter.removeListener('ABC', callback); + + emitter.removeAllListeners('ABC'); + emitter.removeAllListeners(); +} + +function TestFirefoxDomExecutor() { + if (webdriver.FirefoxDomExecutor.isAvailable()) { + var executor: webdriver.CommandExecutor = new webdriver.FirefoxDomExecutor(); + var callback = function(error: Error, responseObject: any) {}; + executor.execute(new webdriver.Command(webdriver.CommandName.CLICK), callback); + } +} + +function TestKey() { + var key: string; + + key = webdriver.Key.ADD; + key = webdriver.Key.ALT; + key = webdriver.Key.ARROW_DOWN; + key = webdriver.Key.ARROW_LEFT; + key = webdriver.Key.ARROW_RIGHT; + key = webdriver.Key.ARROW_UP; + key = webdriver.Key.BACK_SPACE; + key = webdriver.Key.CANCEL; + key = webdriver.Key.CLEAR; + key = webdriver.Key.COMMAND; + key = webdriver.Key.CONTROL; + key = webdriver.Key.DECIMAL; + key = webdriver.Key.DELETE; + key = webdriver.Key.DIVIDE; + key = webdriver.Key.DOWN; + key = webdriver.Key.END; + key = webdriver.Key.ENTER; + key = webdriver.Key.EQUALS; + key = webdriver.Key.ESCAPE; + key = webdriver.Key.F1; + key = webdriver.Key.F2; + key = webdriver.Key.F3; + key = webdriver.Key.F4; + key = webdriver.Key.F5; + key = webdriver.Key.F6; + key = webdriver.Key.F7; + key = webdriver.Key.F8; + key = webdriver.Key.F9; + key = webdriver.Key.F10; + key = webdriver.Key.F11; + key = webdriver.Key.F12; + key = webdriver.Key.HELP; + key = webdriver.Key.HOME; + key = webdriver.Key.INSERT; + key = webdriver.Key.LEFT; + key = webdriver.Key.META; + key = webdriver.Key.MULTIPLY; + key = webdriver.Key.NULL; + key = webdriver.Key.NUMPAD0; + key = webdriver.Key.NUMPAD1; + key = webdriver.Key.NUMPAD2; + key = webdriver.Key.NUMPAD3; + key = webdriver.Key.NUMPAD4; + key = webdriver.Key.NUMPAD5; + key = webdriver.Key.NUMPAD6; + key = webdriver.Key.NUMPAD7; + key = webdriver.Key.NUMPAD8; + key = webdriver.Key.NUMPAD9; + key = webdriver.Key.PAGE_DOWN; + key = webdriver.Key.PAGE_UP; + key = webdriver.Key.PAUSE; + key = webdriver.Key.RETURN; + key = webdriver.Key.RIGHT; + key = webdriver.Key.SEMICOLON; + key = webdriver.Key.SEPARATOR; + key = webdriver.Key.SHIFT; + key = webdriver.Key.SPACE; + key = webdriver.Key.SUBTRACT; + key = webdriver.Key.TAB; + key = webdriver.Key.UP; + + key = webdriver.Key.chord(webdriver.Key.NUMPAD0, webdriver.Key.NUMPAD1); +} + +function TestLocator() { + var locator: webdriver.Locator = new webdriver.Locator('id', 'ABC'); + + var locatorStr: string = locator.toString(); + + var using: string = locator.using; + var value: string = locator.value; + + locator = webdriver.Locator.checkLocator(webdriver.Locator.Strategy.id('ABC')); + locator = webdriver.Locator.checkLocator({id: 'ABC'}); + + locator = webdriver.Locator.createFromObj({id: 'ABC'}); + + locator = webdriver.Locator.Strategy.id('ABC'); + + locator = webdriver.By.id('ABC'); +} + +function TestSession() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var capabilitiesObj: any = {}; + capabilitiesObj[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.ANDROID; + capabilitiesObj[webdriver.Capability.PLATFORM] = 'ANDROID'; + session = new webdriver.Session('ABC', capabilitiesObj); + + var capabilities: webdriver.Capabilities = session.getCapabilities(); + var capability: any = session.getCapability(webdriver.Capability.BROWSER_NAME); + var id: string = session.getId(); + var data: string = session.toJSON(); +} + +function TestUnhandledAlertError() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + + var alert: webdriver.Alert = new webdriver.Alert(driver, 'ABC'); + var error = new webdriver.UnhandledAlertError('An error', alert); + var baseError: webdriver.error.Error = error; + + alert = error.getAlert(); +} + +function TestWebDriverLogs() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var logs: webdriver.WebDriverLogs = webdriver.WebDriver.Logs; + var promise: webdriver.promise.Promise; + + promise = logs.get(webdriver.logging.Type.BROWSER); + promise = logs.getAvailableLogTypes(); +} + +function TestWebDriverNavigation() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var navigation: webdriver.WebDriverNavigation = webdriver.WebDriver.Navigation; + var promise: webdriver.promise.Promise; + + promise = navigation.back(); + promise = navigation.forward(); + promise = navigation.refresh(); + promise = navigation.to('http://google.com'); +} + +function TestWebDriverOptions() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var options: webdriver.WebDriverOptions = webdriver.WebDriver.Options; + var promise: webdriver.promise.Promise; + + // Add Cookie + promise = options.addCookie('name', 'value'); + promise = options.addCookie('name', 'value', 'path'); + promise = options.addCookie('name', 'value', 'path', 'domain'); + promise = options.addCookie('name', 'value', 'path', 'domain', true); + promise = options.addCookie('name', 'value', 'path', 'domain', true, 123); + promise = options.addCookie('name', 'value', 'path', 'domain', true, Date.now()); + + promise = options.deleteAllCookies(); + promise = options.deleteCookie('name'); + promise = options.getCookie('name'); + promise = options.getCookies(); + + var logs: webdriver.WebDriverLogs = options.logs(); + var timeouts: webdriver.WebDriverTimeouts = options.timeouts(); + var window: webdriver.WebDriverWindow = options.window(); +} + +function TestWebDriverTargetLocator() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.WebDriverTargetLocator = webdriver.WebDriver.TargetLocator; + var promise: webdriver.promise.Promise; + + var element: webdriver.WebElement = locator.activeElement(); + var alert: webdriver.Alert = locator.alert(); + promise = locator.defaultContent(); + promise = locator.frame('name'); + promise = locator.frame(1); + promise = locator.window('nameOrHandle'); +} + +function TestWebDriverTimeouts() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var timeouts: webdriver.WebDriverTimeouts = webdriver.WebDriver.Timeouts; + var promise: webdriver.promise.Promise; + + promise = timeouts.implicitlyWait(123); + promise = timeouts.pageLoadTimeout(123); + promise = timeouts.setScriptTimeout(123); +} + +function TestWebDriverWindow() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var window: webdriver.WebDriverWindow = webdriver.WebDriver.Window; + var promise: webdriver.promise.Promise; + + promise = window.getPosition(); + promise = window.getSize(); + promise = window.maximize(); + promise = window.setPosition(12, 34); + promise = window.setSize(12, 34); +} + +function TestWebDriver() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var executor: webdriver.CommandExecutor = new webdriver.FirefoxDomExecutor(); + var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); + var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); + driver = new webdriver.WebDriver(session, executor, flow); + driver = new webdriver.WebDriver(promise, executor); + driver = new webdriver.WebDriver(promise, executor, flow); + + // Call + var actions: webdriver.ActionSequence = driver.actions(); + promise = driver.call(function(){}); + promise = driver.call(function(){ var d: any = this;}, driver); + promise = driver.call(function(a: number){}, driver, 1); + + promise = driver.close(); + flow = driver.controlFlow(); + + // ExecuteAsyncScript + promise = driver.executeAsyncScript('function(){}'); + promise = driver.executeAsyncScript('function(){}', 1, 2, 3); + promise = driver.executeAsyncScript(function(){}); + promise = driver.executeAsyncScript(function(a: number){}, 1); + + // ExecuteScript + promise = driver.executeScript('function(){}'); + promise = driver.executeScript('function(){}', 1, 2, 3); + promise = driver.executeScript(function(){}); + promise = driver.executeScript(function(a: number){}, 1); + + var element: webdriver.WebElement; + element = driver.findElement(webdriver.By.id('ABC')); + element = driver.findElement({id: 'ABC'}); + element = driver.findElement(webdriver.By.js('function(){}'), 1, 2, 3); + element = driver.findElement({js: 'function(){}'}, 1, 2, 3); + + promise = driver.findElements(webdriver.By.className('ABC')); + promise = driver.findElements({className: 'ABC'}); + promise = driver.findElements(webdriver.By.js('function(){}'), 1, 2, 3); + promise = driver.findElements({js: 'function(){}'}, 1, 2, 3); + + promise = driver.get('http://www.google.com'); + promise = driver.getAllWindowHandles(); + promise = driver.getCapabilities(); + promise = driver.getCurrentUrl(); + promise = driver.getPageSource() + promise = driver.getSession(); + promise = driver.getTitle(); + promise = driver.getWindowHandle(); + + promise = driver.isElementPresent(webdriver.By.className('ABC')); + promise = driver.isElementPresent({className: 'ABC'}); + promise = driver.isElementPresent(webdriver.By.js('function(){}'), 1, 2, 3); + promise = driver.isElementPresent({js: 'function(){}'}, 1, 2, 3); + + var options: webdriver.WebDriverOptions = driver.manage(); + var navigation: webdriver.WebDriverNavigation = driver.navigate(); + var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); + + promise = driver.quit(); + promise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); + promise = driver.sleep(123); + promise = driver.takeScreenshot(); + + promise = driver.wait(function() { return true; }, 123); + promise = driver.wait(function() { return true; }, 123, 'Message'); + promise = driver.wait(function() { return promise; }, 123); + promise = driver.wait(function() { return promise; }, 123, 'Message'); + + driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); + driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); +} + +function TestWebElement() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var element: webdriver.WebElement; + var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + + element = new webdriver.WebElement(driver, 'ID'); + element = new webdriver.WebElement(driver, promise); + + var deferred: webdriver.promise.Deferred = element; + + promise = element.clear(); + promise = element.click(); + + element = element.findElement(webdriver.By.id('ABC')); + element = element.findElement({id: 'ABC'}); + element = element.findElement(webdriver.By.js('function(){}'), 1, 2, 3); + element = element.findElement({js: 'function(){}'}, 1, 2, 3); + + promise = element.findElements(webdriver.By.className('ABC')); + promise = element.findElements({className: 'ABC'}); + promise = element.findElements(webdriver.By.js('function(){}'), 1, 2, 3); + promise = element.findElements({js: 'function(){}'}, 1, 2, 3); + + promise = element.isElementPresent(webdriver.By.className('ABC')); + promise = element.isElementPresent({className: 'ABC'}); + promise = element.isElementPresent(webdriver.By.js('function(){}'), 1, 2, 3); + promise = element.isElementPresent({js: 'function(){}'}, 1, 2, 3); + + promise = element.getAttribute('class'); + promise = element.getCssValue('display'); + driver = element.getDriver(); + promise = element.getInnerHtml(); + promise = element.getLocation(); + promise = element.getOuterHtml(); + promise = element.getSize(); + promise = element.getTagName(); + promise = element.getText(); + promise = element.isDisplayed(); + promise = element.isEnabled(); + promise = element.isSelected(); + promise = element.sendKeys('A', 'B', 'C'); + promise = element.submit(); + promise = element.toWireValue(); + + promise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'ID2')); + + var key: string = webdriver.WebElement.ELEMENT_KEY; +} + +function TestLogging() { + webdriver.logging.Preferences['name'] = 'ABC'; + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + level = webdriver.logging.getLevel(1); + + level = webdriver.logging.Level.ALL; + level = webdriver.logging.Level.DEBUG; + level = webdriver.logging.Level.INFO; + level = webdriver.logging.Level.OFF; + level = webdriver.logging.Level.SEVERE; + level = webdriver.logging.Level.WARNING; + + var name: string = level.name; + var value: number = level.value; + + name = webdriver.logging.LevelName.ALL; + name = webdriver.logging.LevelName.DEBUG; + name = webdriver.logging.LevelName.INFO; + name = webdriver.logging.LevelName.OFF; + name = webdriver.logging.LevelName.SEVERE; + name = webdriver.logging.LevelName.WARNING; + + var type: string; + type = webdriver.logging.Type.BROWSER; + type = webdriver.logging.Type.CLIENT; + type = webdriver.logging.Type.DRIVER; + type = webdriver.logging.Type.PERFORMANCE; + type = webdriver.logging.Type.SERVER; +} + +function TestLoggingEntry() { + var entry: webdriver.logging.Entry; + + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC'); + entry = new webdriver.logging.Entry('ALL', 'ABC'); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123, webdriver.logging.Type.BROWSER); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123, webdriver.logging.Type.BROWSER); + + var entryObj: any = entry.toJSON(); + + var message: string = entry.message; + var timestamp: number = entry.timestamp; + var type: string = entry.type; + + entry = webdriver.logging.Entry.fromClosureLogRecord({}); + entry = webdriver.logging.Entry.fromClosureLogRecord({}, webdriver.logging.Type.DRIVER); +} + +function TestProcess() { + var isNative: boolean = webdriver.process.isNative(); + var value: string; + + value = webdriver.process.getEnv('name'); + value = webdriver.process.getEnv('name', 'default'); + + webdriver.process.setEnv('name', 'value'); + webdriver.process.setEnv('name', 123); +} + +function TestPromise() { + var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + + webdriver.promise.asap(promise, function(value: any){ return true; }); + webdriver.promise.asap(promise, function(value: any){}, function(err: any) { return 'ABC'; }); + + promise = webdriver.promise.checkedNodeCall(function(err: any, value: any) { return 123; }); + + var flow: webdriver.promise.ControlFlow = webdriver.promise.controlFlow(); + + promise = webdriver.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { }); + + var deferred: webdriver.promise.Deferred; + deferred = webdriver.promise.defer(function() {}); + deferred = webdriver.promise.defer(function(reason?: any) {}); + + promise = webdriver.promise.delayed(123); + + promise = webdriver.promise.fulfilled(); + promise = webdriver.promise.fulfilled({a: 123}); + + promise = webdriver.promise.fullyResolved({a: 123}); + + var isPromise: boolean = webdriver.promise.isPromise('ABC'); + + promise = webdriver.promise.rejected({a: 123}); + + webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + promise = webdriver.promise.when(promise, function(value: any) { return 123; }, function(err: Error) { return 123; }); +} + +function TestControlFlow() { + var flow: webdriver.promise.ControlFlow; + flow = new webdriver.promise.ControlFlow(); + flow = new webdriver.promise.ControlFlow({clearInterval: function(a: number) {}, + clearTimeout: function(a: number) {}, + setInterval: function(a: () => void, b: number) { return 2; }, + setTimeout: function(a: () => void, b: number) { return 2; }}); + + var emitter: webdriver.EventEmitter = flow; + + var eventType: string; + + eventType = webdriver.promise.ControlFlow.EventType.IDLE; + eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK; + eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; + + var e: any = flow.annotateError(new Error('Error')); + + var promise: webdriver.promise.Promise; + + promise = flow.await(promise); + + flow.clearHistory(); + + promise = flow.execute(function() { return promise; }); + promise = flow.execute(function() { return promise; }, 'Description'); + + var history: string[] = flow.getHistory(); + + var schedule: string = flow.getSchedule(); + + flow.reset(); + + promise = flow.timeout(123); + promise = flow.timeout(123, 'Description'); + + promise = flow.wait(function() { return true; }, 123); + promise = flow.wait(function() { return true; }, 123, 'Timeout Message'); + promise = flow.wait(function() { return promise; }, 123, 'Timeout Message'); + + var timer: webdriver.promise.IControlFlowTimer = flow.timer; + + timer = webdriver.promise.ControlFlow.defaultTimer; + var loopFrequency: number = webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY; +} + +function TestDeferred() { + var deferred: webdriver.promise.Deferred; + + deferred = new webdriver.promise.Deferred(); + deferred = new webdriver.promise.Deferred(function() {}); + deferred = new webdriver.promise.Deferred(function(reason: any) { }); + deferred = new webdriver.promise.Deferred(function() {}, new webdriver.promise.ControlFlow()); + + var promise: webdriver.promise.Promise = deferred; + + deferred.errback(new Error('Error')); + deferred.errback('Error'); + deferred.fulfill(123); + deferred.reject(new Error('Error')); + deferred.reject('Error'); + deferred.removeAll(); + + promise = deferred.promise; +} + +function TestPromiseClass() { + var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + + var obj = { + a: 5 + } + + promise = promise.addBoth(function( a: any ) { }); + promise = promise.addBoth(function( a: any ) { return 123; }); + promise = promise.addBoth(function( a: any ) { }, obj); + + promise = promise.addCallback(function( a: any ) { }); + promise = promise.addCallback(function( a: any ) { return 123; }); + promise = promise.addCallback(function( a: any ) { }, obj); + + promise = promise.addErrback(function( e: any ) { }); + promise = promise.addErrback(function( e: any ) { return 123; }); + promise = promise.addErrback(function( e: any ) { }, obj); + + promise.cancel(obj); + + var isPending: boolean = promise.isPending(); + + promise = promise.then(); + promise = promise.then(function( a: any ) { }); + promise = promise.then(function( a: any ) { return 123; }); + promise = promise.then(function( a: any ) {}, function( e: any) {}); + promise = promise.then(function( a: any ) {}, function( e: any) { return 123; }); +} + +function TestErrorCode() { + var errorCode: number; + + errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE; + errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_VISIBLE; + errorCode = webdriver.error.ErrorCode.IME_ENGINE_ACTIVATION_FAILED; + errorCode = webdriver.error.ErrorCode.IME_NOT_AVAILABLE; + errorCode = webdriver.error.ErrorCode.INVALID_COOKIE_DOMAIN; + errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_COORDINATES; + errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_STATE; + errorCode = webdriver.error.ErrorCode.INVALID_SELECTOR_ERROR; + errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR; + errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPE; + errorCode = webdriver.error.ErrorCode.JAVASCRIPT_ERROR; + errorCode = webdriver.error.ErrorCode.METHOD_NOT_ALLOWED; + errorCode = webdriver.error.ErrorCode.MODAL_DIALOG_OPENED; + errorCode = webdriver.error.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS; + errorCode = webdriver.error.ErrorCode.NO_MODAL_DIALOG_OPEN; + errorCode = webdriver.error.ErrorCode.NO_SUCH_ELEMENT; + errorCode = webdriver.error.ErrorCode.NO_SUCH_FRAME; + errorCode = webdriver.error.ErrorCode.NO_SUCH_WINDOW; + errorCode = webdriver.error.ErrorCode.SCRIPT_TIMEOUT; + errorCode = webdriver.error.ErrorCode.SESSION_NOT_CREATED; + errorCode = webdriver.error.ErrorCode.SQL_DATABASE_ERROR; + errorCode = webdriver.error.ErrorCode.STALE_ELEMENT_REFERENCE; + errorCode = webdriver.error.ErrorCode.SUCCESS; + errorCode = webdriver.error.ErrorCode.TIMEOUT; + errorCode = webdriver.error.ErrorCode.UNABLE_TO_SET_COOKIE; + errorCode = webdriver.error.ErrorCode.UNKNOWN_COMMAND; + errorCode = webdriver.error.ErrorCode.UNKNOWN_ERROR; + errorCode = webdriver.error.ErrorCode.UNSUPPORTED_OPERATION; + errorCode = webdriver.error.ErrorCode.XPATH_LOOKUP_ERROR; +} + +function TestError() { + var error: webdriver.error.Error; + + error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE); + error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE, 'Message'); + + var code: number = error.code; + var state: string = error.state; + var message: string = error.message; + var name: string = error.name; + var stack: string = error.stack; + var isAutomationError: boolean = error.isAutomationError; + var errorStr: string = error.toString(); + + state = webdriver.error.Error.State.ELEMENT_NOT_SELECTABLE + state = webdriver.error.Error.State.ELEMENT_NOT_VISIBLE; + state = webdriver.error.Error.State.IME_ENGINE_ACTIVATION_FAILED; + state = webdriver.error.Error.State.IME_NOT_AVAILABLE; + state = webdriver.error.Error.State.INVALID_COOKIE_DOMAIN; + state = webdriver.error.Error.State.INVALID_ELEMENT_COORDINATES; + state = webdriver.error.Error.State.INVALID_ELEMENT_STATE; + state = webdriver.error.Error.State.INVALID_SELECTOR; + state = webdriver.error.Error.State.JAVASCRIPT_ERROR; + state = webdriver.error.Error.State.MOVE_TARGET_OUT_OF_BOUNDS; + state = webdriver.error.Error.State.NO_SUCH_ALERT; + state = webdriver.error.Error.State.NO_SUCH_DOM + state = webdriver.error.Error.State.NO_SUCH_ELEMENT; + state = webdriver.error.Error.State.NO_SUCH_FRAME; + state = webdriver.error.Error.State.NO_SUCH_WINDOW; + state = webdriver.error.Error.State.SCRIPT_TIMEOUT; + state = webdriver.error.Error.State.SESSION_NOT_CREATED; + state = webdriver.error.Error.State.STALE_ELEMENT_REFERENCE; + state = webdriver.error.Error.State.SUCCESS; + state = webdriver.error.Error.State.TIMEOUT; + state = webdriver.error.Error.State.UNABLE_TO_SET_COOKIE; + state = webdriver.error.Error.State.UNEXPECTED_ALERT_OPEN + state = webdriver.error.Error.State.UNKNOWN_COMMAND; + state = webdriver.error.Error.State.UNKNOWN_ERROR; + state = webdriver.error.Error.State.UNSUPPORTED_OPERATION; +} \ No newline at end of file diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts new file mode 100644 index 0000000000..9ce5321de5 --- /dev/null +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -0,0 +1,3153 @@ +// Type definitions for Selenium WebDriverJS 2.39.0 +// Project: https://code.google.com/p/selenium/ +// Definitions by: Bill Armstrong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module webdriver { + + module logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + var Preferences: any; + + /** + * Log level names from WebDriver's JSON wire protocol. + * @enum {string} + */ + class LevelName { + static ALL: string; + static DEBUG: string; + static INFO: string; + static WARNING: string; + static SEVERE: string; + static OFF: string; + } + + /** + * Common log types. + * @enum {string} + */ + class Type { + /** Logs originating from the browser. */ + static BROWSER: string; + /** Logs from a WebDriver client. */ + static CLIENT: string; + /** Logs from a WebDriver implementation. */ + static DRIVER: string; + /** Logs related to performance. */ + static PERFORMANCE: string; + /** Logs from the remote server. */ + static SERVER: string; + } + + /** + * Logging levels. + * @enum {{value: number, name: webdriver.logging.LevelName}} + */ + class Level { + //region Static Properties + + static ALL: Level; + static DEBUG: Level; + static INFO: Level; + static WARNING: Level; + static SEVERE: Level; + static OFF: Level; + + //endregion + + //region Properties + + value: number; + name: string; + + //endregion + } + + /** + * Converts a level name or value to a {@link webdriver.logging.Level} value. + * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!webdriver.logging.Level} The converted level. + */ + function getLevel(nameOrValue: string): webdriver.logging.Level; + function getLevel(nameOrValue: number): webdriver.logging.Level; + + /** + * A single log entry. + */ + class Entry { + + //region Constructors + + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: webdriver.logging.Level, message: string, opt_timestamp?:number, opt_type?:string); + constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + + //endregion + + //region Public Properties + + /** @type {!webdriver.logging.Level} */ + level: webdriver.logging.Level; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + //endregion + + //region Static Methods + + /** + * Converts a {@link goog.debug.LogRecord} into a + * {@link webdriver.logging.Entry}. + * @param {!goog.debug.LogRecord} logRecord The record to convert. + * @param {string=} opt_type The log type. + * @return {!webdriver.logging.Entry} The converted entry. + */ + static fromClosureLogRecord(logRecord: any, opt_type?:string): webdriver.logging.Entry; + + //endregion + + //region Methods + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): webdriver.logging.Level; + + //endregion + } + } + + module promise { + + //region Functions + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): webdriver.promise.ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: webdriver.promise.ControlFlow) => any): webdriver.promise.Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): webdriver.promise.Promise; + + /** + * Creates a new deferred object. + * @param {Function=} opt_canceller Function to call when cancelling the + * computation of this instance's value. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(opt_canceller?: any): webdriver.promise.Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: any): webdriver.promise.Promise; + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): webdriver.promise.Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: (error: any, value: any) => any): webdriver.promise.Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: any, opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@code webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: (value: any) => any, opt_errback?: (error: any) => any): void; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): webdriver.promise.Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; + + //endregion + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, resolved, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or failed state. + * + *

This class is based on the Promise/A proposal from CommonJS. Additional + * functions are provided for API compatibility with Dojo Deferred objects. + * + * @see http://wiki.commonjs.org/wiki/Promises/A + */ + class Promise { + + //region Constructors + + /** + * @constructor + * @see http://wiki.commonjs.org/wiki/Promises/A + */ + constructor(); + + //endregion + + //region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(reason: any): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param {Function=} opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param {Function=} opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return {!webdriver.promise.Promise} A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): Promise; + + /** + * Registers a function to be invoked when this promise is successfully + * resolved. This function is provided for backwards compatibility with the + * Dojo Deferred API. + * + * @param {Function} callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param {!Object=} opt_self The object which |this| should refer to when the + * function is invoked. + * @return {!webdriver.promise.Promise} A new promise which will be resolved + * with the result of the invoked callback. + */ + addCallback(callback: (value: any) => any, opt_self?: any): Promise; + + + /** + * Registers a function to be invoked when this promise is rejected. + * This function is provided for backwards compatibility with the + * Dojo Deferred API. + * + * @param {Function} errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @param {!Object=} opt_self The object which |this| should refer to when the + * function is invoked. + * @return {!webdriver.promise.Promise} A new promise which will be resolved + * with the result of the invoked callback. + */ + addErrback(errback: (error: any) => any, opt_self?: any): Promise; + + /** + * Registers a function to be invoked when this promise is either rejected or + * resolved. This function is provided for backwards compatibility with the + * Dojo Deferred API. + * + * @param {Function} callback The function to call when this promise is + * either resolved or rejected. The function should expect a single + * argument: the resolved value or rejection error. + * @param {!Object=} opt_self The object which |this| should refer to when the + * function is invoked. + * @return {!webdriver.promise.Promise} A new promise which will be resolved + * with the result of the invoked callback. + */ + addBoth(callback : (value: any) => any, opt_self?: any): Promise; + + /** + * An alias for {@code webdriver.promise.Promise.prototype.then} that permits + * the scope of the invoked function to be specified. This function is provided + * for backwards compatibility with the Dojo Deferred API. + * + * @param {Function} callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param {Function} errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @param {!Object=} opt_self The object which |this| should refer to when the + * function is invoked. + * @return {!webdriver.promise.Promise} A new promise which will be resolved + * with the result of the invoked callback. + */ + addCallbacks(callback: (value: any) => any, errback: (error: any) => any, opt_self?: any): Promise; + + //endregion + } + + /** + * Represents a value that will be resolved at some point in the future. This + * class represents the protected "producer" half of a Promise - each Deferred + * has a {@code promise} property that may be returned to consumers for + * registering callbacks, reserving the ability to resolve the deferred to the + * producer. + * + *

If this Deferred is rejected and there are no listeners registered before + * the next turn of the event loop, the rejection will be passed to the + * {@link webdriver.promise.ControlFlow} as an unhandled failure. + * + *

If this Deferred is cancelled, the cancellation reason will be forward to + * the Deferred's canceller function (if provided). The canceller may return a + * truth-y value to override the reason provided for rejection. + * + * @extends {webdriver.promise.Promise} + */ + class Deferred extends Promise { + //region Constructors + + /** + * + * @param {Function=} opt_canceller Function to call when cancelling the + * computation of this instance's value. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow + * this instance was created under. This should only be provided during + * unit tests. + * @constructor + */ + constructor(opt_canceller?: any, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region Properties + + /** + * The consumer promise for this instance. Provides protected access to the + * callback registering functions. + * @type {!webdriver.promise.Promise} + */ + promise: webdriver.promise.Promise; + + //endregion + + //region Methods + + /** + * Rejects this promise. If the error is itself a promise, this instance will + * be chained to it and be rejected with the error's resolved value. + * @param {*=} opt_error The rejection reason, typically either a + * {@code Error} or a {@code string}. + */ + reject(opt_error?: any): void; + errback(opt_error?: any): void; + + /** + * Resolves this promise with the given value. If the value is itself a + * promise and not a reference to this deferred, this instance will wait for + * it before resolving. + * @param {*=} opt_value The resolved value. + */ + fulfill(opt_value?: any): void; + + /** + * Cancels the computation of this promise's value and flags the promise as a + * rejected value. + * @param {*=} opt_reason The reason for cancelling this promise. + */ + cancel(opt_reason?: any): void; + + /** + * Removes all of the listeners previously registered on this deferred. + * @throws {Error} If this deferred has already been resolved. + */ + removeAll(): void; + + //endregion + } + + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: any, ms: number) => number; + setTimeout: (fn: any, ms: number) => number; + } + + /** + * Handles the execution of scheduled tasks, each of which may be an + * asynchronous operation. The control flow will ensure tasks are executed in + * the ordered scheduled, starting each task only once those before it have + * completed. + * + *

Each task scheduled within this flow may return a + * {@link webdriver.promise.Promise} to indicate it is an asynchronous + * operation. The ControlFlow will wait for such promises to be resolved before + * marking the task as completed. + * + *

Tasks and each callback registered on a {@link webdriver.promise.Deferred} + * will be run in their own ControlFlow frame. Any tasks scheduled within a + * frame will have priority over previously scheduled tasks. Furthermore, if + * any of the tasks in the frame fails, the remainder of the tasks in that frame + * will be discarded and the failure will be propagated to the user through the + * callback/task's promised result. + * + *

Each time a ControlFlow empties its task queue, it will fire an + * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely, + * whenever the flow terminates due to an unhandled error, it will remove all + * remaining tasks in its queue and fire an + * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If + * there are no listeners registered with the flow, the error will be + * rethrown to the global error handler. + * + * @extends {webdriver.EventEmitter} + */ + class ControlFlow extends webdriver.EventEmitter { + + //region Constructors + + /** + * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object + * to use. Should only be set for testing. + * @constructor + */ + constructor(opt_timer?: webdriver.promise.IControlFlowTimer); + + //endregion + + //region Properties + + /** + * The timer used by this instance. + * @type {webdriver.promise.ControlFlow.Timer} + */ + timer: webdriver.promise.IControlFlowTimer; + + //endregion + + //region Static Properties + + /** + * The default timer object, which uses the global timer functions. + * @type {webdriver.promise.ControlFlow.Timer} + */ + static defaultTimer: webdriver.promise.IControlFlowTimer; + + /** + * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. + * @enum {string} + */ + static EventType: { + /** Emitted when all tasks have been successfully executed. */ + IDLE: string; + + /** Emitted whenever a new task has been scheduled. */ + SCHEDULE_TASK: string; + + /** + * Emitted whenever a control flow aborts due to an unhandled promise + * rejection. This event will be emitted along with the offending rejection + * reason. Upon emitting this event, the control flow will empty its task + * queue and revert to its initial state. + */ + UNCAUGHT_EXCEPTION: string; + }; + + /** + * How often, in milliseconds, the event loop should run. + * @type {number} + * @const + */ + static EVENT_LOOP_FREQUENCY: number; + + //endregion + + //region Methods + + /** + * Resets this instance, clearing its queue and removing all event listeners. + */ + reset(): void; + + /** + * Returns a summary of the recent task activity for this instance. This + * includes the most recently completed task, as well as any parent tasks. In + * the returned summary, the task at index N is considered a sub-task of the + * task at index N+1. + * @return {!Array.} A summary of this instance's recent task + * activity. + */ + getHistory(): string[]; + + /** Clears this instance's task history. */ + clearHistory(): void; + + /** + * Appends a summary of this instance's recent task history to the given + * error's stack trace. This function will also ensure the error's stack trace + * is in canonical form. + * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate. + * @return {!(Error|goog.testing.JsUnitException)} The annotated error. + */ + annotateError(e: any): any; + + /** + * @return {string} The scheduled tasks still pending with this instance. + */ + getSchedule(): string; + + /** + * Schedules a task for execution. If there is nothing currently in the + * queue, the task will be executed in the next turn of the event loop. + * + * @param {!Function} fn The function to call to start the task. If the + * function returns a {@link webdriver.promise.Promise}, this instance + * will wait for it to be resolved before starting the next task. + * @param {string=} opt_description A description of the task. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + execute(fn: any, opt_description?: string): webdriver.promise.Promise; + + /** + * Inserts a {@code setTimeout} into the command queue. This is equivalent to + * a thread sleep in a synchronous programming language. + * + * @param {number} ms The timeout delay, in milliseconds. + * @param {string=} opt_description A description to accompany the timeout. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + timeout(ms: number, opt_description?: string): webdriver.promise.Promise; + + /** + * Schedules a task that shall wait for a condition to hold. Each condition + * function may return any value, but it will always be evaluated as a boolean. + * + *

Condition functions may schedule sub-tasks with this instance, however, + * their execution time will be factored into whether a wait has timed out. + * + *

In the event a condition returns a Promise, the polling loop will wait for + * it to be resolved before evaluating whether the condition has been satisfied. + * The resolution time for a promise is factored into whether a wait has timed + * out. + * + *

If the condition function throws, or returns a rejected promise, the + * wait task will fail. + * + * @param {!Function} condition The condition function to poll. + * @param {number} timeout How long to wait, in milliseconds, for the condition + * to hold before timing out. + * @param {string=} opt_message An optional error message to include if the + * wait times out; defaults to the empty string. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * condition has been satisified. The promise shall be rejected if the wait + * times out waiting for the condition. + */ + wait(condition: any, timeout: number, opt_message?: string): webdriver.promise.Promise; + + /** + * Schedules a task that will wait for another promise to resolve. The resolved + * promise's value will be returned as the task result. + * @param {!webdriver.promise.Promise} promise The promise to wait on. + * @return {!webdriver.promise.Promise} A promise that will resolve when the + * task has completed. + */ + await(promise: webdriver.promise.Promise): webdriver.promise.Promise; + + //endregion + } + } + + module error { + + // NOTE: A class was used instead of an Enum so that it could be extended in Protractor. + class ErrorCode { + static SUCCESS: number; + + static NO_SUCH_ELEMENT: number; + static NO_SUCH_FRAME: number; + static UNKNOWN_COMMAND: number; + static UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. + static STALE_ELEMENT_REFERENCE: number; + static ELEMENT_NOT_VISIBLE: number; + static INVALID_ELEMENT_STATE: number; + static UNKNOWN_ERROR: number; + static ELEMENT_NOT_SELECTABLE: number; + static JAVASCRIPT_ERROR: number; + static XPATH_LOOKUP_ERROR: number; + static TIMEOUT: number; + static NO_SUCH_WINDOW: number; + static INVALID_COOKIE_DOMAIN: number; + static UNABLE_TO_SET_COOKIE: number; + static MODAL_DIALOG_OPENED: number; + static NO_MODAL_DIALOG_OPEN: number; + static SCRIPT_TIMEOUT: number; + static INVALID_ELEMENT_COORDINATES: number; + static IME_NOT_AVAILABLE: number; + static IME_ENGINE_ACTIVATION_FAILED: number; + static INVALID_SELECTOR_ERROR: number; + static SESSION_NOT_CREATED: number; + static MOVE_TARGET_OUT_OF_BOUNDS: number; + static SQL_DATABASE_ERROR: number; + static INVALID_XPATH_SELECTOR: number; + static INVALID_XPATH_SELECTOR_RETURN_TYPE: number; + // The following error codes are derived straight from HTTP return codes. + static METHOD_NOT_ALLOWED: number; + } + + /** + * Error extension that includes error status codes from the WebDriver wire + * protocol: + * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes + * + * @extends {Error} + */ + class Error { + + //region Constructors + + /** + * @param {!bot.ErrorCode} code The error's status code. + * @param {string=} opt_message Optional error message. + * @constructor + */ + constructor(code: number, opt_message?: string); + + //endregion + + //region Static Properties + + /** + * Status strings enumerated in the W3C WebDriver working draft. + * @enum {string} + * @see http://www.w3.org/TR/webdriver/#status-codes + */ + static State: { + ELEMENT_NOT_SELECTABLE: string; + ELEMENT_NOT_VISIBLE: string; + IME_ENGINE_ACTIVATION_FAILED: string; + IME_NOT_AVAILABLE: string; + INVALID_COOKIE_DOMAIN: string; + INVALID_ELEMENT_COORDINATES: string; + INVALID_ELEMENT_STATE: string; + INVALID_SELECTOR: string; + JAVASCRIPT_ERROR: string; + MOVE_TARGET_OUT_OF_BOUNDS: string; + NO_SUCH_ALERT: string; + NO_SUCH_DOM: string; + NO_SUCH_ELEMENT: string; + NO_SUCH_FRAME: string; + NO_SUCH_WINDOW: string; + SCRIPT_TIMEOUT: string; + SESSION_NOT_CREATED: string; + STALE_ELEMENT_REFERENCE: string; + SUCCESS: string; + TIMEOUT: string; + UNABLE_TO_SET_COOKIE: string; + UNEXPECTED_ALERT_OPEN: string; + UNKNOWN_COMMAND: string; + UNKNOWN_ERROR: string; + UNSUPPORTED_OPERATION: string; + } + + //endregion + + //region Properties + + /** + * This error's status code. + * @type {!bot.ErrorCode} + */ + code: number; + + /** @type {string} */ + state: string; + + /** @override */ + message: string; + + /** @override */ + name: string; + + /** @override */ + stack: string; + + /** + * Flag used for duck-typing when this code is embedded in a Firefox extension. + * This is required since an Error thrown in one component and then reported + * to another will fail instanceof checks in the second component. + * @type {boolean} + */ + isAutomationError: boolean; + + //endregion + + //region Methods + + /** @return {string} The string representation of this error. */ + toString(): string; + + //endregion + } + } + + module process { + + /** + * Queries for a named environment variable. + * @param {string} name The name of the environment variable to look up. + * @param {string=} opt_default The default value if the named variable is not + * defined. + * @return {string} The queried environment variable. + */ + function getEnv(name: string, opt_default?: string): string; + + /** + * @return {boolean} Whether the current process is Node's native process + * object. + */ + function isNative(): boolean; + + /** + * Sets an environment value. If the new value is either null or undefined, the + * environment variable will be cleared. + * @param {string} name The value to set. + * @param {*} value The new value; will be coerced to a string. + */ + function setEnv(name: string, value: any): void; + + } + + /** + * Creates new {@code webdriver.WebDriver} clients. Upon instantiation, each + * Builder will configure itself based on the following environment variables: + *

+ *
{@code webdriver.AbstractBuilder.SERVER_URL_ENV}
+ *
Defines the remote WebDriver server that should be used for command + * command execution; may be overridden using + * {@code webdriver.AbstractBuilder.prototype.usingServer}.
+ *
+ */ + class AbstractBuilder { + + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Static Properties + + /** + * Environment variable that defines the URL of the WebDriver server that + * should be used for all new WebDriver clients. This setting may be overridden + * using {@code #usingServer(url)}. + * @type {string} + * @const + * @see webdriver.process.getEnv + */ + static SERVER_URL_ENV: string; + + + /** + * The default URL of the WebDriver server to use if + * {@link webdriver.AbstractBuilder.SERVER_URL_ENV} is not set. + * @type {string} + * @const + */ + static DEFAULT_SERVER_URL: string; + + //endregion + + //region Methods + + /** + * Configures which WebDriver server should be used for new sessions. Overrides + * the value loaded from the {@link webdriver.AbstractBuilder.SERVER_URL_ENV} + * upon creation of this instance. + * @param {string} url URL of the server to use. + * @return {!webdriver.AbstractBuilder} This Builder instance for chain calling. + */ + usingServer(url: string): AbstractBuilder; + + /** + * @return {string} The URL of the WebDriver server this instance is configured + * to use. + */ + getServerUrl(): string; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set desired capabilities. + * @param {!(Object|webdriver.Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!webdriver.AbstractBuilder} This Builder instance for chain calling. + */ + withCapabilities(capabilities: webdriver.Capabilities): AbstractBuilder; + withCapabilities(capabilities: any): AbstractBuilder; + + /** + * @return {!webdriver.Capabilities} The current desired capabilities for this + * builder. + */ + getCapabilities(): webdriver.Capabilities; + + /** + * Builds a new {@link webdriver.WebDriver} instance using this builder's + * current configuration. + * @return {!webdriver.WebDriver} A new WebDriver client. + */ + build(): webdriver.WebDriver; + + //endregion + } + + interface ILocation { + x: number; + y: number; + } + + /** + * Enumeration of the buttons used in the advanced interactions API. + * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. + * @enum {number} + */ + class Button { + static LEFT: number; + static MIDDLE: number; + static RIGHT: number; + } + + /** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * NOTE: A class was used instead of an Enum so that it could be extended in Protractor + * + * @enum {string} + */ + class Key { + static NULL: string; + static CANCEL: string; // ^break + static HELP: string; + static BACK_SPACE: string; + static TAB: string; + static CLEAR: string; + static RETURN: string; + static ENTER: string; + static SHIFT: string; + static CONTROL: string; + static ALT: string; + static PAUSE: string; + static ESCAPE: string; + static SPACE: string; + static PAGE_UP: string; + static PAGE_DOWN: string; + static END: string; + static HOME: string; + static ARROW_LEFT: string; + static LEFT: string; + static ARROW_UP: string; + static UP: string; + static ARROW_RIGHT: string; + static RIGHT: string; + static ARROW_DOWN: string; + static DOWN: string; + static INSERT: string; + static DELETE: string; + static SEMICOLON: string; + static EQUALS: string; + + static NUMPAD0: string; // number pad keys + static NUMPAD1: string; + static NUMPAD2: string; + static NUMPAD3: string; + static NUMPAD4: string; + static NUMPAD5: string; + static NUMPAD6: string; + static NUMPAD7: string; + static NUMPAD8: string; + static NUMPAD9: string; + static MULTIPLY: string; + static ADD: string; + static SEPARATOR: string; + static SUBTRACT: string; + static DECIMAL: string; + static DIVIDE: string; + + static F1: string; // function keys + static F2: string; + static F3: string; + static F4: string; + static F5: string; + static F6: string; + static F7: string; + static F8: string; + static F9: string; + static F10: string; + static F11: string; + static F12: string; + + static COMMAND: string; // Apple command key + static META: string; // alias for Windows key + + /** + * Simulate pressing many keys at once in a "chord". Takes a sequence of + * {@link webdriver.Key}s or strings, appends each of the values to a string, + * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns + * the resultant string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + * @see http://code.google.com/p/webdriver/issues/detail?id=79 + */ + static chord(...var_args: string[]): string; + } + + /** + * Class for defining sequences of complex user interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + *

Example:


+     *   new webdriver.ActionSequence(driver).
+     *       keyDown(webdriver.Key.SHIFT).
+     *       click(element1).
+     *       click(element2).
+     *       dragAndDrop(element3, element4).
+     *       keyUp(webdriver.Key.SHIFT).
+     *       perform();
+     * 
+ * + */ + class ActionSequence { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Executes this action sequence. + * @return {!webdriver.promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): webdriver.promise.Promise; + + /** + * Moves the mouse. The location to move to may be specified in terms of the + * mouse's current location, an offset relative to the top-left corner of an + * element, or an element (in which case the middle of the element is used). + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in pixels. + * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. + * Defaults to (0, 0). + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseMove(location: webdriver.WebElement, opt_offset?: ILocation): ActionSequence + mouseMove(location: ILocation): ActionSequence + + /** + * Presses a mouse button. The mouse button will not be released until + * {@link #mouseUp} is called, regardless of whether that call is made in this + * sequence or another. The behavior for out-of-order events (e.g. mouseDown, + * click) is undefined. + * + *

If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

sequence.mouseMove(element).mouseDown()
+ * + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: webdriver.WebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: number): ActionSequence; + + /** + * Releases a mouse button. Behavior is undefined for calling this function + * without a previous call to {@link #mouseDown}. + * + *

If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

sequence.mouseMove(element).mouseUp()
+ * + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: webdriver.WebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: number): ActionSequence; + + /** + * Convenience function for performing a "drag and drop" manuever. The target + * element may be moved to the location of another element, or by an offset (in + * pixels). + * @param {!webdriver.WebElement} element The element to drag. + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in pixels. + * @return {!webdriver.ActionSequence} A self reference. + */ + dragAndDrop(element: webdriver.WebElement, location: webdriver.WebElement): ActionSequence; + dragAndDrop(element: webdriver.WebElement, location: ILocation): ActionSequence; + + /** + * Clicks a mouse button. + * + *

If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

sequence.mouseMove(element).click()
+ * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + click(opt_elementOrButton?: webdriver.WebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: number): ActionSequence; + + /** + * Double-clicks a mouse button. + * + *

If an element is provided, the mouse will first be moved to the center of + * that element. This is equivalent to: + *

sequence.mouseMove(element).doubleClick()
+ * + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: webdriver.WebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: number): ActionSequence; + + /** + * Performs a modifier key press. The modifier key is not released + * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be + * targetted at the currently focused element. + * @param {!webdriver.Key} key The modifier key to push. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyDown(key: string): ActionSequence; + + /** + * Performs a modifier key release. The release is targetted at the currently + * focused element. + * @param {!webdriver.Key} key The modifier key to release. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyUp(key: string): ActionSequence; + + /** + * Simulates typing multiple keys. Each modifier key encountered in the + * sequence will not be released until it is encountered again. All key events + * will be targetted at the currently focused element. + * @param {...(string|!webdriver.Key|!Array.<(string|!webdriver.Key)>)} var_args + * The keys to type. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + sendKeys(...var_args: any[]): ActionSequence; + + //endregion + } + + /** + * Represents a modal dialog such as {@code alert}, {@code confirm}, or + * {@code prompt}. Provides functions to retrieve the message displayed with + * the alert, accept or dismiss the alert, and set the response text (in the + * case of {@code prompt}). + * @extends {webdriver.promise.Deferred} + */ + class Alert extends webdriver.promise.Deferred { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!(string|webdriver.promise.Promise)} text Either the message text + * displayed with this alert, or a promise that will be resolved to said + * text. + * @constructor + */ + constructor(driver: webdriver.WebDriver, text: string); + constructor(driver: webdriver.WebDriver, text: webdriver.promise.Promise); + + //endregion + + //region Methods + + /** + * Retrieves the message text displayed with this alert. For instance, if the + * alert were opened with alert("hello"), then this would return "hello". + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * text displayed with this alert. + */ + getText(): webdriver.promise.Promise; + + /** + * Accepts this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + accept(): webdriver.promise.Promise; + + /** + * Dismisses this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + dismiss(): webdriver.promise.Promise; + + /** + * Sets the response text on this alert. This command will return an error if + * the underlying alert does not support response text (e.g. window.alert and + * window.confirm). + * @param {string} text The text to set. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + sendKeys(text: string): webdriver.promise.Promise; + + //endregion + + } + + /** + * An error returned to indicate that there is an unhandled modal dialog on the + * current page. + * @extends {bot.Error} + */ + class UnhandledAlertError extends webdriver.error.Error { + //region Constructors + + /** + * @param {string} message The error message. + * @param {!webdriver.Alert} alert The alert handle. + * @constructor + */ + constructor(message: string, alert: webdriver.Alert); + + //endregion + + //region Methods + + /** + * @return {!webdriver.Alert} The open alert. + */ + getAlert(): webdriver.Alert; + + //endregion + } + + /** + * Recognized browser names. + * @enum {string} + */ + class Browser { + static ANDROID: string; + static CHROME: string; + static FIREFOX: string; + static INTERNET_EXPLORER: string; + static IPAD: string; + static IPHONE: string; + static OPERA: string; + static PHANTOM_JS: string; + static SAFARI: string; + static HTMLUNIT: string; + } + + /** + * @extends {webdriver.AbstractBuilder} + */ + class Builder extends AbstractBuilder { + + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Static Properties + + /** + * Environment variable that defines the session ID of an existing WebDriver + * session to use when creating clients. If set, all new Builder instances will + * default to creating clients that use this session. To create a new session, + * use {@code #useExistingSession(boolean)}. The use of this environment + * variable requires that {@link webdriver.AbstractBuilder.SERVER_URL_ENV} also + * be set. + * @type {string} + * @const + * @see webdriver.process.getEnv + */ + static SESSION_ID_ENV: string; + + //endregion + + //region Methods + + /** + * Configures the builder to create a client that will use an existing WebDriver + * session. + * @param {string} id The existing session ID to use. + * @return {!webdriver.AbstractBuilder} This Builder instance for chain calling. + */ + usingSession(id: string): webdriver.AbstractBuilder; + + /** + * @return {string} The ID of the session, if any, this builder is configured + * to reuse. + */ + getSession(): string; + + /** + * @override + */ + build(): webdriver.WebDriver; + + //endregion + } + + /** + * Common webdriver capability keys. + * @enum {string} + */ + class Capability { + + /** + * Indicates whether a driver should accept all SSL certs by default. This + * capability only applies when requesting a new session. To query whether + * a driver can handle insecure SSL certs, see + * {@link webdriver.Capability.SECURE_SSL}. + */ + static ACCEPT_SSL_CERTS: string; + + + /** + * The browser name. Common browser names are defined in the + * {@link webdriver.Browser} enum. + */ + static BROWSER_NAME: string; + + /** + * Whether the driver is capable of handling modal alerts (e.g. alert, + * confirm, prompt). To define how a driver should handle alerts, + * use {@link webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR}. + */ + static HANDLES_ALERTS: string; + + /** + * Key for the logging driver logging preferences. + */ + static LOGGING_PREFS: string; + + /** + * Describes the platform the browser is running on. Will be one of + * ANDROID, IOS, LINUX, MAC, UNIX, or WINDOWS. When requesting a + * session, ANY may be used to indicate no platform preference (this is + * semantically equivalent to omitting the platform capability). + */ + static PLATFORM: string; + + /** + * Describes the proxy configuration to use for a new WebDriver session. + */ + static PROXY: string; + + /** Whether the driver supports changing the brower's orientation. */ + static ROTATABLE: string; + + /** + * Whether a driver is only capable of handling secure SSL certs. To request + * that a driver accept insecure SSL certs by default, use + * {@link webdriver.Capability.ACCEPT_SSL_CERTS}. + */ + static SECURE_SSL: string; + + /** Whether the driver supports manipulating the app cache. */ + static SUPPORTS_APPLICATION_CACHE: string; + + /** + * Whether the driver supports controlling the browser's internet + * connectivity. + */ + static SUPPORTS_BROWSER_CONNECTION: string; + + /** Whether the driver supports locating elements with CSS selectors. */ + static SUPPORTS_CSS_SELECTORS: string; + + /** Whether the browser supports JavaScript. */ + static SUPPORTS_JAVASCRIPT: string; + + /** Whether the driver supports controlling the browser's location info. */ + static SUPPORTS_LOCATION_CONTEXT: string; + + /** Whether the driver supports taking screenshots. */ + static TAKES_SCREENSHOT: string; + + /** + * Defines how the driver should handle unexpected alerts. The value should + * be one of "accept", "dismiss", or "ignore. + */ + static UNEXPECTED_ALERT_BEHAVIOR: string; + + /** Defines the browser version. */ + static VERSION: string; + } + + class Capabilities { + //region Constructors + + /** + * @param {(webdriver.Capabilities|Object)=} opt_other Another set of + * capabilities to merge into this instance. + * @constructor + */ + constructor(opt_other?: Capabilities); + constructor(opt_other?: any); + + //endregion + + //region Methods + + /** @return {!Object} The JSON representation of this instance. */ + toJSON(): any; + + /** + * Merges another set of capabilities into this instance. Any duplicates in + * the provided set will override those already set on this instance. + * @param {!(webdriver.Capabilities|Object)} other The capabilities to + * merge into this instance. + * @return {!webdriver.Capabilities} A self reference. + */ + merge(other: Capabilities): Capabilities; + merge(other: any): Capabilities; + + /** + * @param {string} key The capability to set. + * @param {*} value The capability value. Capability values must be JSON + * serializable. Pass {@code null} to unset the capability. + * @return {!webdriver.Capabilities} A self reference. + */ + set(key: string, value: any): Capabilities; + + /** + * @param {string} key The capability to return. + * @return {*} The capability with the given key, or {@code null} if it has + * not been set. + */ + get(key: string): any; + + /** + * @param {string} key The capability to check. + * @return {boolean} Whether the specified capability is set. + */ + has(key: string): boolean; + + //endregion + + //region Static Methods + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Android. + */ + static android(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Chrome. + */ + static chrome(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. + */ + static firefox(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * Internet Explorer. + */ + static ie(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPad. + */ + static ipad(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPhone. + */ + static iphone(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Opera. + */ + static opera(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * PhantomJS. + */ + static phantomjs(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Safari. + */ + static safari(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit. + */ + static htmlunit(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit + * with enabled Javascript. + */ + static htmlunitwithjs(): Capabilities; + + //endregion + } + + /** + * An enumeration of valid command string. + * NOTE: A Class was used instead of an Enum so that the class could be extended in Protractor. + */ + class CommandName { + static GET_SERVER_STATUS: string; + + static NEW_SESSION: string; + static GET_SESSIONS: string; + static DESCRIBE_SESSION: string; + + static CLOSE: string; + static QUIT: string; + + static GET_CURRENT_URL: string; + static GET: string; + static GO_BACK: string; + static GO_FORWARD: string; + static REFRESH: string; + + static ADD_COOKIE: string; + static GET_COOKIE: string; + static GET_ALL_COOKIES: string; + static DELETE_COOKIE: string; + static DELETE_ALL_COOKIES: string; + + static GET_ACTIVE_ELEMENT: string; + static FIND_ELEMENT: string; + static FIND_ELEMENTS: string; + static FIND_CHILD_ELEMENT: string; + static FIND_CHILD_ELEMENTS: string; + + static CLEAR_ELEMENT: string; + static CLICK_ELEMENT: string; + static SEND_KEYS_TO_ELEMENT: string; + static SUBMIT_ELEMENT: string; + + static GET_CURRENT_WINDOW_HANDLE: string; + static GET_WINDOW_HANDLES: string; + static GET_WINDOW_POSITION: string; + static SET_WINDOW_POSITION: string; + static GET_WINDOW_SIZE: string; + static SET_WINDOW_SIZE: string; + static MAXIMIZE_WINDOW: string; + + static SWITCH_TO_WINDOW: string; + static SWITCH_TO_FRAME: string; + static GET_PAGE_SOURCE: string; + static GET_TITLE: string; + + static EXECUTE_SCRIPT: string; + static EXECUTE_ASYNC_SCRIPT: string; + + static GET_ELEMENT_TEXT: string; + static GET_ELEMENT_TAG_NAME: string; + static IS_ELEMENT_SELECTED: string; + static IS_ELEMENT_ENABLED: string; + static IS_ELEMENT_DISPLAYED: string; + static GET_ELEMENT_LOCATION: string; + static GET_ELEMENT_LOCATION_IN_VIEW: string; + static GET_ELEMENT_SIZE: string; + static GET_ELEMENT_ATTRIBUTE: string; + static GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + static ELEMENT_EQUALS: string; + + static SCREENSHOT: string; + static IMPLICITLY_WAIT: string; + static SET_SCRIPT_TIMEOUT: string; + static SET_TIMEOUT: string; + + static ACCEPT_ALERT: string; + static DISMISS_ALERT: string; + static GET_ALERT_TEXT: string; + static SET_ALERT_TEXT: string; + + static EXECUTE_SQL: string; + static GET_LOCATION: string; + static SET_LOCATION: string; + static GET_APP_CACHE: string; + static GET_APP_CACHE_STATUS: string; + static CLEAR_APP_CACHE: string; + static IS_BROWSER_ONLINE: string; + static SET_BROWSER_ONLINE: string; + + static GET_LOCAL_STORAGE_ITEM: string; + static GET_LOCAL_STORAGE_KEYS: string; + static SET_LOCAL_STORAGE_ITEM: string; + static REMOVE_LOCAL_STORAGE_ITEM: string; + static CLEAR_LOCAL_STORAGE: string; + static GET_LOCAL_STORAGE_SIZE: string; + + static GET_SESSION_STORAGE_ITEM: string; + static GET_SESSION_STORAGE_KEYS: string; + static SET_SESSION_STORAGE_ITEM: string; + static REMOVE_SESSION_STORAGE_ITEM: string; + static CLEAR_SESSION_STORAGE: string; + static GET_SESSION_STORAGE_SIZE: string; + + static SET_SCREEN_ORIENTATION: string; + static GET_SCREEN_ORIENTATION: string; + + // These belong to the Advanced user interactions - an element is + // optional for these commands. + static CLICK: string; + static DOUBLE_CLICK: string; + static MOUSE_DOWN: string; + static MOUSE_UP: string; + static MOVE_TO: string; + static SEND_KEYS_TO_ACTIVE_ELEMENT: string; + + // These belong to the Advanced Touch API + static TOUCH_SINGLE_TAP: string; + static TOUCH_DOWN: string; + static TOUCH_UP: string; + static TOUCH_MOVE: string; + static TOUCH_SCROLL: string; + static TOUCH_DOUBLE_TAP: string; + static TOUCH_LONG_PRESS: string; + static TOUCH_FLICK: string; + + static GET_AVAILABLE_LOG_TYPES: string; + static GET_LOG: string; + static GET_SESSION_LOGS: string; + } + + /** + * Describes a command to be executed by the WebDriverJS framework. + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + class Command { + //region Constructors + + /** + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + constructor(name: string); + + //endregion + + //region Methods + + /** + * @return {!webdriver.CommandName} This command's name. + */ + getName(): string; + + /** + * Sets a parameter to send with this command. + * @param {string} name The parameter name. + * @param {*} value The parameter value. + * @return {!webdriver.Command} A self reference. + */ + setParameter(name: string, value: any): webdriver.Command; + + /** + * Sets the parameters for this command. + * @param {!Object.<*>} parameters The command parameters. + * @return {!webdriver.Command} A self reference. + */ + setParameters(parameters: any): webdriver.Command; + + /** + * Returns a named command parameter. + * @param {string} key The parameter key to look up. + * @return {*} The parameter value, or undefined if it has not been set. + */ + getParameter(key: string): any; + + /** + * @return {!Object.<*>} The parameters to send with this command. + */ + getParameters(): any; + + //endregion + } + + /** + * Handles the execution of {@code webdriver.Command} objects. + */ + interface CommandExecutor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * {@link bot.response.ResponseObject} object. + * @param {!webdriver.Command} command The command to execute. + * @param {function(Error, !bot.response.ResponseObject=)} callback the function + * to invoke when the command response is ready. + */ + execute(command: webdriver.Command, callback: (error: Error, responseObject: any) => any ): void; + } + + /** + * Object that can emit events for others to listen for. This is used instead + * of Closure's event system because it is much more light weight. The API is + * based on Node's EventEmitters. + */ + class EventEmitter { + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Fires an event and calls all listeners. + * @param {string} type The type of event to emit. + * @param {...*} var_args Any arguments to pass to each listener. + */ + emit(type: string, ...var_args: any[]): void; + + /** + * Returns a mutable list of listeners for a specific type of event. + * @param {string} type The type of event to retrieve the listeners for. + * @return {!Array.<{fn: !Function, oneshot: boolean, + * scope: (Object|undefined)}>} The registered listeners for + * the given event type. + */ + listeners(type: string): Array<{fn: any; oneshot: boolean; scope: any;}>; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + addListener(type: string, listenerFn: any, opt_scope?:any): EventEmitter; + + /** + * Registers a one-time listener which will be called only the first time an + * event is emitted, after which it will be removed. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + on(type: string, listenerFn: any, opt_scope?:any): EventEmitter; + + /** + * Removes a previously registered event listener. + * @param {string} type The type of event to unregister. + * @param {!Function} listenerFn The handler function to remove. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeListener(type: string, listenerFn: any): EventEmitter; + + /** + * Removes all listeners for a specific type of event. If no event is + * specified, all listeners across all types will be removed. + * @param {string=} opt_type The type of event to remove listeners from. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeAllListeners(opt_type?: string): EventEmitter; + + //endregion + } + + /** + * @implements {webdriver.CommandExecutor} + */ + class FirefoxDomExecutor implements webdriver.CommandExecutor { + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Static Methods + + /** + * @return {boolean} Whether the current environment supports the + * FirefoxDomExecutor. + */ + static isAvailable(): boolean; + + //endretion + + //region Methods + + /** @override */ + execute(command: webdriver.Command, callback: (error: Error, responseObject: any) => any ): void; + + //endregion + } + + /** + * Interface for navigating back and forth in the browser history. + */ + class WebDriverNavigation { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Schedules a command to navigate to a new URL. + * @param {string} url The URL to navigate to. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * URL has been loaded. + */ + to(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to move backwards in the browser history. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * navigation event has completed. + */ + back(): webdriver.promise.Promise; + + /** + * Schedules a command to move forwards in the browser history. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * navigation event has completed. + */ + forward(): webdriver.promise.Promise; + + /** + * Schedules a command to refresh the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * navigation event has completed. + */ + refresh(): webdriver.promise.Promise; + + //endregion + } + + /** + * Provides methods for managing browser and driver state. + */ + class WebDriverOptions { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Schedules a command to add a cookie. + * @param {string} name The cookie name. + * @param {string} value The cookie value. + * @param {string=} opt_path The cookie path. + * @param {string=} opt_domain The cookie domain. + * @param {boolean=} opt_isSecure Whether the cookie is secure. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as + * a number, should be in milliseconds since midnight, January 1, 1970 UTC. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been added to the page. + */ + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + + /** + * Schedules a command to delete all cookies visible to the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * cookies have been deleted. + */ + deleteAllCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to delete the cookie with the given name. This command is + * a no-op if there is no cookie with the given name visible to the current + * page. + * @param {string} name The name of the cookie to delete. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been deleted. + */ + deleteCookie(name: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve all cookies visible to the current page. + * Each cookie will be returned as a JSON object as described by the WebDriver + * wire protocol. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * cookies visible to the current page. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the cookie with the given name. Returns null + * if there is no such cookie. The cookie will be returned as a JSON object as + * described by the WebDriver wire protocol. + * @param {string} name The name of the cookie to retrieve. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * named cookie, or {@code null} if there is no such cookie. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookie(name: string): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Logs} The interface for managing driver + * logs. + */ + logs(): webdriver.WebDriverLogs; + + /** + * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): webdriver.WebDriverTimeouts; + + /** + * @return {!webdriver.WebDriver.Window} The interface for managing the + * current window. + */ + window(): webdriver.WebDriverWindow; + + //endregion + } + + /** + * An interface for managing timeout behavior for WebDriver instances. + */ + class WebDriverTimeouts { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Specifies the amount of time the driver should wait when searching for an + * element if it is not immediately present. + *

+ * When searching for a single element, the driver should poll the page + * until the element has been found, or this timeout expires before failing + * with a {@code bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching + * for multiple elements, the driver should poll the page until at least one + * element has been found or this timeout has expired. + *

+ * Setting the wait timeout to 0 (its default value), disables implicit + * waiting. + *

+ * Increasing the implicit wait timeout should be used judiciously as it + * will have an adverse effect on test run time, especially when used with + * slower location strategies like XPath. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * implicit wait timeout has been set. + */ + implicitlyWait(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait, in milliseconds, for an asynchronous script + * to finish execution before returning an error. If the timeout is less than or + * equal to 0, the script will be allowed to run indefinitely. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * script timeout has been set. + */ + setScriptTimeout(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait for a page load to complete before returning + * an error. If the timeout is negative, page loads may be indefinite. + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the timeout has been set. + */ + pageLoadTimeout(ms: number): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for managing the current window. + */ + class WebDriverWindow { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Retrieves the window's current position, relative to the top left corner of + * the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's position in the form of a {x:number, y:number} object literal. + */ + getPosition(): webdriver.promise.Promise; + + /** + * Repositions the current window. + * @param {number} x The desired horizontal position, relative to the left side + * of the screen. + * @param {number} y The desired vertical position, relative to the top of the + * of the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setPosition(x: number, y: number): webdriver.promise.Promise; + + /** + * Retrieves the window's current size. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's size in the form of a {width:number, height:number} object + * literal. + */ + getSize(): webdriver.promise.Promise; + + /** + * Resizes the current window. + * @param {number} width The desired window width. + * @param {number} height The desired window height. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setSize(width: number, height: number): webdriver.promise.Promise; + + /** + * Maximizes the current window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + maximize(): webdriver.promise.Promise; + + //endregion + } + + /** + * Interface for managing WebDriver log records. + */ + class WebDriverLogs { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region + + /** + * Fetches available log entries for the given type. + * + *

Note that log buffers are reset after each call, meaning that + * available log entries correspond to those entries not yet returned for a + * given log type. In practice, this means that this call will return the + * available log entries since the last call, or from the start of the + * session. + * + * @param {!webdriver.logging.Type} type The desired log type. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of log entries for the specified + * type. + */ + get(type: string): webdriver.promise.Promise; + + /** + * Retrieves the log types available to this driver. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of available log types. + */ + getAvailableLogTypes(): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for changing the focus of the driver to another frame or window. + */ + class WebDriverTargetLocator { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Schedules a command retrieve the {@code document.activeElement} element on + * the current document, or {@code document.body} if activeElement is not + * available. + * @return {!webdriver.WebElement} The active element. + */ + activeElement(): webdriver.WebElement; + + /** + * Schedules a command to switch focus of all future commands to the first frame + * on the page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the default content. + */ + defaultContent(): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * frame on the page. + *

+ * If the frame is specified by a number, the command will switch to the frame + * by its (zero-based) index into the {@code window.frames} collection. + *

+ * If the frame is specified by a string, the command will select the frame by + * its name or ID. To select sub-frames, simply separate the frame names/IDs by + * dots. As an example, "main.child" will select the frame with the name "main" + * and then its child "child". + *

+ * If the specified frame can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. + * @param {string|number} nameOrIndex The frame locator. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified frame. + */ + frame(nameOrIndex: string): webdriver.promise.Promise; + frame(nameOrIndex: number): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * window. Windows may be specified by their {@code window.name} attribute or + * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). + *

+ * If the specificed window can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified window. + */ + window(nameOrHandle: string): webdriver.promise.Promise; + + /** + * Schedules a command to change focus to the active alert dialog. This command + * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal + * dialog is not currently open. + * @return {!webdriver.Alert} The open alert. + */ + alert(): webdriver.Alert; + + //endregion + } + + /** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code webdriver.promise.Promise} that + * represents the result of that command. Callbacks may be registered on this + * object to manipulate the command result or catch an expected error. Any + * commands scheduled with a callback are considered sub-commands and will + * execute before the next command in the current frame. For example: + * + * var message = []; + * driver.call(message.push, message, 'a').then(function() { + * driver.call(message.push, message, 'b'); + * }); + * driver.call(message.push, message, 'c'); + * driver.call(function() { + * alert('message is abc? ' + (message.join('') == 'abc')); + * }); + * + */ + class WebDriver { + //region Constructors + + /** + * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!webdriver.CommandExecutor} executor The executor to use when + * sending commands to the browser. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(session: webdriver.Session, executor: webdriver.CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: webdriver.promise.Promise, executor: webdriver.CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region Static Properties + + static Navigation: WebDriverNavigation; + static Options: WebDriverOptions; + static Timeouts: WebDriverTimeouts; + static Window: WebDriverWindow; + static Logs: WebDriverLogs; + static TargetLocator: WebDriverTargetLocator; + + //endregion + + //region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!webdriver.CommandExecutor} executor Command executor to use when + * querying for session details. + * @param {string} sessionId ID of the session to attach to. + * @return {!webdriver.WebDriver} A new client for the specified session. + */ + static attachToSession(executor: webdriver.CommandExecutor, sessionId: string): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!webdriver.CommandExecutor} executor The executor to create the new + * session with. + * @param {!webdriver.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @return {!webdriver.WebDriver} The driver for the newly created session. + */ + static createSession(executor: webdriver.CommandExecutor, desiredCapabilities: webdriver.Capabilities): WebDriver; + + //endregion + + //region Methods + + /** + * @return {!webdriver.promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): webdriver.promise.ControlFlow; + + /** + * Schedules a {@code webdriver.Command} to be executed by this driver's + * {@code webdriver.CommandExecutor}. + * @param {!webdriver.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the command result. + */ + schedule(command: webdriver.Command, description: string): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise} A promise for this client's session. + */ + getSession(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise} A promise that will resolve with the + * this instance's capabilities. + */ + getCapabilities(): webdriver.promise.Promise; + + /** + * Schedules a command to quit the current session. After calling quit, this + * instance will be invalidated and may no longer be used to issue commands + * against the browser. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the command has completed. + */ + quit(): webdriver.promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * called. Example: + *


+         *   driver.actions().
+         *       mouseDown(element1).
+         *       mouseMove(element2).
+         *       mouseUp().
+         *       perform();
+         * 
+ * @return {!webdriver.ActionSequence} A new action sequence for this instance. + */ + actions(): webdriver.ActionSequence; + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * The script may refer to any variables accessible from the current window. + * Furthermore, the script will execute in the window's context, thus + * {@code document} may be used to refer to the current document. Any local + * variables will not be available once the script has finished executing, + * though global variables will persist. + * + * If the script has a return value (i.e. if the script contains a return + * statement), then the following steps will be taken for resolving this + * functions return value: + *
    + *
  • For a HTML element, the value will resolve to a + * {@code webdriver.WebElement}
  • + *
  • Null and undefined return values will resolve to null
  • + *
  • Booleans, numbers, and strings will resolve as is
  • + *
  • Functions will resolve to their string representation
  • + *
  • For arrays and objects, each member item will be converted according to + * the rules above
  • + *
+ * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute asynchronous JavaScript in the context of the + * currently selected frame or window. The script fragment will be executed as + * the body of an anonymous function. If the script is provided as a function + * object, that function will be converted to a string for injection into the + * target window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * Unlike executing synchronous JavaScript with + * {@code webdriver.WebDriver.prototype.executeScript}, scripts executed with + * this function must explicitly signal they are finished by invoking the + * provided callback. This callback will always be injected into the + * executed function as the last argument, and thus may be referenced with + * {@code arguments[arguments.length - 1]}. The following steps will be taken + * for resolving this functions return value against the first argument to the + * script's callback function: + *
    + *
  • For a HTML element, the value will resolve to a + * {@code webdriver.WebElement}
  • + *
  • Null and undefined return values will resolve to null
  • + *
  • Booleans, numbers, and strings will resolve as is
  • + *
  • Functions will resolve to their string representation
  • + *
  • For arrays and objects, each member item will be converted according to + * the rules above
  • + *
+ * + * Example #1: Performing a sleep that is synchronized with the currently + * selected window: + *
+         * var start = new Date().getTime();
+         * driver.executeAsyncScript(
+         *     'window.setTimeout(arguments[arguments.length - 1], 500);').
+         *     then(function() {
+         *       console.log('Elapsed time: ' + (new Date().getTime() - start) + ' ms');
+         *     });
+         * 
+ * + * Example #2: Synchronizing a test with an AJAX application: + *
+         * var button = driver.findElement(By.id('compose-button'));
+         * button.click();
+         * driver.executeAsyncScript(
+         *     'var callback = arguments[arguments.length - 1];' +
+         *     'mailClient.getComposeWindowWidget().onload(callback);');
+         * driver.switchTo().frame('composeWidget');
+         * driver.findElement(By.id('to')).sendKEys('dog@example.com');
+         * 
+ * + * Example #3: Injecting a XMLHttpRequest and waiting for the result. In this + * example, the inject script is specified with a function literal. When using + * this format, the function is converted to a string for injection, so it + * should not reference any symbols not defined in the scope of the page under + * test. + *
+         * driver.executeAsyncScript(function() {
+         *   var callback = arguments[arguments.length - 1];
+         *   var xhr = new XMLHttpRequest();
+         *   xhr.open("GET", "/resource/data.json", true);
+         *   xhr.onreadystatechange = function() {
+         *     if (xhr.readyState == 4) {
+         *       callback(xhr.resposneText);
+         *     }
+         *   }
+         *   xhr.send('');
+         * }).then(function(str) {
+         *   console.log(JSON.parse(str)['food']);
+         * });
+         * 
+ * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + executeAsyncScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeAsyncScript(script: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {!Function} fn The function to execute. + * @param {Object=} opt_scope The object in whose scope to execute the function. + * @param {...*} var_args Any arguments to pass to the function. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * function's result. + */ + call(fn: any, opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to wait for a condition to hold, as defined by some + * user supplied function. If any errors occur while evaluating the wait, they + * will be allowed to propagate. + * @param {function():boolean|!webdriver.promise.Promise} fn The function to + * evaluate as a wait condition. + * @param {number} timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * wait condition has been satisfied. + */ + wait(fn: () => any, timeout: number, opt_message?: string): webdriver.promise.Promise; + + /** + * Schedules a command to make the driver sleep for the given amount of time. + * @param {number} ms The amount of time, in milliseconds, to sleep. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * sleep has finished. + */ + sleep(ms: number): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current window handle. + */ + getWindowHandle(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!webdriver.promise.Promise} A promise that will be resolved with an + * array of window handles. + */ + getAllWindowHandles(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's source. The page source + * returned is a representation of the underlying DOM: do not expect it to be + * formatted or escaped in the same way as the response sent from the web + * server. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current page source. + */ + getPageSource(): webdriver.promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + close(): webdriver.promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * document has finished loading. + */ + get(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current URL. + */ + getCurrentUrl(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current page's title. + */ + getTitle(): webdriver.promise.Promise; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two statements + * are equivalent: + *

+         * var e1 = driver.findElement(By.id('foo'));
+         * var e2 = driver.findElement({id:'foo'});
+         * 
+ * + *

When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): webdriver.WebElement; + findElement(locatorOrElement: any, ...var_args: any[]): webdriver.WebElement; + + /** + * Schedules a command to test if an element is present on the page. + * + *

If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will resolve to whether + * the element is present on the page. + */ + isElementPresent(locatorOrElement: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + *

    + *
  1. Entire page + *
  2. Current window + *
  3. Visible portion of the current frame + *
  4. The screenshot of the entire display containing the browser + *
+ * + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Options} The options interface for this + * instance. + */ + manage(): webdriver.WebDriverOptions; + + /** + * @return {!webdriver.WebDriver.Navigation} The navigation interface for this + * instance. + */ + navigate(): webdriver.WebDriverNavigation; + + /** + * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): webdriver.WebDriverTargetLocator + + //endregion + } + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code webdriver.WebDriver} instance, or by searching + * under another {@code webdriver.WebElement}: + * + * driver.get('http://www.google.com'); + * var searchForm = driver.findElement(By.tagName('form')); + * var searchBox = searchForm.findElement(By.name('q')); + * searchBox.sendKeys('webdriver'); + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + * + * driver.findElement(By.id('not-there')).then(function(element) { + * alert('Found an element that was not expected to be there!'); + * }, function(error) { + * alert('The element was not found, as expected'); + * }); + * + * @extends {webdriver.promise.Deferred} + */ + class WebElement extends webdriver.promise.Deferred { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!(string|webdriver.promise.Promise)} id Either the opaque ID for the + * underlying DOM element assigned by the server, or a promise that will + * resolve to that ID or another WebElement. + * @constructor + */ + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise); + constructor(driver: webdriver.WebDriver, id: string); + + //endregion + + //region Static Properties + + /** + * The property key used in the wire protocol to indicate that a JSON object + * contains the ID of a WebElement. + * @type {string} + * @const + */ + static ELEMENT_KEY: string; + + //endregion + + //region Methods + + /** + * @return {!webdriver.WebDriver} The parent driver for this instance. + */ + getDriver(): webdriver.WebDriver; + + /** + * @return {!webdriver.promise.Promise} A promise that resolves to this + * element's JSON representation as defined by the WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + toWireValue(): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): WebElement; + findElement(locator: any, ...var_args: any[]): WebElement; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + *

Note that JS locator searches cannot be restricted to a subtree of the + * DOM. All such searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether an element could be located on the page. + */ + isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that match + * the given search criteria. + *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the elements. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with an + * array of located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + //endregion + + //region Static Methods + + /** + * Compares to WebElements for equality. + * @param {!webdriver.WebElement} a A WebElement. + * @param {!webdriver.WebElement} b A WebElement. + * @return {!webdriver.promise.Promise} A promise that will be resolved to + * whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + + //endregion + } + + interface ILocatorStrategy { + className(value: string): Locator; + 'class name'(value: string): Locator; + css(value: string): Locator; + id(value: string): Locator; + js(value: string): Locator; + linkText(value: string): Locator; + 'link text'(value: string): Locator; + name(value: string): Locator; + partialLinkText(value: string): Locator; + 'partial link text'(value: string): Locator; + tagName(value: string): Locator; + 'tag name'(value: string): Locator; + xpath(value: string): Locator; + } + + var By: ILocatorStrategy; + + /** + * An element locator. + */ + class Locator { + + //region Constructors + + /** + * An element locator. + * @param {string} using The type of strategy to use for this locator. + * @param {string} value The search target of this locator. + * @constructor + */ + constructor(using: string, value: string); + + //endregion + + //region Properties + + /** + * The search strategy to use when searching for an element. + * @type {string} + */ + using: string; + + /** + * The search target for this locator. + * @type {string} + */ + value: string; + + //endregion + + //region Static Properties + + /** + * Factory methods for the supported locator strategies. + * @type {Object.} + */ + static Strategy: ILocatorStrategy; + + //endregion + + //region Methods + + /** @return {string} String representation of this locator. */ + toString(): string; + + //endregion + + //region Static Methods + + /** + * Creates a new Locator from an object whose only property is also a key in + * the {@code webdriver.Locator.Strategy} map. + * @param {Object.} obj The object to convert into a locator. + * @return {webdriver.Locator} The new locator object. + */ + static createFromObj(obj: any): Locator + + /** + * Verifies that a {@code locator} is a valid locator to use for searching for + * elements on the page. + * @param {webdriver.Locator|Object.} locator The locator + * to verify, or a short-hand object that can be converted into a locator + * to verify. + * @return {!webdriver.Locator} The validated locator. + */ + static checkLocator(locator: Locator): Locator; + static checkLocator(obj: any): Locator; + + //endregion + } + + /** + * Contains information about a WebDriver session. + */ + class Session { + + //region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|webdriver.Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: webdriver.Capabilities); + constructor(id: string, capabilities: any); + + //endregion + + //region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!webdriver.Capabilities} This session's capabilities. + */ + getCapabilities(): webdriver.Capabilities; + + /** + * Retrieves the value of a specific capability. + * @param {string} key The capability to retrieve. + * @return {*} The capability value. + */ + getCapability(key: string): any; + + /** + * Returns the JSON representation of this object, which is just the string + * session ID. + * @return {string} The JSON representation of this Session. + */ + toJSON(): string; + + //endregion + } +} + +declare module 'selenium-webdriver' { + export = webdriver; +} \ No newline at end of file diff --git a/semver/semver-tests.ts b/semver/semver-tests.ts new file mode 100644 index 0000000000..009a47daf2 --- /dev/null +++ b/semver/semver-tests.ts @@ -0,0 +1,92 @@ +/// + +var obj:Object; +var bool:boolean; +var num:number; +var str:string; +var x:any = null; +var arr:any[]; +var exp:RegExp; +var strArr:string[]; +var numArr:string[]; + +var mod:typeof SemverModule; + +var v1:string, v2:string; +var version:string; +var versions:string[]; +var loose:boolean; + +str = mod.valid(str); + +str = mod.valid(str, loose); +//TODO maybe add an enum for release? +str = mod.inc(str, str, loose); + +//Comparison +bool = mod.gt(v1, v2, loose); +bool = mod.gte(v1, v2, loose); +bool = mod.lt(v1, v2, loose); +bool = mod.lte(v1, v2, loose); +bool = mod.eq(v1, v2, loose); +bool = mod.neq(v1, v2, loose); +bool = mod.cmp(v1, x, v2, loose); +num = mod.compare(v1, v2, loose); +num = mod.rcompare(v1, v2, loose); + +//Ranges +str = mod.validRange(str, loose); +str = mod.satisfies(version, str, loose); +str = mod.maxSatisfying(versions, str, loose); +bool = mod.gtr(version, str, loose); +bool = mod.ltr(version, str, loose); +bool = mod.outside(version, str, str, loose); + +var ver = new mod.Semver(str, bool); +str = ver.raw; +bool = ver.loose; +str = ver.format(); +str = ver.inspect(); +str = ver.toString(); + +num = ver.major; +num = ver.minor; +num = ver.patch; +str = ver.version; +strArr = ver.build; +strArr = ver.prerelease; + +num = ver.compare(ver); +num = ver.compareMain(ver); +num = ver.comparePre(ver); +ver = ver.inc(str); + + +var comp = new SemverModule.Comparator(str, bool); +str = comp.raw; +bool = comp.loose; +str = comp.format(); +str = comp.inspect(); +str = comp.toString(); + +ver = comp.semver; +str = comp.operator; +bool = comp.value; +comp.parse(str); +bool = comp.test(ver); + + +var range = new SemverModule.Range(str, bool); +str = range.raw; +bool = range.loose; +str = range.format(); +str = range.inspect(); +str = range.toString(); + +bool = range.test(ver); + +var sets:SemverModule.Comparator[][]; +sets = range.set(); + +var lims:SemverModule.Comparator[]; +lims = range.parseRange(str); diff --git a/semver/semver.d.ts b/semver/semver.d.ts new file mode 100644 index 0000000000..67f536af5c --- /dev/null +++ b/semver/semver.d.ts @@ -0,0 +1,75 @@ +// Type definitions for semver v2.2.1 +// Project: https://github.com/isaacs/node-semver +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module SemverModule { + + function valid(v:string, loose?:boolean):string; // Return the parsed version, or null if it's not valid. + //TODO maybe add an enum for release? + function inc(v:string, release:string, loose?:boolean):string; // Return the version incremented by the release type (major, minor, patch, or prerelease), or null if it's not valid. + + //Comparison + function gt(v1:string, v2:string, loose?:boolean):boolean; // v1 > v2 + function gte(v1:string, v2:string, loose?:boolean):boolean; // v1 >= v2 + function lt(v1:string, v2:string, loose?:boolean):boolean; // v1 < v2 + function lte(v1:string, v2:string, loose?:boolean):boolean; // v1 <= v2 + function eq(v1:string, v2:string, loose?:boolean):boolean; // v1 == v2 This is true if they're logically equivalent, even if they're not the exact same string. You already know how to compare strings. + function neq(v1:string, v2:string, loose?:boolean):boolean; // v1 != v2 The opposite of eq. + function cmp(v1:string, comparator:any, v2:string, loose?:boolean):boolean; // Pass in a comparison string, and it'll call the corresponding function above. "===" and "!==" do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. + function compare(v1:string, v2:string, loose?:boolean):number; // Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if v2 is greater. Sorts in ascending order if passed to Array.sort(). + function rcompare(v1:string, v2:string, loose?:boolean):number; // The reverse of compare. Sorts an array of versions in descending order when passed to Array.sort(). + + //Ranges + function validRange(range:string, loose?:boolean):string; // Return the valid range or null if it's not valid + function satisfies(version:string, range:string, loose?:boolean):string; // Return true if the version satisfies the range. + function maxSatisfying(versions:string[], range:string, loose?:boolean):string; // Return the highest version in the list that satisfies the range, or null if none of them do. + function gtr(version:string, range:string, loose?:boolean):boolean; // Return true if version is greater than all the versions possible in the range. + function ltr(version:string, range:string, loose?:boolean):boolean; // Return true if version is less than all the versions possible in the range. + function outside(version:string, range:string, hilo:string, loose?:boolean):boolean; // Return true if the version is outside the bounds of the range in either the high or low direction. The hilo argument must be either the string '>' or '<'. (This is the function called by gtr and ltr.) + + class SemverBase { + raw:string; + loose:boolean; + format():string; + inspect():string; + toString():string; + } + + class Semver extends SemverBase { + constructor(version:string, loose?:boolean); + + major:number; + minor:number; + patch:number; + version:string; + build:string[]; + prerelease:string[]; + + compare(other:Semver):number; + compareMain(other:Semver):number; + comparePre(other:Semver):number; + inc(release:string):Semver; + } + + class Comparator extends SemverBase { + constructor(comp:string, loose?:boolean); + + semver:Semver; + operator:string; + value:boolean; + parse(comp:string) :void; + test(version:Semver):boolean; + } + + class Range extends SemverBase { + constructor(range:string, loose?:boolean); + + set():Comparator[][]; + parseRange(range:string):Comparator[]; + test(version:Semver):boolean; + } +} +declare module "semver" { +export = SemverModule; +} diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 9f872afafc..b0417fd33b 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -1,6 +1,6 @@ -// Type definitions for sptypescript +// Type definitions for sptypescript // Project: http://sptypescript.codeplex.com -// Definitions by: Stanislav Vyshchepan and Andrey Markeev +// Definitions by: Stanislav Vyshchepan , Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/should/should-tests.ts b/should/should-tests.ts index c390aa323c..e88c6f1447 100644 --- a/should/should-tests.ts +++ b/should/should-tests.ts @@ -41,7 +41,7 @@ should.not.exist({}); user.should.have.property('pets').with.lengthOf(4); user.pets.should.have.lengthOf(4); -user.should.be.a('object').and.have.property('name', 'tj'); +user.should.be.of.type('object').and.have.property('name', 'tj'); 'foo'.should.equal('bar'); @@ -89,8 +89,8 @@ args.should.be.arguments; user.age.should.be.within(5, 50); -user.should.be.a('object'); -'test'.should.be.a('string'); +user.should.be.of.type('object'); +'test'.should.be.of.type('string'); user.should.be.an.instanceof(User); ['a'].should.be.an.instanceOf(Array); diff --git a/should/should.d.ts b/should/should.d.ts index 7241c0389b..b3c37846a2 100644 --- a/should/should.d.ts +++ b/should/should.d.ts @@ -1,6 +1,6 @@ -// Type definitions for should.js 1.2.2 +// Type definitions for should.js 3.1.2 // Project: https://github.com/visionmedia/should.js -// Definitions by: Alex Varju +// Definitions by: Alex Varju and Maxime LUCE (1.3+) // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Object { @@ -9,12 +9,13 @@ interface Object { interface ShouldAssertion { // basic grammar + a: ShouldAssertion; an: ShouldAssertion; - // a: ShouldAssertion; and: ShouldAssertion; be: ShouldAssertion; have: ShouldAssertion; with: ShouldAssertion; + of: ShouldAssertion; not: ShouldAssertion; // validators @@ -23,31 +24,58 @@ interface ShouldAssertion { ok: ShouldAssertion; true: ShouldAssertion; false: ShouldAssertion; + NaN: ShouldAssertion; + Infinity: ShouldAssertion; + Array: ShouldAssertion; + Object: ShouldAssertion; + String: ShouldAssertion; + Boolean: ShouldAssertion; + Number: ShouldAssertion; + Error: ShouldAssertion; + Function: ShouldAssertion; eql(expected: any, description?: string): ShouldAssertion; equal(expected: any, description?: string): ShouldAssertion; within(start: number, finish: number, description?: string): ShouldAssertion; approximately(value: number, delta: number, description?: string): ShouldAssertion; - a(expected: any, description?: string): ShouldAssertion; + type(expected: any, description?: string): ShouldAssertion; instanceof(constructor: Function, description?: string): ShouldAssertion; above(n: number, description?: string): ShouldAssertion; below(n: number, description?: string): ShouldAssertion; + match(other: {}, description?: string): ShouldAssertion; + match(other: (val: any) => any, description?: string): ShouldAssertion; match(regexp: RegExp, description?: string): ShouldAssertion; + match(other: any, description?: string): ShouldAssertion; + matchEach(other: {}, description?: string): ShouldAssertion; + matchEach(other: (val: any) => any, description?: string): ShouldAssertion; + matchEach(regexp: RegExp, description?: string): ShouldAssertion; + matchEach(other: any, description?: string): ShouldAssertion; length(n: number, description?: string): ShouldAssertion; property(name: string, description?: string): ShouldAssertion; property(name: string, val: any, description?: string): ShouldAssertion; + properties(names: string[]): ShouldAssertion; + properties(name: string): ShouldAssertion; + properties(descriptor: any): ShouldAssertion; + properties(...properties: string[]): ShouldAssertion; ownProperty(name: string, description?: string): ShouldAssertion; - include(obj: any, description?: string): ShouldAssertion; - includeEql(obj: any[], description?: string): ShouldAssertion; contain(obj: any): ShouldAssertion; + containEql(obj: any): ShouldAssertion; + containDeep(obj: any): ShouldAssertion; keys(...allKeys: string[]): ShouldAssertion; keys(allKeys: string[]): ShouldAssertion; header(field: string, val?: string): ShouldAssertion; status(code: number): ShouldAssertion; json: ShouldAssertion; html: ShouldAssertion; + startWith(expected: string, message?: any): ShouldAssertion; + endWith(expected: string, message?: any): ShouldAssertion; throw(message?: any): ShouldAssertion; + // deprecated + include(obj: any, description?: string): ShouldAssertion; + includeEql(obj: any[], description?: string): ShouldAssertion; + // aliases + exactly(expected: any, description?: string): ShouldAssertion; instanceOf(constructor: Function, description?: string): ShouldAssertion; throwError(message?: any): ShouldAssertion; lengthOf(n: number, description?: string): ShouldAssertion; @@ -65,6 +93,8 @@ interface ShouldInternal { } interface Internal extends ShouldInternal { + (obj: any): ShouldAssertion; + // node.js's assert functions fail(actual: any, expected: any, message: string, operator: string): void; assert(value: any, message: string): void; @@ -78,8 +108,11 @@ interface Internal extends ShouldInternal { throws(block: any, error?: any, message?: string): void; doesNotThrow(block: any, message?: string): void; ifError(value: any): void; + inspect(value: any, obj: any): any; } declare module "should" { export = Internal; } + +declare var should: Internal; diff --git a/siesta/siesta.d.ts b/siesta/siesta.d.ts index aaf6692bf3..f09f3f1274 100644 --- a/siesta/siesta.d.ts +++ b/siesta/siesta.d.ts @@ -1,3 +1,8 @@ +// Type definitions for Siesta +// Project: http://www.bryntum.com/products/siesta/ +// Definitions by: bquarmby +// Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module Siesta { /** * @abstract diff --git a/signalr/signalr-tests.ts b/signalr/signalr-tests.ts index 8a96bf9a12..3ef8cad875 100644 --- a/signalr/signalr-tests.ts +++ b/signalr/signalr-tests.ts @@ -60,7 +60,7 @@ interface MyHubConnection extends HubConnection { }; // My Hubs Server function: server: { - send(message: string); + send(message: string): any; }; } @@ -107,7 +107,7 @@ function test_hubs() { proxy.invoke('send', msg); proxy.invoke('send', msg, room); proxy.invoke('add', 1, 2) - .done(function (result) { + .done(function (result: any) { console.log('The result is ' + result); }); proxy.on('addMessage', function (msg?) { diff --git a/signalr/signalr-tests.ts.tscparams b/signalr/signalr-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/signalr/signalr-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/signalr/signalr.d.ts b/signalr/signalr.d.ts index 70b03c4ec8..6519f70518 100644 --- a/signalr/signalr.d.ts +++ b/signalr/signalr.d.ts @@ -1,13 +1,14 @@ // Type definitions for SignalR 1.0 // Project: http://www.asp.net/signalr // Definitions by: Boris Yankov +// Modified by: T. Michael Keesey // Definitions: https://github.com/borisyankov/DefinitelyTyped /// interface HubMethod { - (callback: (data: string) => void ); + (callback: (data: string) => void ): any; } interface SignalREvents { @@ -36,6 +37,7 @@ interface SignalR { logging: boolean; messageId: string; url: string; + qs: any; (url: string, queryString?: any, logging?: boolean): SignalR; hubConnection(url?: string): SignalR; @@ -74,8 +76,8 @@ interface HubProxy { hubName: string; init(connection: HubConnection, hubName: string): void; hasSubscriptions(): boolean; - on(eventName: string, callback: (...msg) => void ): HubProxy; - off(eventName: string, callback: (msg) => void ): HubProxy; + on(eventName: string, callback: (...msg: any[]) => void ): HubProxy; + off(eventName: string, callback: (msg: any) => void ): HubProxy; invoke(methodName: string, ...args: any[]): JQueryDeferred; } @@ -87,18 +89,18 @@ interface HubConnectionSettings { interface HubConnection extends SignalR { //(url?: string, queryString?: any, logging?: boolean): HubConnection; - proxies; - received(callback: (data: { Id; Method; Hub; State; Args; }) => void ): HubConnection; + proxies: any; + received(callback: (data: { Id: any; Method: any; Hub: any; State: any; Args: any; }) => void ): HubConnection; createHubProxy(hubName: string): HubProxy; } interface SignalRfn { - init(url, qs, logging); + init(url: any, qs: any, logging: any): any; } interface ConnectionSettings { - transport?; - callback?; + transport?: any; + callback?: any; waitForPageLoad?: boolean; jsonp?: boolean; } diff --git a/signalr/signalr.d.ts.tscparams b/signalr/signalr.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/signalr/signalr.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/sinon/sinon.d.ts b/sinon/sinon.d.ts index 7d207ef2ac..eb62a286e3 100644 --- a/sinon/sinon.d.ts +++ b/sinon/sinon.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Sinon 1.5 +// Type definitions for Sinon 1.8.1 // Project: http://sinonjs.org/ // Definitions by: William Sears // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped @@ -189,6 +189,19 @@ interface SinonStatic { clock: SinonFakeTimers; } +interface SinonFakeUploadProgress { + eventListeners: { + progress: any[]; + load: any[]; + abort: any[]; + error: any[]; + }; + + addEventListener(event: string, listener: (e: Event) => any): void; + removeEventListener(event: string, listener: (e: Event) => any): void; + dispatchEvent(event: Event): void; +} + interface SinonFakeXMLHttpRequest { // Properties onCreate: (xhr: SinonFakeXMLHttpRequest) => void; @@ -200,7 +213,9 @@ interface SinonFakeXMLHttpRequest { statusText: string; async: boolean; username: string; - password: string; + password: string; + withCredentials: boolean; + upload: SinonFakeUploadProgress; responseXML: Document; getResponseHeader(header: string): string; getAllResponseHeaders(): any; @@ -230,6 +245,7 @@ interface SinonFakeServer { autoRespondAfter: number; fakeHTTPMethods: boolean; getHTTPMethod: (request: SinonFakeXMLHttpRequest) => string; + requests: SinonFakeXMLHttpRequest[]; // Methods respondWith(body: string): void; @@ -378,15 +394,17 @@ interface SinonTestWrapper extends SinonSandbox { } interface SinonStatic { - config: SinonTestConfig; - test(fn: (...args: any[]) => any): SinonTestWrapper; - testCase(tests: any): any; + config: SinonTestConfig; + test(fn: (...args: any[]) => any): SinonTestWrapper; + testCase(tests: any): any; } // Utility overridables interface SinonStatic { + createStubInstance: (constructor: any) => SinonStub; format: (obj: any) => string; log: (message: string) => void; + restore(object: any): void; } declare var sinon: SinonStatic; diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index 481e6cb8dc..b7810f4671 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -1,3 +1,8 @@ +// Type definitions for SlickGrid 2.1.0 +// Project: https://github.com/mleibman/SlickGrid +// Definitions by: Josh Baldwin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /* SlickGrid-2.1.d.ts may be freely distributed under the MIT license. @@ -470,7 +475,7 @@ declare module Slick { /** * If set to true, whenever this column is resized, the entire table view will rerender. **/ - rerenderOnReize?: boolean; + rerenderOnResize?: boolean; /** * If false, column can no longer be resized. diff --git a/slickgrid/slick.headerbuttons.d.ts b/slickgrid/slick.headerbuttons.d.ts new file mode 100644 index 0000000000..ab160ea836 --- /dev/null +++ b/slickgrid/slick.headerbuttons.d.ts @@ -0,0 +1,41 @@ +// Type definitions for SlickGrid HeaderButtons Plugin 2.1.0 +// Project: https://github.com/mleibman/SlickGrid +// Definitions by: Derek Cicerone +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Slick { + + export interface Column { + header: Header; + } + + export interface Header { + buttons: HeaderButton[]; + } + + export interface HeaderButton { + command?: string; + cssClass?: string; + handler?: Function; + image?: string; + showOnHover?: boolean; + tooltip?: string; + } + + export interface OnCommandEventData { + grid: Grid; + column: Column; + command: string; + button: HeaderButton; + } + + export module Plugins { + + export class HeaderButtons extends Plugin { + constructor(); + public onCommand: Event>; + } + } +} diff --git a/socket.io-client/socket.io-client-tests.ts b/socket.io-client/socket.io-client-tests.ts new file mode 100644 index 0000000000..7b5f967473 --- /dev/null +++ b/socket.io-client/socket.io-client-tests.ts @@ -0,0 +1,10 @@ +import io = require('socket.io-client'); + +var socket = io.connect('http://localhost:80'); + +socket.on('connect', function () { + console.log('Connected!'); + socket.emit('event', 'some test data', function () { + console.log('Sent some data.'); + }); +}); diff --git a/socket.io-client/socket.io-client.d.ts b/socket.io-client/socket.io-client.d.ts new file mode 100644 index 0000000000..e4c6e0e38c --- /dev/null +++ b/socket.io-client/socket.io-client.d.ts @@ -0,0 +1,33 @@ +// Type definitions for socket.io nodejs client +// Project: http://socket.io/ +// Definitions by: Maido Kaara +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "socket.io-client" { + + export function connect(host: string, details?: any): Socket; + + interface EventEmitter { + emit(name: string, ...data: any[]): any; + on(ns: string, fn: Function): EventEmitter; + addListener(ns: string, fn: Function): EventEmitter; + removeListener(ns: string, fn: Function): EventEmitter; + removeAllListeners(ns: string): EventEmitter; + once(ns: string, fn: Function): EventEmitter; + listeners(ns: string): Function[]; + } + + interface SocketNamespace extends EventEmitter { + of(name: string): SocketNamespace; + send(data: any, fn: Function): SocketNamespace; + emit(name: string): SocketNamespace; + } + + interface Socket extends EventEmitter { + of(name: string): SocketNamespace; + connect(fn: Function): Socket; + packet(data: any): Socket; + flushBuffer(): void; + disconnect(): Socket; + } +} diff --git a/socket.io/socket.io.d.ts b/socket.io/socket.io.d.ts index d1b4a4863c..8d137d7af0 100644 --- a/socket.io/socket.io.d.ts +++ b/socket.io/socket.io.d.ts @@ -23,7 +23,7 @@ interface Socket { in(room: string): Socket; to(room: string): Socket; join(name: string, fn: Function): Socket; - unjoin(name: string, fn: Function): Socket; + leave(name: string, fn: Function): Socket; set(key: string, value: any, fn: Function): Socket; get(key: string, fn: Function): Socket; has(key: string, fn: Function): Socket; diff --git a/soundjs/soundjs.d.ts b/soundjs/soundjs.d.ts index d51100279b..922d116675 100644 --- a/soundjs/soundjs.d.ts +++ b/soundjs/soundjs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for SoundJS 0.5.0 +// Type definitions for SoundJS 0.5.2 // Project: http://www.createjs.com/#!/SoundJS // Definitions by: Pedro Ferreira // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -19,45 +19,29 @@ declare module createjs { constructor(); // properties - static BASE_PATH: string; static buildDate: string; - static capabilities: Object; flashReady: boolean; showOutput: boolean; + static swfPath: string; static version: string; // methods create(src: string): SoundInstance; - flashLog(data: string): void; getVolume(): number; - handleErrorEvent(error: string): void; - handleEvent(method: string): void; - handlePreloadEvent(flashId: string, method: string): void; - handleSoundEvent(flashId: string, method: string): void; isPreloadStarted(src: string): boolean; static isSupported(): boolean; - preload(src: string, instance: Object, basePath: string): void; + preload(src: string, instance: Object): void; register(src: string, instances: number): Object; - registerPreloadInstance(flashId: string, instance: any): void; - registerSoundInstance(flashId: string, instance: any): void; removeAllSounds (): void; removeSound(src: string): void; setMute(value: boolean): boolean; setVolume(value: number): boolean; - unregisterPreloadInstance(flashId: string): void; - unregisterSoundInstance(flashId: string, instance: any): void; - toString(): string; } export class HTMLAudioPlugin { constructor(); // properties - static AUDIO_ENDED: string; - static AUDIO_ERROR: string; - static AUDIO_READY: string; - static AUDIO_SEEKED: string; - static AUDIO_STALLED: string; defaultNumChannels: number; enableIOS: boolean; static MAX_INSTANCES: number; @@ -66,18 +50,17 @@ declare module createjs { create(src: string): SoundInstance; isPreloadStarted(src: string): boolean; static isSupported(): boolean; - preload(src: string, instance: Object, basePath: string): void; + preload(src: string, instance: Object): void; register(src: string, instances: number): Object; removeAllSounds(): void; removeSound(src: string): void; - toString(): string; } export class Sound { // properties static activePlugin: Object; + static alternateExtensions: any[]; static defaultInterruptBehavior: string; - static DELIMITER: string; static EXTENSION_MAP: Object; static INTERRUPT_ANY: string; static INTERRUPT_EARLY: string; @@ -102,18 +85,18 @@ declare module createjs { static loadComplete(src: string): boolean; static play(src: string, interrupt?: any, delay?: number, offset?: number, loop?: number, volume?: number, pan?: number): SoundInstance; static registerManifest(manifest: any[], basePath: string): Object; - static registerPlugin(plugin: Object): boolean; static registerPlugins(plugins: any[]): boolean; + static registerSound(src: string, id?: string, data?: number, preload?: boolean, basePath?: string): Object; static registerSound(src: string, id?: string, data?: Object, preload?: boolean, basePath?: string): Object; + static registerSound(src: Object, id?: string, data?: number, preload?: boolean, basePath?: string): Object; static registerSound(src: Object, id?: string, data?: Object, preload?: boolean, basePath?: string): Object; static removeAllSounds(): void; - static removeManifest(manifest: any[]): Object; - static removeSound(src: string): boolean; - static removeSound(src: Object): boolean; + static removeManifest(manifest: any[], basePath: string): Object; + static removeSound(src: string, basePath: string): boolean; + static removeSound(src: Object, basePath: string): boolean; static setMute(value: boolean): boolean; static setVolume(value: number): void; static stop(): void; - static toString(): string; // EventDispatcher mixins static addEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; @@ -128,16 +111,19 @@ declare module createjs { static off(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; static off(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; static off(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; - static on(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; - static on(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function; - static on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object; - static on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): Object; + static off(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + static on(type: string, listener: (eventObj: Object) => boolean, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + static on(type: string, listener: (eventObj: Object) => void, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + static on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; + static on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; static removeAllEventListeners(type?: string): void; static removeEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; static removeEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; - + static removeEventListener(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + static toString(): string; + static willTrigger(type: string): boolean; } export class SoundInstance extends EventDispatcher { @@ -149,6 +135,7 @@ declare module createjs { panNode: any; playState: string; sourceNode: any; + src: string; uniqueId: any; //HERE string or number volume: number; @@ -191,15 +178,11 @@ declare module createjs { isPreloadStarted(src: string): boolean; static isSupported(): boolean; playEmptySound(): void; + preload(src: string, instance: Object): void; register(src: string, instances: number): Object; removeAllSounds(src: string): void; - /** - * @deprecated - */ - removeFromPreload(src: string): void; removeSound(src: string): void; setMute(value: boolean): boolean; setVolume(value: number): boolean; - toString(): string; } } diff --git a/state-machine/state-machine.d.ts b/state-machine/state-machine.d.ts index efecb2e4c3..0805a1db31 100644 --- a/state-machine/state-machine.d.ts +++ b/state-machine/state-machine.d.ts @@ -1,9 +1,9 @@ // Type definitions for Finite State Machine 2.2 // Project: https://github.com/jakesgordon/javascript-state-machine // Definitions by: Boris Yankov +// Definitions by: Maarten Docter (2013/01/22) +// Definitions by: William Sears (2013/01/25) // Definitions: https://github.com/borisyankov/DefinitelyTyped -// Updated: 2013/01/22 by Maarten Docter -// Updated: 2013/01/25 by William Sears interface StateMachineErrorCallback { (eventName?: string, from?: string, to?: string, args?: any[], errorCode?: number, errorMessage?: string, ex?: Error): void; // NB. errorCode? See: StateMachine.Error @@ -11,7 +11,7 @@ interface StateMachineErrorCallback { interface StateMachineEventDef { name: string; - from: string; + from: any; // string or string[] to: string; } @@ -78,4 +78,4 @@ interface StateMachine { transition: StateMachineTransition; } -declare var StateMachine: StateMachineStatic; \ No newline at end of file +declare var StateMachine: StateMachineStatic; diff --git a/storejs/storejs.d.ts b/storejs/storejs.d.ts index 8f1adcb1b4..d80865b2a4 100644 --- a/storejs/storejs.d.ts +++ b/storejs/storejs.d.ts @@ -1,9 +1,10 @@ // Type definitions for store.js -// store.js exposes a simple API for cross browser local storage // Project: https://github.com/marcuswestin/store.js/ // Definitions by: Vincent Bortone // Definitions: https://github.com/borisyankov/DefinitelyTyped +// store.js exposes a simple API for cross browser local storage + interface StoreJSStatic { set(key: string, value: any): any; get(key: string): any; @@ -17,4 +18,4 @@ interface StoreJSStatic { deserialize(value: string): any; } -declare var store: StoreJSStatic; \ No newline at end of file +declare var store: StoreJSStatic; diff --git a/sugar/sugar.d.ts b/sugar/sugar.d.ts index ff2ff8dcc9..de418b65e5 100644 --- a/sugar/sugar.d.ts +++ b/sugar/sugar.d.ts @@ -1,4 +1,8 @@ -/* +// Type definitions for Sugar 1.3.9 +// Project: http://sugarjs.com/ +// Definitions by: Josh Baldwin +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/* sugar-1.3.9.d.ts may be freely distributed under the MIT license. Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/sugar.d.ts @@ -2129,7 +2133,7 @@ interface Array { * }, 2, true); **/ each( - fn: (element: T, index: number, array: T[]) => boolean, + fn: (element: T, index?: number, array?: T[]) => any, index?: number, loop?: boolean): T[]; @@ -2354,16 +2358,14 @@ interface Array { * [{age:35,name:'ken'},{age:15,name:'bob'}].groupBy(function(n) { * return n.age; * }); -> { 35: [{age:35,name:'ken'}], 15: [{age:15,name:'bob'}] } - * todo: return should be : { [key: U]: any } **/ - groupBy(map: string, fn?: (group: T) => void ): { [key: string]: any }; + groupBy(map: string, fn?: (key: string, items: T[]) => void): { [key: string]: T }; /** * @see groupBy * @param map Callback function for each element, returns the key for the group the element should be in. - * todo: return should be : { [key: U]: any } **/ - groupBy(map: (element: T) => U, fn?: (group: T) => void ): { [key: string]: any }; + groupBy(map: (element: T) => U, fn?: (key: string, items: T[]) => void): { [key: string]: T[] }; /** * Groups the array into arrays. @@ -2549,7 +2551,7 @@ interface Array { * return n['a']; * }); -> {a:3} **/ - max(map: string): T; + max(map?: string): T; /** * @see max @@ -2567,7 +2569,7 @@ interface Array { /** * @see max **/ - max(map: (n: T) => U): T[]; + max(map: (n: T) => U, all: boolean): T[]; /*** * Returns the element in the array with the lowest value. @@ -2585,7 +2587,7 @@ interface Array { * return n['a']; * }); -> [{a:2}] **/ - min(map: string): T; + min(map?: string): T; /** * @see min If true return all min values in the array, default = false. @@ -2617,7 +2619,7 @@ interface Array { * return n.age; * }); -> [{age:12,name:'bob'},{age:12,name:'ted'}] **/ - most(map: string): T[]; + most(map?: string): T[]; /** * @see most @@ -3384,7 +3386,7 @@ interface ObjectStatic { * }); * **/ - watch(obj: any, prop: string, fn: (prop: string, oldVal: any, newVal: any) => any): void; + watch(obj: any, prop: string, fn: (prop?: string, oldVal?: any, newVal?: any) => any): void; } interface Object { @@ -3834,7 +3836,7 @@ interface Object { * }); * **/ - watch(prop: string, fn: (prop: string, oldVal: any, newVal: any) => any): void; + watch(prop: string, fn: (prop?: string, oldVal?: any, newVal?: any) => any): void; } interface Function { diff --git a/svgjs/svgjs.d.ts b/svgjs/svgjs.d.ts index 6b7a7a6ae1..5ff8303ff8 100644 --- a/svgjs/svgjs.d.ts +++ b/svgjs/svgjs.d.ts @@ -38,7 +38,36 @@ declare module svgjs { mask():Mask; // TODO gradients - } + } + + + // https://github.com/wout/svg.filter.js + export interface Filter { + gaussianBlur(values:string):Filter; + colorMatrix(name:string, value:number):Filter; + colorMatrix(name:string, matrix:number[]):Filter; + componentTransfer(components:{rgb?: FilterComponentTransfer; g?: FilterComponentTransfer;}):Filter; + offset(x:number, y:number):Filter; + blend():Filter; + in(source:FilterSource):Filter; + sourceAlpha:FilterSource; + source:FilterSource; + } + + export interface FilterSource { + + } + + + export interface FilterComponentTransfer { + type: string; + tableValues?: string; + slope?: number; + intercept: number; + amplitude: number; + exponent: number; + offset: number; + } export interface Element extends Text, Parent { node:LinkedHTMLElement; @@ -48,9 +77,10 @@ declare module svgjs { animate(duration?:number, ease?:string, delay?:number):Animation; animate(info:{ease?:string; duration?:number; delay?:number}):Animation; - attr(name:string, value:any, namespace?:string):Element; - attr(obj:Object):Element; attr(name:string):any; + attr(obj:Object):Element; + attr(name:string, value:any, namespace?:string):Element; + viewbox():Viewbox; viewbox(x:number, y:number, w:number, h:number):Element; viewbox(obj:Viewbox):Element; @@ -71,6 +101,7 @@ declare module svgjs { remove():void; each(iterator:(i?:number, children?:Element[])=>void, deep?:boolean):void; + filter(adder:(filter:Filter)=>void):Element; transform(t:Transform):Element; @@ -204,6 +235,12 @@ declare module svgjs { export interface RBox extends BBox {} + export interface Attributes { + (name:string, value:any):void; + (obj:Object):void; + (name:string):any; + } + export interface Viewbox { x: number; y: number; diff --git a/teechart/teechart.d.ts b/teechart/teechart.d.ts index 27fead7653..2b747b3d9f 100644 --- a/teechart/teechart.d.ts +++ b/teechart/teechart.d.ts @@ -1,3 +1,7 @@ +// Type definitions for TeeChart 1.3 +// Project: http://www.steema.com +// Definitions by: Steema Software +// Definitions: https://github.com/borisyankov/DefinitelyTyped /** * TeeChart(tm) for TypeScript * diff --git a/test-module/test-addon.ts b/test-module/test-addon.ts new file mode 100644 index 0000000000..14c5ba0d6f --- /dev/null +++ b/test-module/test-addon.ts @@ -0,0 +1,5 @@ +/// + +declare module 'test-addon' { + export function addon(): Such; +} diff --git a/test-module/test-module.d.ts b/test-module/test-module.d.ts new file mode 100644 index 0000000000..294e7ea433 --- /dev/null +++ b/test-module/test-module.d.ts @@ -0,0 +1,7 @@ +interface Such { + amaze(): void; + much(): void; +} +declare module 'test-module' { + export function wow(): Such; +} diff --git a/threejs/three-tests.ts b/threejs/three-tests.ts index 5f079347fe..afb4b23004 100644 --- a/threejs/three-tests.ts +++ b/threejs/three-tests.ts @@ -1613,7 +1613,7 @@ THE SOFTWARE. }); var orders = [ 'XYZ', 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY' ]; - var eulerAngles = new THREE.Vector3( 0.1, -0.3, 0.25 ); + var eulerAngles = new THREE.Euler( 0.1, -0.3, 0.25 ); @@ -1699,16 +1699,19 @@ THE SOFTWARE. }); - test( "setFromEuler/setEulerFromQuaternion", function() { + test( "setFromEuler/setFromQuaternion", function() { var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; // ensure euler conversion to/from Quaternion matches. for( var i = 0; i < orders.length; i ++ ) { for( var j = 0; j < angles.length; j ++ ) { - var eulers2 = new THREE.Vector3().setEulerFromQuaternion( new THREE.Quaternion().setFromEuler( angles[j], orders[i] ), orders[i] ); - - ok( eulers2.distanceTo( angles[j] ) < 0.001, "Passed!" ); + var eulers2 = new THREE.Euler().setFromQuaternion( + new THREE.Quaternion().setFromEuler(new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i])), + orders[i] + ); + var v = new THREE.Vector3().applyEuler(eulers2); + ok( v.distanceTo( angles[j] ) < 0.001, "Passed!" ); } } @@ -1718,8 +1721,8 @@ THE SOFTWARE. // ensure euler conversion for Quaternion matches that of Matrix4 for( var i = 0; i < orders.length; i ++ ) { - var q = new THREE.Quaternion().setFromEuler( eulerAngles, orders[i] ); - var m = new THREE.Matrix4().setRotationFromEuler( eulerAngles, orders[i] ); + var q = new THREE.Quaternion().setFromEuler( eulerAngles ); + var m = new THREE.Matrix4().makeRotationFromEuler( eulerAngles ); var q2 = new THREE.Quaternion().setFromRotationMatrix( m ); ok( qSub( q, q2 ).length() < 0.001, "Passed!" ); @@ -1763,15 +1766,15 @@ THE SOFTWARE. var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; - var q1 = new THREE.Quaternion().setFromEuler( angles[0], "XYZ" ); - var q2 = new THREE.Quaternion().setFromEuler( angles[1], "XYZ" ); - var q3 = new THREE.Quaternion().setFromEuler( angles[2], "XYZ" ); + var q1 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); + var q2 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); + var q3 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); var q = new THREE.Quaternion().multiplyQuaternions( q1, q2 ).multiply( q3 ); - var m1 = new THREE.Matrix4().setRotationFromEuler( angles[0], "XYZ" ); - var m2 = new THREE.Matrix4().setRotationFromEuler( angles[1], "XYZ" ); - var m3 = new THREE.Matrix4().setRotationFromEuler( angles[2], "XYZ" ); + var m1 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); + var m2 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); + var m3 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); var m = new THREE.Matrix4().multiplyMatrices( m1, m2 ).multiply( m3 ); @@ -1787,8 +1790,8 @@ THE SOFTWARE. // ensure euler conversion for Quaternion matches that of Matrix4 for( var i = 0; i < orders.length; i ++ ) { for( var j = 0; j < angles.length; j ++ ) { - var q = new THREE.Quaternion().setFromEuler( angles[j], orders[i] ); - var m = new THREE.Matrix4().setRotationFromEuler( angles[j], orders[i] ); + var q = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); + var m = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); var v0 = new THREE.Vector3(1, 0, 0); var qv = v0.clone().applyQuaternion( q ); @@ -1971,10 +1974,10 @@ THE SOFTWARE. ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); a = new THREE.Ray( zero3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - m.rotateByAxis( new THREE.Vector3( 0, 0, 1 ), Math.PI ); + m.makeRotationAxis( new THREE.Vector3( 0, 0, 1 ), Math.PI ); ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); - m.identity().rotateX( Math.PI ); + m.identity().makeRotationX( Math.PI ); var b = a.clone(); b.direction.negate(); var a2 = a.clone().applyMatrix4( m ); @@ -4467,7 +4470,7 @@ var container, stats; } var PI2 = Math.PI * 2; - particleMaterial = new THREE.ParticleCanvasMaterial( { + particleMaterial = new THREE.ParticleSystemMaterial( { color: 0x000000, program: function ( context ) { @@ -4527,7 +4530,8 @@ var container, stats; var mat = mesh.material; mat.color.setHex( Math.random() * 0xffffff ); - var particle = new THREE.Particle( particleMaterial ); + var geometry = new THREE.Geometry(); + var particle = new THREE.ParticleSystem(geometry, particleMaterial ); particle.position = intersects[ 0 ].point; particle.scale.x = particle.scale.y = 8; scene.add( particle ); @@ -4623,8 +4627,8 @@ var container, stats; scene = new THREE.Scene(); for ( var i = 0; i < 100; i ++ ) { - - var particle = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: Math.random() * 0x808080 + 0x808080, program: programStroke } ) ); + var geometry = new THREE.Geometry(); + var particle = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: Math.random() * 0x808080 + 0x808080, program: programStroke } ) ); particle.position.x = Math.random() * 800 - 400; particle.position.y = Math.random() * 800 - 400; particle.position.z = Math.random() * 800 - 400; @@ -5154,15 +5158,16 @@ var container, stats; } - particle1 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0xff0040, program: program } ) ); + var geometry = new THREE.Geometry(); + particle1 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0xff0040, program: program } ) ); particle1.scale.x = particle1.scale.y = particle1.scale.z = 0.5; scene.add( particle1 ); - particle2 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x0040ff, program: program } ) ); + particle2 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0x0040ff, program: program } ) ); particle2.scale.x = particle2.scale.y = particle2.scale.z = 0.5; scene.add( particle2 ); - particle3 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x80ff80, program: program } ) ); + particle3 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0x80ff80, program: program } ) ); particle3.scale.x = particle3.scale.y = particle3.scale.z = 0.5; scene.add( particle3 ); @@ -5277,15 +5282,16 @@ var container, stats; } - particle1 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0xff0040, program: program } ) ); + var geometry = new THREE.Geometry(); + particle1 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0xff0040, program: program } ) ); particle1.scale.x = particle1.scale.y = particle1.scale.z = 0.5; scene.add( particle1 ); - particle2 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x0040ff, program: program } ) ); + particle2 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0x0040ff, program: program } ) ); particle2.scale.x = particle2.scale.y = particle2.scale.z = 0.5; scene.add( particle2 ); - particle3 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x80ff80, program: program } ) ); + particle3 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0x80ff80, program: program } ) ); particle3.scale.x = particle3.scale.y = particle3.scale.z = 0.5; scene.add( particle3 ); @@ -5401,7 +5407,7 @@ var container, stats; // particles var PI2 = Math.PI * 2; - var material = new THREE.ParticleCanvasMaterial( { + var material = new THREE.ParticleSystemMaterial( { color: 0xffffff, program: function ( context ) { @@ -5419,7 +5425,7 @@ var container, stats; for ( var i = 0; i < 100; i ++ ) { - particle = new THREE.Particle( material ); + particle = new THREE.ParticleSystem(geometry, material ); particle.position.x = Math.random() * 2 - 1; particle.position.y = Math.random() * 2 - 1; particle.position.z = Math.random() * 2 - 1; @@ -5556,7 +5562,7 @@ var container, stats; // particles var PI2 = Math.PI * 2; - var material = new THREE.ParticleCanvasMaterial( { + var material = new THREE.ParticleSystemMaterial( { color: 0xffffff, program: function ( context ) { @@ -5570,9 +5576,10 @@ var container, stats; } ); + var geometry = new THREE.Geometry(); for ( var i = 0; i < 1000; i ++ ) { - particle = new THREE.Particle( material ); + particle = new THREE.ParticleSystem(geometry, material ); particle.position.x = Math.random() * 2 - 1; particle.position.y = Math.random() * 2 - 1; particle.position.z = Math.random() * 2 - 1; @@ -5780,7 +5787,8 @@ var container, stats; } - particleLight = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0xffffff, program: program } ) ); + var geometry = new THREE.Geometry(); + particleLight = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0xffffff, program: program } ) ); particleLight.scale.x = particleLight.scale.y = particleLight.scale.z = 4; scene.add( particleLight ); @@ -6344,7 +6352,7 @@ var container, stats; var amounty = 10; var PI2 = Math.PI * 2; - var materialParticle = new THREE.ParticleCanvasMaterial( { + var materialParticle = new THREE.ParticleSystemMaterial( { color: 0x0808080, program: function ( context ) { @@ -6358,11 +6366,10 @@ var container, stats; } ); + var geometry = new THREE.Geometry(); for ( var ix = 0; ix < amountx; ix++ ) { - for ( var iy = 0; iy < amounty; iy++ ) { - - var particle = new THREE.Particle( materialParticle ); + var particle = new THREE.ParticleSystem(geometry, materialParticle ); particle.position.x = ix * separation - ( ( amountx * separation ) / 2 ); particle.position.y = -153 particle.position.z = iy * separation - ( ( amounty * separation ) / 2 ); @@ -6472,13 +6479,13 @@ var container, stats; scene = new THREE.Scene(); - var material = new THREE.ParticleBasicMaterial(); - + var material = new THREE.ParticleSystemMaterial(); + var geometry = new THREE.Geometry(); for ( var ix = 0; ix < AMOUNTX; ix++ ) { for ( var iy = 0; iy < AMOUNTY; iy++ ) { - particle = new THREE.Particle( material ); + particle = new THREE.ParticleSystem(geometry, material ); particle.scale.y = 4; particle.position.x = ix * SEPARATION - ( ( AMOUNTX * SEPARATION ) / 2 ); particle.position.z = iy * SEPARATION - ( ( AMOUNTY * SEPARATION ) / 2 ); @@ -6607,9 +6614,10 @@ var container, stats; group = new THREE.Object3D(); scene.add( group ); + var geometry = new THREE.Geometry(); for ( var i = 0; i < 1000; i++ ) { - particle = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: Math.random() * 0x808008 + 0x808080, program: program } ) ); + particle = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: Math.random() * 0x808008 + 0x808080, program: program } ) ); particle.position.x = Math.random() * 2000 - 1000; particle.position.y = Math.random() * 2000 - 1000; particle.position.z = Math.random() * 2000 - 1000; @@ -6730,11 +6738,11 @@ var container, stats; scene = new THREE.Scene(); - var material = new THREE.ParticleBasicMaterial({ map: new THREE.Texture(generateSprite()), blending: THREE.AdditiveBlending }); - + var material = new THREE.ParticleSystemMaterial({ map: new THREE.Texture(generateSprite()), blending: THREE.AdditiveBlending }); + var geometry = new THREE.Geometry(); for (var i = 0; i < 1000; i++) { - particle = new THREE.Particle(material); + particle = new THREE.ParticleSystem(geometry, material); initParticle(particle, i * 10); @@ -6796,7 +6804,7 @@ var container, stats; function initParticle(particle, delay) { - var particle = this instanceof THREE.Particle ? this : particle; + var particle = this instanceof THREE.ParticleSystem ? this : particle; var delay = delay !== undefined ? delay : 0; particle.position.x = 0; @@ -6900,11 +6908,11 @@ var container, stats; scene = new THREE.Scene(); - var material = new THREE.ParticleBasicMaterial( { map: new THREE.Texture( generateSprite() ), blending: THREE.AdditiveBlending } ); - + var material = new THREE.ParticleSystemMaterial( { map: new THREE.Texture( generateSprite() ), blending: THREE.AdditiveBlending } ); + var geometry = new THREE.Geometry(); for ( var i = 0; i < 1000; i++ ) { - particle = new THREE.Particle( material ); + particle = new THREE.ParticleSystem(geometry, material ); initParticle( particle, i * 10 ); @@ -6966,7 +6974,7 @@ var container, stats; function initParticle( particle, delay ) { - var particle = this instanceof THREE.Particle ? this : particle; + var particle = this instanceof THREE.ParticleSystem ? this : particle; var delay = delay !== undefined ? delay : 0; particle.position.x = 0; @@ -7083,7 +7091,7 @@ var container, stats; particles = new Array(); var PI2 = Math.PI * 2; - var material = new THREE.ParticleCanvasMaterial( { + var material = new THREE.ParticleSystemMaterial( { color: 0xffffff, program: function ( context ) { @@ -7097,12 +7105,12 @@ var container, stats; } ); var i = 0; - + var geometry = new THREE.Geometry(); for ( var ix = 0; ix < AMOUNTX; ix ++ ) { for ( var iy = 0; iy < AMOUNTY; iy ++ ) { - particle = particles[ i ++ ] = new THREE.Particle( material ); + particle = particles[ i ++ ] = new THREE.ParticleSystem(geometry, material ); particle.position.x = ix * SEPARATION - ( ( AMOUNTX * SEPARATION ) / 2 ); particle.position.z = iy * SEPARATION - ( ( AMOUNTY * SEPARATION ) / 2 ); scene.add( particle ); @@ -7948,8 +7956,8 @@ var container, stats; joint.position.copy( start ); joint.position.lerp( end, 0.5 ); - joint.matrix.copy( objMatrix ); - joint.rotation.setEulerFromRotationMatrix( joint.matrix, joint.eulerOrder ); + joint.matrix.copy(objMatrix); + joint.rotation = new THREE.Euler().setFromRotationMatrix(joint.matrix, joint.eulerOrder); joint.matrixAutoUpdate = false; joint.updateMatrix(); @@ -9086,12 +9094,12 @@ var container, stats; var stars; var starsMaterials = [ - new THREE.ParticleBasicMaterial( { color: 0x555555, size: 2, sizeAttenuation: false } ), - new THREE.ParticleBasicMaterial( { color: 0x555555, size: 1, sizeAttenuation: false } ), - new THREE.ParticleBasicMaterial( { color: 0x333333, size: 2, sizeAttenuation: false } ), - new THREE.ParticleBasicMaterial( { color: 0x3a3a3a, size: 1, sizeAttenuation: false } ), - new THREE.ParticleBasicMaterial( { color: 0x1a1a1a, size: 2, sizeAttenuation: false } ), - new THREE.ParticleBasicMaterial( { color: 0x1a1a1a, size: 1, sizeAttenuation: false } ) + new THREE.ParticleSystemMaterial( { color: 0x555555, size: 2, sizeAttenuation: false } ), + new THREE.ParticleSystemMaterial( { color: 0x555555, size: 1, sizeAttenuation: false } ), + new THREE.ParticleSystemMaterial( { color: 0x333333, size: 2, sizeAttenuation: false } ), + new THREE.ParticleSystemMaterial( { color: 0x3a3a3a, size: 1, sizeAttenuation: false } ), + new THREE.ParticleSystemMaterial( { color: 0x1a1a1a, size: 2, sizeAttenuation: false } ), + new THREE.ParticleSystemMaterial( { color: 0x1a1a1a, size: 1, sizeAttenuation: false } ) ]; for ( i = 10; i < 30; i ++ ) { @@ -10185,8 +10193,9 @@ var container, stats; sphere = new THREE.Mesh( new THREE.SphereGeometry( 100, 20, 20 ), new THREE.MeshNormalMaterial( { shading: THREE.SmoothShading } ) ); scene.add( sphere ); - var geometry = new THREE.CylinderGeometry( 0, 10, 100, 3 ); - geometry.applyMatrix( new THREE.Matrix4().setRotationFromEuler( new THREE.Vector3( Math.PI / 2, Math.PI, 0 ) ) ); + var geometry = new THREE.CylinderGeometry(0, 10, 100, 3); + var v = new THREE.Vector3(Math.PI / 2, Math.PI, 0); + geometry.applyMatrix(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(v.x, v.y, v.z) ) ); var material = new THREE.MeshNormalMaterial(); @@ -11536,7 +11545,6 @@ declare var ballPosition: THREE.Vector3; mesh.receiveShadow = true; var animation = new THREE.Animation( mesh, geometry.animation.name ); - animation.JITCompile = false; animation.interpolationType = THREE.AnimationHandler.LINEAR; animation.play(); @@ -12079,7 +12087,7 @@ declare var ballPosition: THREE.Vector3; // - var material = new THREE.ParticleBasicMaterial( { size: 15, vertexColors: true } ); + var material = new THREE.ParticleSystemMaterial( { size: 15, vertexColors: true } ); particleSystem = new THREE.ParticleSystem( geometry, material ); scene.add( particleSystem ); @@ -12225,7 +12233,7 @@ declare var ballPosition: THREE.Vector3; } - var particles = new THREE.ParticleSystem( geometry, new THREE.ParticleBasicMaterial( { color: 0x888888 } ) ); + var particles = new THREE.ParticleSystem( geometry, new THREE.ParticleSystemMaterial( { color: 0x888888 } ) ); scene.add( particles ); // @@ -13249,30 +13257,6 @@ declare var ballPosition: THREE.Vector3; geometry.vertices.push( new THREE.Vector3( x1, y1, z1 ) ); } - - var ribbon = new THREE.Ribbon( geometry, material ); - scene.add( ribbon ); - - materials.push( ribbon.material ); - - var ribbon = new THREE.Ribbon( geometry, material.clone() ); - ribbon.position.y = 250; - ribbon.position.x = 250; - scene.add( ribbon ); - - var ribbonMaterial = ribbon.material; - - ribbonMaterial.uniforms.color.value.setHSL( 0, 0.75, 1 ); - materials.push( ribbon.material ); - - var ribbon = new THREE.Ribbon( geometry, material.clone() ); - ribbon.position.y = -250; - ribbon.position.x = 250; - scene.add( ribbon ); - - ribbonMaterial.uniforms.color.value.setHSL( 0.1, 0.75, 1 ); - materials.push( ribbon.material ); - // renderer = new THREE.WebGLRenderer( { antialias: true } ); @@ -14289,8 +14273,8 @@ declare var ballPosition: THREE.Vector3; } - var extrudeSettings: { amount: number; bevelEnabled: boolean; bevelSegments: number; steps: number; extrudePath?: THREE.SplineCurve3; }; - extrudeSettings = { amount: 200, bevelEnabled: true, bevelSegments: 2, steps: 150 }; // bevelSegments: 2, steps: 2 , bevelSegments: 5, bevelSize: 8, bevelThickness:5, + var extrudeSettings: { amount: number; bevelEnabled: boolean; bevelSegments: number; steps: number; extrudePath: THREE.Path; }; + extrudeSettings = { amount: 200, bevelEnabled: true, bevelSegments: 2, steps: 150, extrudePath: new THREE.Path() }; // bevelSegments: 2, steps: 2 , bevelSegments: 5, bevelSize: 8, bevelThickness:5, // var extrudePath = new THREE.Path(); @@ -14302,41 +14286,6 @@ declare var ballPosition: THREE.Vector3; extrudeSettings.bevelEnabled = false; - var extrudeBend = new THREE.SplineCurve3( //Closed - [ - - new THREE.Vector3( 30, 12, 83), - new THREE.Vector3( 40, 20, 67), - new THREE.Vector3( 60, 40, 99), - new THREE.Vector3( 10, 60, 49), - new THREE.Vector3( 25, 80, 40) - - ]); - - var pipeSpline = new THREE.SplineCurve3([ - new THREE.Vector3(0, 10, -10), new THREE.Vector3(10, 0, -10), new THREE.Vector3(20, 0, 0), new THREE.Vector3(30, 0, 10), new THREE.Vector3(30, 0, 20), new THREE.Vector3(20, 0, 30), new THREE.Vector3(10, 0, 30), new THREE.Vector3(0, 0, 30), new THREE.Vector3(-10, 10, 30), new THREE.Vector3(-10, 20, 30), new THREE.Vector3(0, 30, 30), new THREE.Vector3(10, 30, 30), new THREE.Vector3(20, 30, 15), new THREE.Vector3(10, 30, 10), new THREE.Vector3(0, 30, 10), new THREE.Vector3(-10, 20, 10), new THREE.Vector3(-10, 10, 10), new THREE.Vector3(0, 0, 10), new THREE.Vector3(10, -10, 10), new THREE.Vector3(20, -15, 10), new THREE.Vector3(30, -15, 10), new THREE.Vector3(40, -15, 10), new THREE.Vector3(50, -15, 10), new THREE.Vector3(60, 0, 10), new THREE.Vector3(70, 0, 0), new THREE.Vector3(80, 0, 0), new THREE.Vector3(90, 0, 0), new THREE.Vector3(100, 0, 0)] - ); - - var sampleClosedSpline = new THREE.ClosedSplineCurve3([ - new THREE.Vector3(0, -40, -40), - new THREE.Vector3(0, 40, -40), - new THREE.Vector3(0, 140, -40), - new THREE.Vector3(0, 40, 40), - new THREE.Vector3(0, -40, 40), - ]); - - var randomPoints = []; - - for ( var i = 0; i < 10; i ++ ) { - - randomPoints.push( new THREE.Vector3(Math.random() * 200,Math.random() * 200,Math.random() * 200 ) ); - - } - - var randomSpline = new THREE.SplineCurve3( randomPoints ); - - extrudeSettings.extrudePath = randomSpline; // extrudeBend sampleClosedSpline pipeSpline randomSpline - // Circle var circleRadius = 4; @@ -14360,7 +14309,7 @@ declare var ballPosition: THREE.Vector3; var pts = [], starPoints = 5, l; - for ( i = 0; i < starPoints * 2; i ++ ) { + for ( var i = 0; i < starPoints * 2; i ++ ) { if ( i % 2 == 1 ) { @@ -14408,7 +14357,7 @@ declare var ballPosition: THREE.Vector3; var circle3d = starShape.extrude( extrudeSettings ); //circleShape rectShape smileyShape starShape // var circle3d = new THREE.ExtrudeGeometry(circleShape, extrudeBend, extrudeSettings ); - var tube = new THREE.TubeGeometry(extrudeSettings.extrudePath, 150, 4, 5, false, true); + var tube = new THREE.TubeGeometry(extrudeSettings.extrudePath, 150, 4, 5, false); // new THREE.TubeGeometry(extrudePath, segments, 2, radiusSegments, closed2, debug); @@ -14556,18 +14505,6 @@ function render() { var binormal = new THREE.Vector3(); var normal = new THREE.Vector3(); - - var pipeSpline = new THREE.SplineCurve3([ - new THREE.Vector3(0, 10, -10), new THREE.Vector3(10, 0, -10), new THREE.Vector3(20, 0, 0), new THREE.Vector3(30, 0, 10), new THREE.Vector3(30, 0, 20), new THREE.Vector3(20, 0, 30), new THREE.Vector3(10, 0, 30), new THREE.Vector3(0, 0, 30), new THREE.Vector3(-10, 10, 30), new THREE.Vector3(-10, 20, 30), new THREE.Vector3(0, 30, 30), new THREE.Vector3(10, 30, 30), new THREE.Vector3(20, 30, 15), new THREE.Vector3(10, 30, 10), new THREE.Vector3(0, 30, 10), new THREE.Vector3(-10, 20, 10), new THREE.Vector3(-10, 10, 10), new THREE.Vector3(0, 0, 10), new THREE.Vector3(10, -10, 10), new THREE.Vector3(20, -15, 10), new THREE.Vector3(30, -15, 10), new THREE.Vector3(40, -15, 10), new THREE.Vector3(50, -15, 10), new THREE.Vector3(60, 0, 10), new THREE.Vector3(70, 0, 0), new THREE.Vector3(80, 0, 0), new THREE.Vector3(90, 0, 0), new THREE.Vector3(100, 0, 0)]); - - var sampleClosedSpline = new THREE.ClosedSplineCurve3([ - new THREE.Vector3(0, -40, -40), - new THREE.Vector3(0, 40, -40), - new THREE.Vector3(0, 140, -40), - new THREE.Vector3(0, 40, 40), - new THREE.Vector3(0, -40, 40), - ]); - // Keep a dictionary of Curve instances var splines = { GrannyKnot: new THREE.Curves.GrannyKnot(), @@ -14583,9 +14520,7 @@ function render() { DecoratedTorusKnot4a: new THREE.Curves.DecoratedTorusKnot4a(), DecoratedTorusKnot4b: new THREE.Curves.DecoratedTorusKnot4b(), DecoratedTorusKnot5a: new THREE.Curves.DecoratedTorusKnot5a(), - DecoratedTorusKnot5c: new THREE.Curves.DecoratedTorusKnot5c(), - PipeSpline: pipeSpline, - SampleClosedSpline: sampleClosedSpline + DecoratedTorusKnot5c: new THREE.Curves.DecoratedTorusKnot5c() }; @@ -14626,7 +14561,7 @@ function render() { extrudePath = splines[value]; - tube = new THREE.TubeGeometry(extrudePath, segments, 2, radiusSegments, closed2, debug); + tube = new THREE.TubeGeometry(extrudePath, segments, 2, radiusSegments, closed2); addGeometry(tube, 0xff00ff); setScale(); @@ -16872,7 +16807,7 @@ function render() { // vertices from real points var pgeo = points.clone(); - var particles = new THREE.ParticleSystem( pgeo, new THREE.ParticleBasicMaterial( { color: color, size: 2, opacity: 0.75 } ) ); + var particles = new THREE.ParticleSystem( pgeo, new THREE.ParticleSystemMaterial( { color: color, size: 2, opacity: 0.75 } ) ); particles.position.set( x, y, z + 75 ); particles.rotation.set( rx, ry, rz ); particles.scale.set( s, s, s ); @@ -16889,7 +16824,7 @@ function render() { // equidistance sampled points var pgeo = spacedPoints.clone(); - var particles2 = new THREE.ParticleSystem( pgeo, new THREE.ParticleBasicMaterial( { color: color, size: 2, opacity: 0.5 } ) ); + var particles2 = new THREE.ParticleSystem( pgeo, new THREE.ParticleSystemMaterial( { color: color, size: 2, opacity: 0.5 } ) ); particles2.position.set( x, y, z + 125 ); particles2.rotation.set( rx, ry, rz ); particles2.scale.set( s, s, s ); @@ -17083,12 +17018,6 @@ function render() { // TODO 3d path? - var apath = new THREE.SplineCurve3(); - apath.points.push(new THREE.Vector3(-50, 150, 10)); - apath.points.push(new THREE.Vector3(-20, 180, 20)); - apath.points.push(new THREE.Vector3(40, 220, 50)); - apath.points.push(new THREE.Vector3(200, 290, 100)); - var extrudeSettings:any = { amount: 20 }; // bevelSegments: 2, steps: 2 , bevelSegments: 5, bevelSize: 8, bevelThickness:5 @@ -17109,7 +17038,6 @@ function render() { addShape( smileyShape, extrudeSettings, 0xee00ff, -200, 250, 0, 0, 0, Math.PI, 1 ); addShape( arcShape, extrudeSettings, 0xbb4422, 150, 0, 0, 0, 0, 0, 1 ); - extrudeSettings.extrudePath = apath; extrudeSettings.bevelEnabled = false; extrudeSettings.steps = 20; @@ -17494,10 +17422,9 @@ function render() { } for ( var i = 0; i < smooth.vertices.length; i++ ) { - - var particle = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: Math.random() * 0x808008 + 0x808080, program: program } ) ); + var geometry = new THREE.Geometry(); + var particle = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: Math.random() * 0x808008 + 0x808080, program: program } ) ); particle.position = smooth.vertices[ i ]; - var pos = smooth.vertices.position particle.scale.x = particle.scale.y = 5; group.add( particle ); } @@ -17523,10 +17450,9 @@ function render() { } for ( var i = 0; i < geometry.vertices.length; i++ ) { - - particle = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: Math.random() * 0x808008 + 0x808080, program: drawText(i) } ) ); + var geometry = new THREE.Geometry(); + particle = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: Math.random() * 0x808008 + 0x808080, program: drawText(i) } ) ); particle.position = smooth.vertices[ i ]; - var pos = geometry.vertices.position particle.scale.x = particle.scale.y = 30; group.add( particle ); } @@ -20226,7 +20152,6 @@ function render() { THREE.AnimationHandler.add( object.geometry.animation ); var animation = new THREE.Animation( object, object.geometry.animation.name ); - animation.JITCompile = false; animation.interpolationType = THREE.AnimationHandler.LINEAR; animation.play(); @@ -22629,62 +22554,6 @@ function render() { } - var tmpRot = new THREE.Matrix4(); - tmpRot.makeRotationAxis( new THREE.Vector3( 1, 0, 0 ), Math.PI/2 ); - - var xgrid = 34; - var ygrid = 15; - var nribbons = xgrid * ygrid; - - var c = 0; - for (var i = 0; i < xgrid; i ++ ) - for (var j = 0; j < ygrid; j ++ ) { - - var material = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.VertexColors, side: THREE.DoubleSide } ); - - ribbon = new THREE.Ribbon( i % 2 ? geometry : geometry2, material ); - ribbon.rotation.x = 0; - ribbon.rotation.y = Math.PI / 2; - ribbon.rotation.z = Math.PI; - - x = 40 * ( i - xgrid/2 ); - y = 40 * ( j - ygrid/2 ); - z = 0; - - ribbon.position.set( x, y, z ); - - ribbon.matrixAutoUpdate = false; - - // manually create local matrix - - ribbon.matrix.setPosition( ribbon.position ); - ribbon.matrixRotationWorld.setRotationFromEuler( ribbon.rotation ); - - ribbon.matrix.elements[ 0 ] = ribbon.matrixRotationWorld.elements[ 0 ]; - ribbon.matrix.elements[ 4 ] = ribbon.matrixRotationWorld.elements[ 4 ]; - ribbon.matrix.elements[ 8 ] = ribbon.matrixRotationWorld.elements[ 8 ]; - - ribbon.matrix.elements[ 1 ] = ribbon.matrixRotationWorld.elements[ 1 ]; - ribbon.matrix.elements[ 5 ] = ribbon.matrixRotationWorld.elements[ 5 ]; - ribbon.matrix.elements[ 9 ] = ribbon.matrixRotationWorld.elements[ 9 ]; - - ribbon.matrix.elements[ 2 ] = ribbon.matrixRotationWorld.elements[ 2 ]; - ribbon.matrix.elements[ 6 ] = ribbon.matrixRotationWorld.elements[ 6 ]; - ribbon.matrix.elements[ 10 ] = ribbon.matrixRotationWorld.elements[ 10 ]; - - ribbon.matrix.multiply( tmpRot ); - - ribbon.matrix.scale( ribbon.scale ); - - ribbons.push( ribbon ); - scene.add( ribbon ); - - c ++; - - } - - scene.matrixAutoUpdate = false; - // renderer = new THREE.WebGLRenderer( { antialias: false } ); diff --git a/threejs/three.d.ts b/threejs/three.d.ts index e2e923f87f..b76430f92e 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1,5940 +1,5307 @@ -// Type definitions for three.js -// Project: http://mrdoob.github.com/three.js/ -// Definitions by: Kon -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface WebGLRenderingContext {} - -declare module THREE { - export var REVISION: string; - - // GL STATE CONSTANTS - - export enum CullFace { } - export var CullFaceNone: CullFace; - export var CullFaceBack: CullFace; - export var CullFaceFront: CullFace; - export var CullFaceFrontBack: CullFace; - - export enum FrontFaceDirection { } - export var FrontFaceDirectionCW: FrontFaceDirection; - export var FrontFaceDirectionCCW: FrontFaceDirection; - - // SHADOWING TYPES - - export enum ShadowMapType { } - export var BasicShadowMap: ShadowMapType; - export var PCFShadowMap: ShadowMapType; - export var PCFSoftShadowMap: ShadowMapType; - - // MATERIAL CONSTANTS - - // side - export enum Side { } - export var FrontSide: Side; - export var BackSide: Side; - export var DoubleSide: Side; - - // shading - export enum Shading { } - export var NoShading: Shading; - export var FlatShading: Shading; - export var SmoothShading: Shading; - - // colors - export enum Colors { } - export var NoColors: Colors; - export var FaceColors: Colors; - export var VertexColors: Colors; - - // blending modes - export enum Blending { } - export var NoBlending: Blending; - export var NormalBlending: Blending; - export var AdditiveBlending: Blending; - export var SubtractiveBlending: Blending; - export var MultiplyBlending: Blending; - export var CustomBlending: Blending; - - // custom blending equations - // (numbers start from 100 not to clash with other - // mappings to OpenGL constants defined in Texture.js) - export enum BlendingEquation { } - export var AddEquation: BlendingEquation; - export var SubtractEquation: BlendingEquation; - export var ReverseSubtractEquation: BlendingEquation; - - // custom blending destination factors - export enum BlendingDstFactor { } - export var ZeroFactor: BlendingDstFactor; - export var OneFactor: BlendingDstFactor; - export var SrcColorFactor: BlendingDstFactor; - export var OneMinusSrcColorFactor: BlendingDstFactor; - export var SrcAlphaFactor: BlendingDstFactor; - export var OneMinusSrcAlphaFactor: BlendingDstFactor; - export var DstAlphaFactor: BlendingDstFactor; - export var OneMinusDstAlphaFactor: BlendingDstFactor; - - // custom blending source factors - export enum BlendingSrcFactor { } - export var DstColorFactor: BlendingSrcFactor; - export var OneMinusDstColorFactor: BlendingSrcFactor; - export var SrcAlphaSaturateFactor: BlendingSrcFactor; - - // TEXTURE CONSTANTS - export enum Combine { } - export var MultiplyOperation: Combine; - export var MixOperation: Combine; - export var AddOperation: Combine; - - // Mapping modes - export enum Mapping { } - export interface MappingConstructor { - new(): Mapping; - } - export var UVMapping: MappingConstructor; - export var CubeReflectionMapping: MappingConstructor; - export var CubeRefractionMapping: MappingConstructor; - export var SphericalReflectionMapping: MappingConstructor; - export var SphericalRefractionMapping: MappingConstructor; - - // Wrapping modes - export enum Wrapping { } - export var RepeatWrapping: Wrapping; - export var ClampToEdgeWrapping: Wrapping; - export var MirroredRepeatWrapping: Wrapping; - - // Filters - export enum TextureFilter { } - export var NearestFilter: TextureFilter; - export var NearestMipMapNearestFilter: TextureFilter; - export var NearestMipMapLinearFilter: TextureFilter; - export var LinearFilter: TextureFilter; - export var LinearMipMapNearestFilter: TextureFilter; - export var LinearMipMapLinearFilter: TextureFilter; - - // Data types - export enum TextureDataType { } - export var UnsignedByteType: TextureDataType; - export var ByteType: TextureDataType; - export var ShortType: TextureDataType; - export var UnsignedShortType: TextureDataType; - export var IntType: TextureDataType; - export var UnsignedIntType: TextureDataType; - export var FloatType: TextureDataType; - - // Pixel types - export enum PixelType { } - // export var UnsignedByteType:number; - export var UnsignedShort4444Type: PixelType; - export var UnsignedShort5551Type: PixelType; - export var UnsignedShort565Type: PixelType; - - // Pixel formats - export enum PixelFormat { } - export var AlphaFormat: PixelFormat; - export var RGBFormat: PixelFormat; - export var RGBAFormat: PixelFormat; - export var LuminanceFormat: PixelFormat; - export var LuminanceAlphaFormat: PixelFormat; - - // Compressed texture formats - export enum CompressedPixelFormat { } - export var RGB_S3TC_DXT1_Format: CompressedPixelFormat; - export var RGBA_S3TC_DXT1_Format: CompressedPixelFormat; - export var RGBA_S3TC_DXT3_Format: CompressedPixelFormat; - export var RGBA_S3TC_DXT5_Format: CompressedPixelFormat; - - - // Potential future PVRTC compressed texture formats - // export enum CompressedTextureFormats {} - // export var RGB_PVRTC_4BPPV1_Format :CompressedTextureFormats; - // export var RGB_PVRTC_2BPPV1_Format :CompressedTextureFormats; - // export var RGBA_PVRTC_4BPPV1_Format:CompressedTextureFormats; - // export var RGBA_PVRTC_2BPPV1_Format:CompressedTextureFormats; - - - // Following enums don't be contained by three.js - - // export enum EulerOrder {} - // export var XYZ:EulerOrder; - // export var XZY:EulerOrder; - // export var YXZ:EulerOrder; - // export var YZX:EulerOrder; - // export var ZXY:EulerOrder; - // export var ZYX:EulerOrder; - - // enum UniformType {} - // i, // single integer - // f, // single float - // v2, // single THREE.Vector2 - // v3, // single THREE.Vector3 - // v4, // single THREE.Vector4 - // c, // single THREE.Color - // iv1, // flat array of integers (JS or typed array) - // iv, // flat array of integers with 3 x N size (JS or typed array) - // fv1, // flat array of floats (JS or typed array) - // fv, // flat array of floats with 3 x N size (JS or typed array) - // v2v, // array of THREE.Vector2 - // v3v, // array of THREE.Vector3 - // v4v, // array of THREE.Vector4 - // m4, // single THREE.Matrix4 - // m4v, // array of THREE.Matrix4 - // t, // single THREE.Texture (2d or cube) - // tv, // array of THREE.Texture (2d) - // } - - // Core /////////////////////////////////////////////////////////////////////////////////////////////// - - interface BufferGeometryAttributeArray extends ArrayBufferView{ - length: number; - } - - interface BufferGeometryAttribute{ - itemSize: number; - array: BufferGeometryAttributeArray; - numItems: number; - } - - interface BufferGeometryAttributes{ - [name: string]: BufferGeometryAttribute; - index?: BufferGeometryAttribute; - position?: BufferGeometryAttribute; - normal?: BufferGeometryAttribute; - color?: BufferGeometryAttribute; - } - - /** - * This is a superefficent class for geometries because it saves all data in buffers. - * It reduces memory costs and cpu cycles. But it is not as easy to work with because of all the nessecary buffer calculations. - * It is mainly interesting when working with static objects. - * - * @see src/core/BufferGeometry.js - */ - export class BufferGeometry { - /** - * This creates a new BufferGeometry. It also sets several properties to an default value. - */ - constructor(); - - /** - * Unique number of this buffergeometry instance - */ - id: number; - - /** - * This hashmap has as id the name of the attribute to be set and as value the buffer to set it to. - */ - attributes: BufferGeometryAttributes; - - /** - * When set, it holds certain buffers in memory to have faster updates for this object. When unset, it deletes those buffers and saves memory. - */ - dynamic: boolean; - - /** - * Bounding box. - */ - boundingBox: BoundingBox3D; - - /** - * Bounding sphere. - */ - boundingSphere: BoundingSphere; - - hasTangents: boolean; - morphTargets: any[]; - - offsets: { start: number; count: number; index: number; }[]; - - /** - * Bakes matrix transform directly into vertex coordinates. - */ - applyMatrix(matrix: Matrix4): void; - - verticesNeedUpdate: boolean; - - /** - * Computes bounding box of the geometry, updating Geometry.boundingBox attribute. - * Bounding boxes aren't computed by default. They need to be explicitly computed, otherwise they are null. - */ - computeBoundingBox(): void; - - /** - * Computes bounding sphere of the geometry, updating Geometry.boundingSphere attribute. - * Bounding spheres aren't' computed by default. They need to be explicitly computed, otherwise they are null. - */ - computeBoundingSphere(): void; - - /** - * Computes vertex normals by averaging face normals. - */ - computeVertexNormals(): void; - - normalizeNormals(): void; - - /** - * Computes vertex tangents. - * Based on http://www.terathon.com/code/tangent.html - * Geometry must have vertex UVs (layer 0 will be used). - */ - computeTangents(): void; - - /** - * Disposes the object from memory. - * You need to call this when you want the bufferGeometry removed while the application is running. - */ - dispose(): void; - } - - /** - * Object for keeping track of time. - * - * @see src/core/Clock.js - */ - export class Clock { - /** - * @param autoStart Automatically start the clock. - */ - constructor(autoStart?: boolean); - - /** - * If set, starts the clock automatically when the first update is called. - */ - autoStart: boolean; - - /** - * When the clock is running, It holds the starttime of the clock. - * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. - */ - startTime: number; - - /** - * When the clock is running, It holds the previous time from a update. - * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. - */ - oldTime: number; - - /** - * When the clock is running, It holds the time elapsed btween the start of the clock to the previous update. - * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. - */ - elapsedTime: number; - - /** - * This property keeps track whether the clock is running or not. - */ - running: boolean; - - /** - * Starts clock. - */ - start(): void; - - /** - * Stops clock. - */ - stop(): void; - - /** - * Get milliseconds passed since the clock started. - */ - getElapsedTime(): number; - - /** - * Get the milliseconds passed since the last call to this method. - */ - getDelta(): number; - } - - export interface HSL { - h: number; - s: number; - l: number; - } - - /** - * Represents a color. See also {@link ColorUtils}. - * - * @example - * var color = new THREE.Color( 0xff0000 ); - * - * @see src/math/Color.js - */ - export class Color { - constructor(hex?: string); - - /** - * @param hex initial color in hexadecimal - */ - constructor(hex?: number); - - /** - * Red channel value between 0 and 1. Default is 1. - */ - r: number; - - /** - * Green channel value between 0 and 1. Default is 1. - */ - g: number; - - /** - * Blue channel value between 0 and 1. Default is 1. - */ - b: number; - set (value: number): void; - set (value: string): void; - setHex(hex: number): Color; - - /** - * Sets this color from RGB values. - * @param r Red channel value between 0 and 1. - * @param g Green channel value between 0 and 1. - * @param b Blue channel value between 0 and 1. - */ - setRGB(r: number, g: number, b: number): Color; - - /** - * Sets this color from HSL values. - * Based on MochiKit implementation by Bob Ippolito. - * - * @param h Hue channel value between 0 and 1. - * @param s Saturation value channel between 0 and 1. - * @param l Value channel value between 0 and 1. - */ - setHSL(h: number, s: number, l: number): Color; - - /** - * Sets this color from a CSS context style string. - * @param contextStyle Color in CSS context style format. - */ - setStyle(style: string): Color; - - /** - * Copies given color. - * @param color Color to copy. - */ - copy(color: Color): Color; - - /** - * Copies given color making conversion from gamma to linear space. - * @param color Color to copy. - */ - copyGammaToLinear(color: Color): Color; - - /** - * Copies given color making conversion from linear to gamma space. - * @param color Color to copy. - */ - copyLinearToGamma(color: Color): Color; - - /** - * Converts this color from gamma to linear space. - */ - convertGammaToLinear(): Color; - - /** - * Converts this color from linear to gamma space. - */ - convertLinearToGamma(): Color; - - /** - * Returns the hexadecimal value of this color. - */ - getHex(): number; - - /** - * Returns the string formated hexadecimal value of this color. - */ - getHexString(): string; - - getHSL(): HSL; - - /** - * Returns the value of this color in CSS context style. - * Example: rgb(r, g, b) - */ - getStyle(): string; - - offsetHSL(h:number, s:number, l:number): Color; - - add(color: Color): Color; - addColors(color1: Color, color2: Color): Color; - addScalar(s: number): Color; - multiply(color: Color): Color; - multiplyScalar(s: number): Color; - lerp(color: Color, alpha: number): Color; - - /** - * Clones this color. - */ - clone(): Color; - } - - var ColorKeywords: { - [name: string]: number; - aliceblue: number; - antiquewhite: number; - aqua: number; - aquamarine: number; - azure: number; - beige: number; - bisque: number; - black: number; - blanchedalmond: number; - blue: number; - blueviolet: number; - brown: number; - burlywood: number; - cadetblue: number; - chartreuse: number; - chocolate: number; - coral: number; - cornflowerblue: number; - cornsilk: number; - crimson: number; - cyan: number; - darkblue: number; - darkcyan: number; - darkgoldenrod: number; - darkgray: number; - darkgreen: number; - darkgrey: number; - darkkhaki: number; - darkmagenta: number; - darkolivegreen: number; - darkorange: number; - darkorchid: number; - darkred: number; - darksalmon: number; - darkseagreen: number; - darkslateblue: number; - darkslategray: number; - darkslategrey: number; - darkturquoise: number; - darkviolet: number; - deeppink: number; - deepskyblue: number; - dimgray: number; - dimgrey: number; - dodgerblue: number; - firebrick: number; - floralwhite: number; - forestgreen: number; - fuchsia: number; - gainsboro: number; - ghostwhite: number; - gold: number; - goldenrod: number; - gray: number; - green: number; - greenyellow: number; - grey: number; - honeydew: number; - hotpink: number; - indianred: number; - indigo: number; - ivory: number; - khaki: number; - lavender: number; - lavenderblush: number; - lawngreen: number; - lemonchiffon: number; - lightblue: number; - lightcoral: number; - lightcyan: number; - lightgoldenrodyellow: number; - lightgray: number; - lightgreen: number; - lightgrey: number; - lightpink: number; - lightsalmon: number; - lightseagreen: number; - lightskyblue: number; - lightslategray: number; - lightslategrey: number; - lightsteelblue: number; - lightyellow: number; - lime: number; - limegreen: number; - linen: number; - magenta: number; - maroon: number; - mediumaquamarine: number; - mediumblue: number; - mediumorchid: number; - mediumpurple: number; - mediumseagreen: number; - mediumslateblue: number; - mediumspringgreen: number; - mediumturquoise: number; - mediumvioletred: number; - midnightblue: number; - mintcream: number; - mistyrose: number; - moccasin: number; - navajowhite: number; - navy: number; - oldlace: number; - olive: number; - olivedrab: number; - orange: number; - orangered: number; - orchid: number; - palegoldenrod: number; - palegreen: number; - paleturquoise: number; - palevioletred: number; - papayawhip: number; - peachpuff: number; - peru: number; - pink: number; - plum: number; - powderblue: number; - purple: number; - red: number; - rosybrown: number; - royalblue: number; - saddlebrown: number; - salmon: number; - sandybrown: number; - seagreen: number; - seashell: number; - sienna: number; - silver: number; - skyblue: number; - slateblue: number; - slategray: number; - slategrey: number; - snow: number; - springgreen: number; - steelblue: number; - tan: number; - teal: number; - thistle: number; - tomato: number; - turquoise: number; - violet: number; - wheat: number; - white: number; - whitesmoke: number; - yellow: number; - yellowgreen: number; - }; - - /** - * JavaScript events for custom objects - * - * # Example - * var Car = function () { - * - * EventDispatcher.call( this ); - * this.start = function () { - * - * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } ); - * - * }; - * - * }; - * - * var car = new Car(); - * car.addEventListener( 'start', function ( event ) { - * - * alert( event.message ); - * - * } ); - * car.start(); - * - * @source src/core/EventDispatcher.js - */ - export class EventDispatcher { - /** - * Creates eventDispatcher object. It needs to be call with '.call' to add the functionality to an object. - */ - constructor(); - - /** - * Adds a listener to an event type. - * @param type The type of the listener that gets removed. - * @param listener The listener function that gets removed. - */ - addEventListener(type: string, listener: (event: any) => void ): void; - - /** - * Fire an event type. - * @param type The type of event that gets fired. - */ - dispatchEvent(event: { type:string; target: any; }): void; - - /** - * Removes a listener from an event type. - * @param type The type of the listener that gets removed. - * @param listener The listener function that gets removed. - */ - removeEventListener(type: string, listener: (event: any) => void ): void; - } - - export interface Face { - /** - * Face normal. - */ - normal: Vector3; - - /** - * Face color. - */ - color: Color; - - /** - * Array of 4 vertex normals. - */ - vertexNormals: Vector3[]; - - /** - * Array of 4 vertex normals. - */ - vertexColors: Color[]; - - /** - * Array of 4 vertex tangets. - */ - vertexTangents: number[]; - - /** - * Material index (points to {@link Geometry.materials}). - */ - materialIndex: number; - - /** - * Face centroid. - */ - centroid: Vector3; - - clone(): Face; - } - - /** - * Triangle face. - * - * # Example - * var normal = new THREE.Vector3( 0, 1, 0 ); - * var color = new THREE.Color( 0xffaa00 ); - * var face = new THREE.Face3( 0, 1, 2, normal, color, 0 ); - * - * @source https://github.com/mrdoob/three.js/blob/master/src/core/Face3.js - */ - export class Face3 implements Face { - /** - * @param a Vertex A index. - * @param b Vertex B index. - * @param c Vertex C index. - * @param normal Face normal or array of vertex normals. - * @param color Face color or array of vertex colors. - * @param materialIndex Material index. - */ - constructor(a: number, b: number, c: number, normal?: Vector3, color?: Color, materialIndex?: number); - constructor(a: number, b: number, c: number, normal?: Vector3, vertexColors?: Color[], materialIndex?: number); - constructor(a: number, b: number, c: number, vertexNormals?: Vector3[], color?: Color, materialIndex?: number); - constructor(a: number, b: number, c: number, vertexNormals?: Vector3[], vertexColors?: Color[], materialIndex?: number); - - /** - * Vertex A index. - */ - a: number; - - /** - * Vertex B index. - */ - b: number; - - /** - * Vertex C index. - */ - c: number; - - clone(): Face3; - - // properties inherits from Face /////////////////////////////////// - - /** - * Face normal. - */ - normal: Vector3; - - /** - * Face color. - */ - color: Color; - - /** - * Array of 4 vertex normals. - */ - vertexNormals: Vector3[]; - - /** - * Array of 4 vertex normals. - */ - vertexColors: Color[]; - - /** - * Array of 4 vertex tangets. - */ - vertexTangents: number[]; - - /** - * Material index (points to {@link Geometry.materials}). - */ - materialIndex: number; - - /** - * Face centroid. - */ - centroid: Vector3; - } - - /** - * Quad face. - * - * # example - * var normal = new THREE.Vector3( 0, 1, 0 ); - * var color = new THREE.Color( 0xffaa00 ); - * var face = new THREE.Face4( 0, 1, 2, 3, normal, color, 0 ); - * - * @source https://github.com/mrdoob/three.js/blob/master/src/core/Face4.js - */ - export class Face4 implements Face { - /** - * @param a Vertex A index. - * @param b Vertex B index. - * @param c Vertex C index. - * @param d Vertex D index. - * @param normal Face normal or array of vertex normals. - * @param color Face color or array of vertex colors. - * @param materialIndex Material index. - */ - constructor(a: number, b: number, c: number, d: number, normal?: Vector3, color?: Color, materialIndex?: number); - constructor(a: number, b: number, c: number, d: number, normal?: Vector3, vertexColors?: Color[], materialIndex?: number); - constructor(a: number, b: number, c: number, d: number, vertexNormals?: Vector3[], color?: Color, materialIndex?: number); - constructor(a: number, b: number, c: number, d: number, vertexNormals?: Vector3[], vertexColors?: Color[], materialIndex?: number); - - /** - * Vertex A index. - */ - a: number; - - /** - * Vertex B index. - */ - b: number; - - /** - * Vertex C index. - */ - c: number; - - /** - * Vertex D index. - */ - d: number; - - clone(): Face4; - - - - // properties inherits from Face /////////////////////////////////// - - /** - * Face normal. - */ - normal: Vector3; - - /** - * Face color. - */ - color: Color; - - /** - * Array of 4 vertex normals. - */ - vertexNormals: Vector3[]; - - /** - * Array of 4 vertex normals. - */ - vertexColors: Color[]; - - /** - * Array of 4 vertex tangets. - */ - vertexTangents: number[]; - - /** - * Material index (points to {@link Geometry.materials}). - */ - materialIndex: number; - - /** - * Face centroid. - */ - centroid: Vector3; - } - - /** - * Frustums are used to determine what is inside the camera's field of view. They help speed up the rendering process. - */ - export class Frustum { - constructor(p0?: Plane, p1?: Plane, p2?: Plane, p3?: Plane, p4?: Plane, p5?: Plane); - - /** - * Array of 6 vectors. - */ - planes: Plane[]; - - set (p0?: number, p1?: number, p2?: number, p3?: number, p4?: number, p5?: number): Frustum; - copy(frustum: Frustum): Frustum; - setFromMatrix(m: Matrix4): Frustum; - - /** - * Checks whether the object is inside the Frustum. - */ - intersectsObject(object: Object3D): boolean; - - intersectsSphere(sphere: Sphere): boolean; - containsPoint(point: Vector3): boolean; - clone(): Frustum; - } - - export class Line3{ - constructor(start?:Vector3, end?:Vector3); - start: Vector3; - end: Vector3; - set(start?:Vector3, end?:Vector3):Line3; - copy(line:Line3):Line3; - center(optionalTarget?:Vector3):Vector3; - delta(optionalTarget?:Vector3):Vector3; - distanceSq():number; - distance():number; - at(t:number, optionalTarget?: Vector3):Vector3; - closestPointToPointParameter(point:Vector3, clampToLine?:boolean):number; - closestPointToPoint(point:Vector3, clampToLine?:boolean, optionalTarget?:Vector3):Vector3; - applyMatrix4(matrix:Matrix4):Line3; - equals(line:Line3):boolean; - clone():Line3; - } - - export class Plane { - constructor(normal?: Vector3, constant?: number); - normal: Vector3; - constant: number; - set (normal: Vector3, constant: number): Plane; - setComponents(x: number, y: number, z: number, w: number): Plane; - setFromNormalAndCoplanarPoint(normal: Vector3, point: Vector3): Plane; - setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): Plane; - copy(plane: Plane): Plane; - normalize(): Plane; - negate(): Plane; - distanceToPoint(point: Vector3): number; - distanceToSphere(sphere: Sphere): number; - projectPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - orthoPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - isIntersectionLine(line: Line3): boolean; - intersectLine(line: Line3, optionalTarget?: Vector3): Vector3; - coplanarPoint(optionalTarget?: boolean): Vector3; - applyMatrix4(matrix: Matrix4, optionalNormalMatrix?: Matrix3): Plane; - translate(offset: Vector3): Plane; - equals(plane: Plane): boolean; - clone(): Plane; - } - - export class Sphere { - constructor(center?: Vector3, radius?: number); - center: Vector3; - radius: number; - set (center: Vector3, radius: number): Sphere; - setFromCenterAndPoints(center: Vector3, points: Vector3[]): Sphere; - copy(sphere: Sphere): Sphere; - empty(): boolean; - containsPoint(point: Vector3): boolean; - distanceToPoint(point: Vector3): number; - intersectsSphere(sphere: Sphere): boolean; - clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - getBoundingBox(optionalTarget?: Box3): Box3; - applyMatrix4(matrix: Matrix): Sphere; - translate(offset: Vector3): Sphere; - equals(sphere: Sphere): boolean; - clone(): Sphere; - } - - - export interface MorphTarget { - name: string; - vertices: Vector3[]; - } - - export interface MorphColor { - name: string; - color: Color[]; - } - - export interface BoundingBox3D { - min: Vector3; - max: Vector3; - } - - export interface BoundingSphere { - radius: number; - } - - - /** - * Base class for geometries - * - * # Example - * var geometry = new THREE.Geometry(); - * geometry.vertices.push( new THREE.Vector3( -10, 10, 0 ) ); - * geometry.vertices.push( new THREE.Vector3( -10, -10, 0 ) ); - * geometry.vertices.push( new THREE.Vector3( 10, -10, 0 ) ); - * geometry.faces.push( new THREE.Face3( 0, 1, 2 ) ); - * geometry.computeBoundingSphere(); - * - * @see https://github.com/mrdoob/three.js/blob/master/src/core/Geometry.js - */ - export class Geometry { - constructor(); - - /** - * Unique number of this geometry instance - */ - id: number; - - /** - * Name for this geometry. Default is an empty string. - */ - name: string; - - /** - * The array of vertices hold every position of points of the model. - * To signal an update in this array, Geometry.verticesNeedUpdate needs to be set to true. - */ - vertices: Vector3[]; - - /** - * Array of vertex colors, matching number and order of vertices. - * Used in ParticleSystem, Line and Ribbon. - * Meshes use per-face-use-of-vertex colors embedded directly in faces. - * To signal an update in this array, Geometry.colorsNeedUpdate needs to be set to true. - */ - colors: Color[]; - - /** - * Array of vertex normals, matching number and order of vertices. - * Normal vectors are nessecary for lighting - * To signal an update in this array, Geometry.normalsNeedUpdate needs to be set to true. - */ - normals: Vector3[]; - - /** - * Array of triangles or/and quads. - * The array of faces describe how each vertex in the model is connected with each other. - * To signal an update in this array, Geometry.elementsNeedUpdate needs to be set to true. - */ - faces: Face[]; - - /** - * Array of face UV layers. - * Each UV layer is an array of UV matching order and number of faces. - * To signal an update in this array, Geometry.uvsNeedUpdate needs to be set to true. - */ - faceUvs: Vector2[][]; - - /** - * Array of face UV layers. - * Each UV layer is an array of UV matching order and number of vertices in faces. - * To signal an update in this array, Geometry.uvsNeedUpdate needs to be set to true. - */ - faceVertexUvs: Vector2[][][]; - - /** - * Array of morph targets. Each morph target is a Javascript object: - * - * { name: "targetName", vertices: [ new THREE.Vector3(), ... ] } - * - * Morph vertices match number and order of primary vertices. - */ - morphTargets: MorphTarget[]; - - /** - * Array of morph colors. Morph colors have similar structure as morph targets, each color set is a Javascript object: - * - * morphNormal = { name: "NormalName", normals: [ new THREE.Vector3(), ... ] } - */ - morphColors: MorphColor[]; - - /** - * Array of skinning weights, matching number and order of vertices. - */ - skinWeights: number[]; - - /** - * Array of skinning indices, matching number and order of vertices. - */ - skinIndices: number[]; - - /** - * Bounding box. - */ - boundingBox: BoundingBox3D; - - /** - * Bounding sphere. - */ - boundingSphere: BoundingSphere; - - /** - * True if geometry has tangents. Set in Geometry.computeTangents. - */ - hasTangents: boolean; - - /** - * Set to true if attribute buffers will need to change in runtime (using "dirty" flags). - * Unless set to true internal typed arrays corresponding to buffers will be deleted once sent to GPU. - * Defaults to true. - */ - dynamic: boolean; - - /** - * Set to true if the vertices array has been updated. - */ - verticesNeedUpdate: boolean; - - /** - * Set to true if the faces array has been updated. - */ - elementsNeedUpdate: boolean; - - /** - * Set to true if the uvs array has been updated. - */ - uvsNeedUpdate: boolean; - - /** - * Set to true if the normals array has been updated. - */ - normalsNeedUpdate: boolean; - - /** - * Set to true if the tangents in the faces has been updated. - */ - tangentsNeedUpdate: boolean; - - /** - * Set to true if the colors array has been updated. - */ - colorsNeedUpdate: boolean; - - /** - * Set to true if the linedistances array has been updated. - */ - lineDistancesNeedUpdate: boolean; - - /** - * Set to true if an array has changed in length. - */ - buffersNeedUpdate: boolean; - - /** - * - */ - animation: AnimationData; - - /** - * Bakes matrix transform directly into vertex coordinates. - */ - applyMatrix(matrix: Matrix4): void; - - /** - * Computes centroids for all faces. - */ - computeCentroids(): void; - - /** - * Computes face normals. - */ - computeFaceNormals(): void; - - /** - * Computes vertex normals by averaging face normals. - * Face normals must be existing / computed beforehand. - */ - computeVertexNormals(areaWeighted?: boolean): void; - - /** - * Computes morph normals. - */ - computeMorphNormals(): void; - - /** - * Computes vertex tangents. - * Based on http://www.terathon.com/code/tangent.html - * Geometry must have vertex UVs (layer 0 will be used). - */ - computeTangents(): void; - - computeLineDistances(): void; - - /** - * Computes bounding box of the geometry, updating {@link Geometry.boundingBox} attribute. - */ - computeBoundingBox(): void; - - /** - * Computes bounding sphere of the geometry, updating Geometry.boundingSphere attribute. - * Neither bounding boxes or bounding spheres are computed by default. They need to be explicitly computed, otherwise they are null. - */ - computeBoundingSphere(): void; - - /** - * Checks for duplicate vertices using hashmap. - * Duplicated vertices are removed and faces' vertices are updated. - */ - mergeVertices(): number; - - /** - * Creates a new clone of the Geometry. - */ - clone(): Geometry; - - /** - * Removes The object from memory. - * Don't forget to call this method when you remove an geometry because it can cuase meomory leaks. - */ - dispose(): void; - } - - var GeometryIdCount: number; - var GeometryLibrary: Geometry[]; - - interface Math { - /** - * Clamps the x to be between a and b. - * - * @param x Value to be clamped. - * @param a Minimum value - * @param b Maximum value. - */ - clamp(x: number, a: number, b: number): number; - - /** - * Clamps the x to be larger than a. - * - * @param x — Value to be clamped. - * @param a — Minimum value - */ - clampBottom(x: number, a: number): number; - - /** - * Linear mapping of x from range [a1, a2] to range [b1, b2]. - * - * @param x Value to be mapped. - * @param a1 Minimum value for range A. - * @param a2 Maximum value for range A. - * @param b1 Minimum value for range B. - * @param b2 Maximum value for range B. - */ - mapLinear(x: number, a1: number, a2: number, b1: number, b2: number): number; - - smoothstep(x:number, min:number, max:number):number; - - smootherstep(x:number, min:number, max:number):number; - - /** - * Random float from 0 to 1 with 16 bits of randomness. - * Standard Math.random() creates repetitive patterns when applied over larger space. - */ - random16(): number; - - /** - * Random integer from low to high interval. - */ - randInt(low: number, high: number): number; - - /** - * Random float from low to high interval. - */ - randFloat(low: number, high: number): number; - - /** - * Random float from - range / 2 to range / 2 interval. - */ - randFloatSpread(range: number): number; - - /** - * Returns -1 if x is less than 0, 1 if x is greater than 0, and 0 if x is zero. - */ - sign(x: number): number; - - degToRad(degrees: number): number; - - radToDeg(radians: number): number; - } - - /** - * - * @see src/math/Math.js - */ - export var Math: Math; - - /** - * ( interface Matrix<T> ) - */ - export interface Matrix { - /** - * Float32Array with matrix values. - */ - elements: Float32Array; - - /** - * identity():T; - */ - identity(): Matrix; - - /** - * copy(m:T):T; - */ - copy(m: Matrix): Matrix; - - multiplyVector3Array(a: number[]): number[]; - - /** - * multiplyScalar(s:number):T; - */ - multiplyScalar(s: number): Matrix; - - determinant(): number; - - /** - * getInverse(matrix:T, throwOnInvertible?:boolean):T; - */ - getInverse(matrix: Matrix, throwOnInvertible?: boolean): Matrix; - - /** - * transpose():T; - */ - transpose(): Matrix; - - /** - * clone():T; - */ - clone(): Matrix; - } - - /** - * ( class Matrix3 implements Matrix<Matrix3> ) - */ - export class Matrix3 implements Matrix { - /** - * Creates an identity matrix. - */ - constructor(); - - /** - * Initialises the matrix with the supplied n11..n33 values. - */ - constructor(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number); - - /** - * Float32Array with matrix values. - */ - elements: Float32Array; - - set (n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): Matrix3; - identity(): Matrix3; - copy(m: Matrix3): Matrix3; - multiplyVector3Array(a: number[]): number[]; - multiplyScalar(s: number): Matrix3; - determinant(): number; - getInverse(matrix: Matrix3, throwOnInvertible?: boolean): Matrix3; - getInverse(matrix: Matrix4, throwOnInvertible?: boolean): Matrix3; - - /** - * Transposes this matrix in place. - */ - transpose(): Matrix3; - - getNormalMatrix(m:Matrix4): Matrix3; - - /** - * Transposes this matrix into the supplied array r, and returns itself. - */ - transposeIntoArray(r: number[]): number[]; - - clone(): Matrix3; - } - - /** - * A 4x4 Matrix. - * - * @example - * // Simple rig for rotating around 3 axes - * var m = new THREE.Matrix4(); - * var m1 = new THREE.Matrix4(); - * var m2 = new THREE.Matrix4(); - * var m3 = new THREE.Matrix4(); - * var alpha = 0; - * var beta = Math.PI; - * var gamma = Math.PI/2; - * m1.makeRotationX( alpha ); - * m2.makeRotationY( beta ); - * m3.makeRotationZ( gamma ); - * m.multiplyMatrices( m1, m2 ); - * m.multiply( m3 ); - */ - export class Matrix4 implements Matrix { - - /** - * Creates an identity matrix. - */ - constructor(); - - - /** - * Initialises the matrix with the supplied n11..n44 values. - */ - constructor(n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number); - - /** - * Float32Array with matrix values. - */ - elements: Float32Array; - - /** - * Sets all fields of this matrix. - */ - set (n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number): Matrix4; - - /** - * Resets this matrix to identity. - */ - identity(): Matrix4; - - /** - * Copies a matrix m into this matrix. - */ - copy(m: Matrix4): Matrix4; - - /** - * Sets the rotation submatrix of this matrix to the rotation specified by Euler angles. - * Default order is "XYZ". - * - * @param v Rotation vector. order — The order of rotations. Eg. "XYZ". - */ - setRotationFromEuler(v: Vector3, order?: string): Matrix4; - - /** - * Sets the rotation submatrix of this matrix to the rotation specified by q. - */ - setRotationFromQuaternion(q: Quaternion): Matrix4; - - /** - * Constructs a rotation matrix, looking from eye towards center with defined up vector. - */ - lookAt(eye: Vector3, target: Vector3, up: Vector3): Matrix4; - - /** - * Multiplies this matrix by m. - */ - multiply(m: Matrix4): Matrix4; - - /** - * Sets this matrix to a x b. - */ - multiplyMatrices(a: Matrix4, b: Matrix4): Matrix4; - - /** - * Sets this matrix to a x b and stores the result into the flat array r. - * r can be either a regular Array or a TypedArray. - */ - multiplyToArray(a: Matrix4, b: Matrix4, r: number[]): Matrix4; - - /** - * Multiplies this matrix by s. - */ - multiplyScalar(s: number): Matrix4; - - multiplyVector3Array(a: number[]): number[]; - - rotateAxis(v: Vector3): Vector3; - - /** - * Computes the cross product between this matrix and the Vector4 parameter a. - */ - crossVector(a: Vector3): Vector4; - - /** - * Computes determinant of this matrix. - * Based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - */ - determinant(): number; - - /** - * Transposes this matrix. - */ - transpose(): Matrix4; - - /** - * Flattens this matrix into supplied flat array. - */ - flattenToArray(flat: number[]): number[]; - - /** - * Flattens this matrix into supplied flat array starting from offset position in the array. - */ - flattenToArrayOffset(flat: number[], offset: number): number[]; - - /** - * Sets the position component for this matrix from vector v. - */ - setPosition(v: Vector3): Vector3; - - /** - * Sets this matrix to the inverse of matrix m. - * Based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm. - */ - getInverse(m: Matrix4, throwOnInvertible?: boolean): Matrix4; - - /** - * Sets this matrix to the transformation composed of translation, rotation and scale. - */ - compose(translation: Vector3, rotation: Quaternion, scale: Vector3): Matrix4; - - /** - * Decomposes this matrix into the translation, rotation and scale components. - * If parameters are not passed, new instances will be created. - */ - decompose(translation?: Vector3, rotation?: Quaternion, scale?: Vector3): Object[]; // [Vector3, Quaternion, Vector3] - - /** - * Copies the translation component of the supplied matrix m into this matrix translation component. - */ - extractPosition(m: Matrix4): Matrix4; - - /** - * Copies the rotation component of the supplied matrix m into this matrix rotation component. - */ - extractRotation(m: Matrix4): Matrix4; - - /** - * Translates this matrix by vector v. - */ - translate(v: Vector3): Matrix4; - - /** - * Rotates this matrix around the x axis by angle. - */ - rotateX(angle: number): Matrix4; - - /** - * Rotates this matrix around the y axis by angle. - */ - rotateY(angle: number): Matrix4; - - /** - * Rotates this matrix around the z axis by angle. - */ - rotateZ(angle: number): Matrix4; - - /** - * Rotates this matrix around the supplied axis by angle. - */ - rotateByAxis(axis: Vector3, angle: number): Matrix4; - - /** - * Multiplies the columns of this matrix by vector v. - */ - scale(v: Vector3): Matrix4; - - getMaxScaleOnAxis(): number; - - /** - * Sets this matrix as translation transform. - */ - makeTranslation(x: number, y: number, z: number): Matrix4; - - /** - * Sets this matrix as rotation transform around x axis by theta radians. - * - * @param theta Rotation angle in radians. - */ - makeRotationX(theta: number): Matrix4; - - /** - * Sets this matrix as rotation transform around y axis by theta radians. - * - * @param theta Rotation angle in radians. - */ - makeRotationY(theta: number): Matrix4; - - /** - * Sets this matrix as rotation transform around z axis by theta radians. - * - * @param theta Rotation angle in radians. - */ - makeRotationZ(theta: number): Matrix4; - - /** - * Sets this matrix as rotation transform around axis by angle radians. - * Based on http://www.gamedev.net/reference/articles/article1199.asp. - * - * @param axis Rotation axis. - * @param theta Rotation angle in radians. - */ - makeRotationAxis(axis: Vector3, angle: number): Matrix4; - - /** - * Sets this matrix as scale transform. - */ - makeScale(x: number, y: number, z: number): Matrix4; - - /** - * Creates a frustum matrix. - */ - makeFrustum(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix4; - - /** - * Creates a perspective projection matrix. - */ - makePerspective(fov: number, aspect: number, near: number, far: number): Matrix4; - - /** - * Creates an orthographic projection matrix. - */ - makeOrthographic(left: number, right: number, top: number, bottom: number, near: number, far: number): Matrix4; - - /** - * Clones this matrix. - */ - clone(): Matrix4; - } - - export class Ray { - constructor(origin?: Vector3, direction?: Vector3); - origin: Vector3; - direction: Vector3; - set (origin: Vector3, direction: Vector3): Ray; - copy(ray: Ray): Ray; - at(t: number, optionalTarget?: Vector3): Vector3; - recast(t: number): Ray; - closestPointToPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - distanceToPoint(point: Vector3): number; - isIntersectionSphere(sphere: Sphere): boolean; - isIntersectionPlane(plane: Plane): boolean; - distanceToPlane(plane: Plane): number; - intersectPlane(plane: Plane, optionalTarget?: Vector3): Vector3; - applyMatrix4(matrix4: Matrix4): Ray; - equals(ray: Ray): boolean; - clone(): Ray; - } - - - /** - * Base class for scene graph objects - */ - export class Object3D { - constructor(); - - /** - * Unique number of this object instance. - */ - id: number; - - /** - * Optional name of the object (doesn't need to be unique). - */ - name: string; - - properties: any; - - /** - * Object's parent in the scene graph. - */ - parent: Object3D; - - /** - * Array with object's children. - */ - children: Object3D[]; - - /** - * Object's local position. - */ - position: Vector3; - - /** - * Object's local rotation (Euler angles), in radians. - */ - rotation: Vector3; - - /** - * Order of axis for Euler angles. - */ - eulerOrder: string; - // eulerOrder:EulerOrder; - - /** - * Object's local scale. - */ - scale: Vector3; - - /** - * Up direction. - */ - up: Vector3; - - /** - * Local transform. - */ - matrix: Matrix4; - - /** - * Global rotation. - */ - matrixRotationWorld: Matrix4; - - /** - * Global rotation. - */ - quaternion: Quaternion; - - /** - * Use quaternion instead of Euler angles for specifying local rotation. - */ - useQuaternion: boolean; - - /** - * Default is 0.0. - */ - boundRadius: number; - - /** - * Maximum scale from x, y, z scale components. - */ - boundRadiusScale: number; - - /** - * Override depth-sorting order if non null. - */ - renderDepth: number; - - /** - * Object gets rendered if true. - */ - visible: boolean; - - /** - * Gets rendered into shadow map. - */ - castShadow: boolean; - - /** - * Material gets baked in shadow receiving. - */ - receiveShadow: boolean; - - /** - * When this is set, it checks every frame if the object is in the frustum of the camera. Otherwise the object gets drawn every frame even if it isn't visible. - */ - frustumCulled: boolean; - - /** - * When this is set, it calculates the matrix of position, (rotation or quaternion) and scale every frame and also recalculates the matrixWorld property. - */ - matrixAutoUpdate: boolean; - - /** - * When this is set, it calculates the matrixWorld in that frame and resets this property to false. - */ - matrixWorldNeedsUpdate: boolean; - - /** - * When this is set, then the rotationMatrix gets calculated every frame. - */ - rotationAutoUpdate: boolean; - - /** - * This updates the position, rotation and scale with the matrix. - */ - applyMatrix(matrix: Matrix4): void; - - /** - * Translates object along arbitrary axis by distance. - * @param distance Distance. - * @param axis Translation direction. - */ - translate(distance: number, axis: Vector3): void; - - /** - * Translates object along x axis by distance. - * @param distance Distance. - */ - translateX(distance: number): void; - - /** - * Translates object along y axis by distance. - * @param distance Distance. - */ - translateY(distance: number): void; - - /** - * Translates object along z axis by distance. - * @param distance Distance. - */ - translateZ(distance: number): void; - - /** - * Updates the vector from local space to world space. - * @param vector A local vector. - */ - localToWorld(vector: Vector3): Vector3; - - /** - * Updates the vector from world space to local space. - * @param vector A world vector. - */ - worldToLocal(vector: Vector3): Vector3; - - /** - * Rotates object to face point in space. - * @param vector A world vector to look at. - */ - lookAt(vector: Vector3): void; - - /** - * Adds object as child of this object. - */ - add(object: Object3D): void; - - /** - * Removes object as child of this object. - */ - remove(object: Object3D): void; - - /** - * Translates object along arbitrary axis by distance. - * @param distance Distance. - * @param axis Translation direction. - */ - traverse(callback: (object: Object3D) => any): void; - - /** - * Gets first child with name matching the argument. Searches whole subgraph recursively if recursive is true. - * @param name Object name. - * @param recursive Whether check in the objects's children. - */ - getChildByName(name: string, recursive: boolean): Object3D; - - /** - * Searches whole subgraph recursively to add all objects in the array. - * @param array optional argument that returns the the array with descendants. - */ - getDescendants(array?: Object3D[]): Object3D[]; - - /** - * Updates local transform. - */ - updateMatrix(): void; - - /** - * Updates global transform of the object and its children. - */ - updateMatrixWorld(force: boolean): void; - - /** - * Creates a new clone of this object and all descendants. - */ - clone(object?: Object3D): Object3D; - - static defaultEulerOrder: string; - // static defaultEulerOrder:EulerOrder; - } - - var Object3DIdCount: number; - var Object3DLibrary: Object3D[]; - - /** - * Projects points between spaces. - */ - export class Projector { - - constructor(); - - projectVector(vector: Vector3, camera: Camera): Vector3; - - unprojectVector(vector: Vector3, camera: Camera): Vector3; - - /** - * Translates a 2D point from NDC (Normalized Device Coordinates) to a Raycaster that can be used for picking. NDC range from [-1..1] in x (left to right) and [1.0 .. -1.0] in y (top to bottom). - */ - pickingRay(vector: Vector3, camera: Camera): Raycaster; - - /** - * Transforms a 3D scene object into 2D render data that can be rendered in a screen with your renderer of choice, projecting and clipping things out according to the used camera. - * If the scene were a real scene, this method would be the equivalent of taking a picture with the camera (and developing the film would be the next step, using a Renderer). - * - * @param scene scene to project. - * @param camera camera to use in the projection. - * @param sort select whether to sort elements using the Painter's algorithm. - */ - projectScene(scene: Scene, camera: Camera, sortObjects: boolean, sortElements?: boolean): { - objects: Object3D[]; // Mesh, Line or other object - sprites: Object3D[]; // Sprite or Particle - lights: Light[]; - elements: Face[]; // Line, Particle, Face3 or Face4 - }; - } - - /** - * Implementation of a quaternion. This is used for rotating things without incurring in the dreaded gimbal lock issue, amongst other advantages. - * - * @example - * var quaternion = new THREE.Quaternion(); - * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 ); - * var vector = new THREE.Vector3( 1, 0, 0 ); - * vector.applyQuaternion( quaternion ); - */ - export class Quaternion { - /** - * @param x x coordinate - * @param y y coordinate - * @param z z coordinate - * @param w w coordinate - */ - constructor(x?: number, y?: number, z?: number, w?: number); - - x: number; - y: number; - z: number; - w: number; - - /** - * Sets values of this quaternion. - */ - set (x: number, y: number, z: number, w: number): Quaternion; - - /** - * Copies values of q to this quaternion. - */ - copy(q: Quaternion): Quaternion; - - /** - * Sets this quaternion from rotation specified by Euler angles. - */ - setFromEuler(v: Vector3, order: string): Quaternion; - - /** - * Sets this quaternion from rotation specified by axis and angle. - * Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm. - * Axis have to be normalized, angle is in radians. - */ - setFromAxisAngle(axis: Vector3, angle: number): Quaternion; - - /** - * Sets this quaternion from rotation component of m. Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm. - */ - setFromRotationMatrix(m: Matrix4): Quaternion; - - /** - * Inverts this quaternion. - */ - inverse(): Quaternion; - - conjugate(): Quaternion; - - lengthSq(): number; - - /** - * Computes length of this quaternion. - */ - length(): number; - - /** - * Normalizes this quaternion. - */ - normalize(): Quaternion; - - /** - * Multiplies this quaternion by b. - */ - multiply(q: Quaternion): Quaternion; - - /** - * Sets this quaternion to a x b - * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm. - */ - multiplyQuaternions(a: Quaternion, b: Quaternion): Quaternion; - - slerp(qb: Quaternion, t: number): Quaternion; - - equals(v: Quaternion): boolean; - - /** - * Clones this quaternion. - */ - clone(): Quaternion; - - /** - * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/. - */ - static slerp(qa: Quaternion, qb: Quaternion, qm: Quaternion, t: number): Quaternion; - } - - export interface Intersection { - distance: number; - point: Vector3; - face: Face; - object: Object3D; - } - - export class Raycaster { - constructor(origin?: Vector3, direction?: Vector3, near?: number, far?: number); - ray: Ray; - near: number; - far: number; - precision: number; - set (origin: Vector3, direction: Vector3): void; - intersectObject(object: Object3D, recursive?: boolean): Intersection[]; - intersectObjects(objects: Object3D[], recursive?: boolean): Intersection[]; - } - - export interface SplineControlPoint { - x: number; - y: number; - z: number; - } - - /** - * Represents a spline. - * - * @see src/math/Spline.js - */ - export class Spline { - /** - * Initialises the spline with points, which are the places through which the spline will go. - */ - constructor(points: SplineControlPoint[]); - - points: SplineControlPoint[]; - - /** - * Initialises using the data in the array as a series of points. Each value in a must be another array with three values, where a[n] is v, the value for the nth point, and v[0], v[1] and v[2] are the x, y and z coordinates of that point n, respectively. - * - * @param a array of triplets containing x, y, z coordinates - */ - initFromArray(a: number[][]): void; - - /** - * Return the interpolated point at k. - * - * @param k point index - */ - getPoint(k: number): SplineControlPoint; - - /** - * Returns an array with triplets of x, y, z coordinates that correspond to the current control points. - */ - getControlPointsArray(): number[][]; - - /** - * Returns the length of the spline when using nSubDivisions. - * @param nSubDivisions number of subdivisions between control points. Default is 100. - */ - getLength(nSubDivisions?: number): { chunks: number[]; total: number; }; - - /** - * Modifies the spline so that it looks similar to the original but has its points distributed in such way that moving along the spline it's done at a more or less constant speed. The points should also appear more uniformly spread along the curve. - * This is done by resampling the original spline, with the density of sampling controlled by samplingCoef. Here it's interesting to note that denser sampling is not necessarily better: if sampling is too high, you may get weird kinks in curvature. - * - * @param samplingCoef how many intermediate values to use between spline points - */ - reparametrizeByArcLength(samplingCoef: number): void; - } - - class Triangle{ - constructor(a?: Vector3, b?: Vector3, c?: Vector3 ); - a: Vector3; - b: Vector3; - c: Vector3; - set(a: Vector3, b: Vector3, c: Vector3): Triangle; - setFromPointsAndIndices( points: Vector3[], i0: number, i1: number, i2: number ): Triangle; - copy(triangle: Triangle): Triangle; - area(): number; - midpoint(optionalTarget?: Vector3): Vector3; - normal(optionalTarget?: Vector3): Vector3; - plane(optionalTarget?: Vector3): Plane; - barycoordFromPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - containsPoint(point: Vector3): boolean; - equals(triangle: Triangle): boolean; - clone(): Triangle; - static normal(a: Vector3, b: Vector3, c: Vector3, optionalTarget?: Vector3): Vector3; - // static/instance method to calculate barycoordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - static barycoordFromPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3, optionalTarget: Vector3 ): Vector3; - static containsPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3): boolean; - } - - - /** - * ( interface Vector<T> ) - * - * Abstruct interface of Vector2, Vector3 and Vector4. - * Currently the members of Vector is NOT type safe because it accepts different typed vectors. - * Those definitions will be changed when TypeScript innovates Generics to be type safe. - * - * @example - * var v:THREE.Vector = new THREE.Vector3(); - * v.addVectors(new THREE.Vector2(0, 1), new THREE.Vector2(2, 3)); // invalid but compiled successfully - */ - export interface Vector { - setComponent(index: number, value: number): void; - - getComponent(index: number): number; - - /** - * copy(v:T):T; - */ - copy(v: Vector): Vector; - - /** - * add(v:T):T; - */ - add(v: Vector): Vector; - - /** - * addVectors(a:T, b:T):T; - */ - addVectors(a: Vector, b: Vector): Vector; - - /** - * sub(v:T):T; - */ - sub(v: Vector): Vector; - - /** - * subVectors(a:T, b:T):T; - */ - subVectors(a: Vector, b: Vector): Vector; - - /** - * multiplyScalar(s:number):T; - */ - multiplyScalar(s: number): Vector; - - /** - * divideScalar(s:number):T; - */ - divideScalar(s: number): Vector; - - /** - * negate():T; - */ - negate(): Vector; - - /** - * dot(v:T):T; - */ - dot(v: Vector): number; - - /** - * lengthSq():number; - */ - lengthSq(): number; - - /** - * length():number; - */ - length(): number; - - /** - * normalize():T; - */ - normalize(): Vector; - - /** - * NOTE: Vector4 doesn't have the property. - * - * distanceTo(v:T):number; - */ - distanceTo(v: Vector): number; - - /** - * NOTE: Vector4 doesn't have the property. - * - * distanceToSquared(v:T):number; - */ - distanceToSquared(v: Vector): number; - - /** - * setLength(l:number):T; - */ - setLength(l: number): Vector; - - /** - * lerp(v:T, alpha:number):T; - */ - lerp(v: Vector, alpha: number): Vector; - - /** - * equals(v:T):boolean; - */ - equals(v: Vector): boolean; - - /** - * clone():T; - */ - clone(): Vector; - } - - /** - * 2D vector. - * - * ( class Vector2 implements Vector ) - */ - export class Vector2 implements Vector { - - constructor(x?: number, y?: number); - - x: number; - - y: number; - - /** - * Sets value of this vector. - */ - set (x: number, y: number): Vector2; - - /** - * Sets X component of this vector. - */ - setX (x: number): Vector2; - - /** - * Sets Y component of this vector. - */ - setY(y: number): Vector2; - - /** - * Sets a component of this vector. - */ - setComponent(index: number, value: number): void; - - /** - * Gets a component of this vector. - */ - getComponent(index: number): number; - - /** - * Copies value of v to this vector. - */ - copy(v: Vector2): Vector2; - - /** - * Adds v to this vector. - */ - add(v: Vector2): Vector2; - - /** - * Sets this vector to a + b. - */ - addVectors(a: Vector2, b: Vector2): Vector2; - - /** - * Subtracts v from this vector. - */ - sub(v: Vector2): Vector2; - - /** - * Sets this vector to a - b. - */ - subVectors(a: Vector2, b: Vector2): Vector2; - - /** - * Multiplies this vector by scalar s. - */ - multiplyScalar(s: number): Vector2; - - /** - * Divides this vector by scalar s. - * Set vector to ( 0, 0 ) if s == 0. - */ - divideScalar(s: number): Vector2; - - min(v: Vector2): Vector2; - - max(v: Vector2): Vector2; - - clamp(min: Vector2, max: Vector2): Vector2; - - /** - * Inverts this vector. - */ - negate(): Vector2; - - /** - * Computes dot product of this vector and v. - */ - dot(v: Vector2): number; - - /** - * Computes squared length of this vector. - */ - lengthSq(): number; - - /** - * Computes length of this vector. - */ - length(): number; - - /** - * Normalizes this vector. - */ - normalize(): Vector2; - - /** - * Computes distance of this vector to v. - */ - distanceTo(v: Vector2): number; - - /** - * Computes squared distance of this vector to v. - */ - distanceToSquared(v: Vector2): number; - - /** - * Normalizes this vector and multiplies it by l. - */ - setLength(l: number): Vector2; - - lerp(v: Vector2, alpha: number): Vector2; - - /** - * Checks for strict equality of this vector and v. - */ - equals(v: Vector2): boolean; - - toArray(): number[]; - - /** - * Clones this vector. - */ - clone(): Vector2; - } - - /** - * 3D vector. - * - * @example - * var a = new THREE.Vector3( 1, 0, 0 ); - * var b = new THREE.Vector3( 0, 1, 0 ); - * var c = new THREE.Vector3(); - * c.crossVectors( a, b ); - * - * @see src/math/Vector3.js - * - * ( class Vector3 implements Vector ) - */ - export class Vector3 implements Vector { - - constructor(x?: number, y?: number, z?: number); - - x: number; - - y: number; - - z: number; - - /** - * Sets value of this vector. - */ - set (x: number, y: number, z: number): Vector3; - - /** - * Sets x value of this vector. - */ - setX(x: number): Vector3; - - /** - * Sets y value of this vector. - */ - setY(y: number): Vector3; - - /** - * Sets z value of this vector. - */ - setZ(z: number): Vector3; - - setComponent(index: number, value: number): void; - - getComponent(index: number): number; - - /** - * Copies value of v to this vector. - */ - copy(v: Vector3): Vector3; - - /** - * Adds v to this vector. - */ - add(a: Object): Vector3; - - addScalar(s: number): Vector3; - - /** - * Sets this vector to a + b. - */ - addVectors(a: Vector3, b: Vector3): Vector3; - - /** - * Subtracts v from this vector. - */ - sub(a: Vector3): Vector3; - - /** - * Sets this vector to a - b. - */ - subVectors(a: Vector3, b: Vector3): Vector3; - - multiply(v: Vector3): Vector3; - - /** - * Multiplies this vector by scalar s. - */ - multiplyScalar(s: number): Vector3; - - multiplyVectors(a: Vector3, b: Vector3): Vector3; - applyMatrix3(m: Matrix3): Vector3; - applyMatrix4(m: Matrix4): Vector3; - applyProjection(m: Matrix4): Vector3; - applyQuaternion(q: Quaternion): Vector3; - - // applyEuler(v:Vector3, eulerOrder:EulerOrder):Vector3; - applyEuler(v: Vector3, eulerOrder: string): Vector3; - - applyAxisAngle(axis: Vector3, angle: number): Vector3; - transformDirection(m:Matrix4):Vector3; - divide(v: Vector3): Vector3; - - /** - * Divides this vector by scalar s. - * Set vector to ( 0, 0, 0 ) if s == 0. - */ - divideScalar(s: number): Vector3; - - min(v: Vector3): Vector3; - max(v: Vector3): Vector3; - - clamp(min: Vector3, max: Vector3): Vector3; - - /** - * Inverts this vector. - */ - negate(): Vector3; - - /** - * Computes dot product of this vector and v. - */ - dot(v: Vector3): number; - - /** - * Computes squared length of this vector. - */ - lengthSq(): number; - - /** - * Computes length of this vector. - */ - length(): number; - - /** - * Computes Manhattan length of this vector. - * http://en.wikipedia.org/wiki/Taxicab_geometry - */ - lengthManhattan(): number; - - /** - * Normalizes this vector. - */ - normalize(): Vector3; - - /** - * Normalizes this vector and multiplies it by l. - */ - setLength(l: number): Vector3; - - lerp(v: Vector3, alpha: number): Vector3; - - /** - * Sets this vector to cross product of itself and v. - */ - cross(a: Vector3): Vector3; - - /** - * Sets this vector to cross product of a and b. - */ - crossVectors(a: Vector3, b: Vector3): Vector3; - - projectOnVector(v:Vector3): Vector3; - - projectOnPlane(planeNormal:Vector3): Vector3; - - reflect(vector:Vector3):Vector3; - - angleTo(v: Vector3): number; - - /** - * Computes distance of this vector to v. - */ - distanceTo(v: Vector3): number; - - /** - * Computes squared distance of this vector to v. - */ - distanceToSquared(v: Vector3): number; - - /** - * Sets this vector extracting position from matrix transform. - */ - getPositionFromMatrix(m: Matrix4): Vector3; - - setEulerFromRotationMatrix(m: Matrix4, order: string): Vector3; - - setEulerFromQuaternion(q: Quaternion, order: string): Vector3; - - /** - * Sets this vector extracting scale from matrix transform. - */ - getScaleFromMatrix(m: Matrix4): Vector3; - - /** - * Checks for strict equality of this vector and v. - */ - equals(v: Vector3): boolean; - - toArray(): number[]; - - /** - * Clones this vector. - */ - clone(): Vector3; - } - - /** - * 4D vector. - * - * ( class Vector4 implements Vector ) - */ - export class Vector4 implements Vector { - constructor(x?: number, y?: number, z?: number, w?: number); - x: number; - y: number; - z: number; - w: number; - - /** - * Sets value of this vector. - */ - set (x: number, y: number, z: number, w: number): Vector4; - - /** - * Sets X component of this vector. - */ - setX (x: number): Vector2; - - /** - * Sets Y component of this vector. - */ - setY(y: number): Vector2; - - /** - * Sets Z component of this vector. - */ - setZ(z: number): Vector2; - - /** - * Sets w component of this vector. - */ - setW(w: number): Vector2; - - setComponent(index: number, value: number): void; - - getComponent(index: number): number; - - /** - * Copies value of v to this vector. - */ - copy(v: Vector4): Vector4; - - /** - * Adds v to this vector. - */ - add(v: Vector4): Vector4; - - /** - * Sets this vector to a + b. - */ - addVectors(a: Vector4, b: Vector4): Vector4; - - /** - * Subtracts v from this vector. - */ - sub(v: Vector4): Vector4; - - /** - * Sets this vector to a - b. - */ - subVectors(a: Vector4, b: Vector4): Vector4; - - /** - * Multiplies this vector by scalar s. - */ - multiplyScalar(s: number): Vector4; - - /** - * Divides this vector by scalar s. - * Set vector to ( 0, 0, 0 ) if s == 0. - */ - divideScalar(s: number): Vector4; - - min(v: Vector4): Vector4; - - max(v: Vector4): Vector4; - - clamp(min: Vector4, max: Vector4): Vector4; - - /** - * Inverts this vector. - */ - negate(): Vector4; - - /** - * Computes dot product of this vector and v. - */ - dot(v: Vector4): number; - - /** - * Computes squared length of this vector. - */ - lengthSq(): number; - - /** - * Computes length of this vector. - */ - length(): number; - - lengthManhattan(): number; - - /** - * Normalizes this vector. - */ - normalize(): Vector4; - - /** - * NOTE: Vector4 doesn't have the property. - * Computes distance of this vector to v. - */ - distanceTo(v: Vector3): number; - - /** - * NOTE: Vector4 doesn't have the property. - * Computes squared distance of this vector to v. - */ - distanceToSquared(v: Vector3): number; - - - /** - * Normalizes this vector and multiplies it by l. - */ - setLength(l: number): Vector4; - - /** - * Linearly interpolate between this vector and v with alpha factor. - */ - lerp(v: Vector4, alpha: number): Vector4; - - /** - * Checks for strict equality of this vector and v. - */ - equals(v: Vector4): boolean; - - toArray(): number[]; - - /** - * Clones this vector. - */ - clone(): Vector4; - - /** - * http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - * @param q is assumed to be normalized - */ - setAxisAngleFromQuaternion(q: Quaternion): Vector4; - - /** - * http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - * @param m assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - */ - setAxisAngleFromRotationMatrix(m: Matrix3): Vector4; - } - - export class Box2 { - constructor(min?: Vector2, max?: Vector2); - min: Vector2; - max: Vector2; - set (min: Vector2, max: Vector2): Box2; - setFromPoints(points: Vector2[]): Box2; - setFromCenterAndSize(center: Vector2, size: number): Box2; - copy(box: Box2): Box2; - makeEmpty(): Box2; - empty(): boolean; - center(optionalTarget?: Vector2): Vector2; - size(optionalTarget?: Vector2): Vector2; - expandByPoint(point: Vector2): Box2; - expandByVector(vector: Vector2): Box2; - expandByScalar(scalar: number): Box2; - containsPoint(point: Vector2): boolean; - containsBox(box: Box2): boolean; - getParameter(point: Vector2): Vector2; - isIntersectionBox(box: Box2): boolean; - clampPoint(point: Vector2, optionalTarget?: Vector2): Vector2; - distanceToPoint(point: Vector2): number; - intersect(box: Box2): Box2; - union(box: Box2): Box2; - translate(offset: Vector2): Box2; - equals(box: Box2): boolean; - clone(): Box2; - } - - export class Box3 { - constructor(min?: Vector3, max?: Vector3); - min: Vector3; - max: Vector3; - set (min: Vector3, max: Vector3): Box3; - setFromPoints(points: Vector3[]): Box3; - setFromCenterAndSize(center: Vector3, size: number): Box3; - copy(box: Box3): Box3; - makeEmpty(): Box3; - empty(): boolean; - center(optionalTarget?: Vector3): Vector3; - size(optionalTarget?: Vector3): Vector3; - expandByPoint(point: Vector3): Box3; - expandByVector(vector: Vector3): Box3; - expandByScalar(scalar: number): Box3; - containsPoint(point: Vector3): boolean; - containsBox(box: Box3): boolean; - getParameter(point: Vector3): Vector3; - isIntersectionBox(box: Box3): boolean; - clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - distanceToPoint(point: Vector3): number; - getBoundingSphere(): Sphere; - intersect(box: Box3): Box3; - union(box: Box3): Box3; - applyMatrix4(matrix: Matrix4): Box3; - translate(offset: Vector3): Box3; - equals(box: Box3): boolean; - clone(): Box3; - } - - // Cameras //////////////////////////////////////////////////////////////////////////////////////// - - /** - * Abstract base class for cameras. This class should always be inherited when you build a new camera. - */ - export class Camera extends Object3D { - - /** - * This constructor sets following properties to the correct type: matrixWorldInverse, projectionMatrix and projectionMatrixInverse. - */ - constructor(); - - /** - * This is the inverse of matrixWorld. MatrixWorld contains the Matrix which has the world transform of the Camera. - */ - matrixWorldInverse: Matrix4; - - /** - * This is the matrix which contains the projection. - */ - projectionMatrix: Matrix4; - - /** - * This is the inverse of projectionMatrix. - */ - projectionMatrixInverse: Matrix4; - - /** - * This make the camera look at the vector position in local space. - * @param vector point to look at - */ - lookAt(vector: Vector3): void; - } - - /** - * Camera with orthographic projection - * - * @example - * var camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); - * scene.add( camera ); - * - * @see src/cameras/OrthographicCamera.js - */ - export class OrthographicCamera extends Camera { - /** - * @param left Camera frustum left plane. - * @param right Camera frustum right plane. - * @param top Camera frustum top plane. - * @param bottom Camera frustum bottom plane. - * @param near Camera frustum near plane. - * @param far Camera frustum far plane. - */ - constructor(left: number, right: number, top: number, bottom: number, near?: number, far?: number); - - /** - * Camera frustum left plane. - */ - left: number; - - /** - * Camera frustum right plane. - */ - right: number; - - /** - * Camera frustum top plane. - */ - top: number; - - /** - * Camera frustum bottom plane. - */ - bottom: number; - - /** - * Camera frustum near plane. - */ - near: number; - - /** - * Camera frustum far plane. - */ - far: number; - - /** - * Updates the camera projection matrix. Must be called after change of parameters. - */ - updateProjectionMatrix(): void; - } - - /** - * Camera with perspective projection. - * - * # example - * var camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 ); - * scene.add( camera ); - * - * @source https://github.com/mrdoob/three.js/blob/master/src/cameras/PerspectiveCamera.js - */ - export class PerspectiveCamera extends Camera { - /** - * @param fov Camera frustum vertical field of view. Default value is 50. - * @param aspect Camera frustum aspect ratio. Default value is 1. - * @param near Camera frustum near plane. Default value is 0.1. - * @param far Camera frustum far plane. Default value is 2000. - */ - constructor(fov?: number, aspect?: number, near?: number, far?: number); - - /** - * Camera frustum vertical field of view, from bottom to top of view, in degrees. - */ - fov: number; - - /** - * Camera frustum aspect ratio, window width divided by window height. - */ - aspect: number; - - /** - * Camera frustum near plane. - */ - near: number; - - /** - * Camera frustum far plane. - */ - far: number; - - /** - * Uses focal length (in mm) to estimate and set FOV 35mm (fullframe) camera is used if frame size is not specified. - * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html - * @param focalLength focal length - * @param frameHeight frame size. Default value is 24. - */ - setLens(focalLength: number, frameHeight?: number): void; - - /** - * Sets an offset in a larger frustum. This is useful for multi-window or multi-monitor/multi-machine setups. - * For example, if you have 3x2 monitors and each monitor is 1920x1080 and the monitors are in grid like this: - * - * +---+---+---+ - * | A | B | C | - * +---+---+---+ - * | D | E | F | - * +---+---+---+ - * - * then for each monitor you would call it like this: - * - * var w = 1920; - * var h = 1080; - * var fullWidth = w * 3; - * var fullHeight = h * 2; - * - * // A - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * // B - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * // C - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * // D - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * // E - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * // F - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); Note there is no reason monitors have to be the same size or in a grid. - * - * @param fullWidth full width of multiview setup - * @param fullHeight full height of multiview setup - * @param x horizontal offset of subcamera - * @param y vertical offset of subcamera - * @param width width of subcamera - * @param height height of subcamera - */ - setViewOffset(fullWidth: number, fullHeight: number, x: number, y: number, width: number, height: number): void; - - /** - * Updates the camera projection matrix. Must be called after change of parameters. - */ - updateProjectionMatrix(): void; - } - - // Lights ////////////////////////////////////////////////////////////////////////////////// - - /** - * Abstract base class for lights. - */ - export class Light extends Object3D { - constructor(hex?: number); - color: Color; - } - - /** - * This light's color gets applied to all the objects in the scene globally. - * - * # example - * var light = new THREE.AmbientLight( 0x404040 ); // soft white light - * scene.add( light ); - * - * @source https://github.com/mrdoob/three.js/blob/master/src/lights/AmbientLight.js - */ - export class AmbientLight extends Light { - /** - * This creates a Ambientlight with a color. - * @param hex Numeric value of the RGB component of the color. - */ - constructor(hex?: number); - } - - export class AreaLight{ - constructor(hex: number, intensity?: number); - normal: Vector3; - right: Vector3; - intensity: number; - width: number; - height: number; - constantAttenuation: number; - linearAttenuation: number; - quadraticAttenuation: number; - } - - /** - * Affects objects using MeshLambertMaterial or MeshPhongMaterial. - * - * @example - * // White directional light at half intensity shining from the top. - * var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); - * directionalLight.position.set( 0, 1, 0 ); - * scene.add( directionalLight ); - * - * @see src/lights/DirectionalLight.js - */ - export class DirectionalLight extends Light { - - constructor(hex?: number, intensity?: number); - - /** - * Direction of the light is normalized vector from position to (0,0,0). - * Default — new THREE.Vector3(). - */ - position: Vector3; - - /** - * Target used for shadow camera orientation. - */ - target: Object3D; - - /** - * Light's intensity. - * Default — 1.0. - */ - intensity: number; - - /** - * If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. - * Default — false. - */ - castShadow: boolean; - - /** - * If set to true light will only cast shadow but not contribute any lighting (as if intensity was 0 but cheaper to compute). - * Default — false. - */ - onlyShadow: boolean; - - /** - * Orthographic shadow camera frustum parameter. - * Default — 50. - */ - shadowCameraNear: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — 5000. - */ - shadowCameraFar: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — -500. - */ - shadowCameraLeft: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — 500. - */ - shadowCameraRight: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — 500. - */ - shadowCameraTop: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — -500. - */ - shadowCameraBottom: number; - - /** - * Show debug shadow camera frustum. - * Default — false. - */ - shadowCameraVisible: boolean; - - /** - * Shadow map bias. - * Default — 0. - */ - shadowBias: number; - - /** - * Darkness of shadow casted by this light (from 0 to 1). - * Default — 0.5. - */ - shadowDarkness: number; - - /** - * Shadow map texture width in pixels. - * Default — 512. - */ - shadowMapWidth: number; - - /** - * Shadow map texture height in pixels. - * Default — 512. - */ - shadowMapHeight: number; - - /** - * Default — false. - */ - shadowCascade: boolean; - - /** - * Three.Vector3( 0, 0, -1000 ). - */ - shadowCascadeOffset: Vector3; - - /** - * Default — 2. - */ - shadowCascadeCount: number; - - /** - * Default — [ 0, 0, 0 ]. - */ - shadowCascadeBias: number[]; - - /** - * Default — [ 512, 512, 512 ]. - */ - shadowCascadeWidth: number[]; - - /** - * Default — [ 512, 512, 512 ]. - */ - shadowCascadeHeight: number[]; - - /** - * Default — [ -1.000, 0.990, 0.998 ]. - */ - shadowCascadeNearZ: number[]; - - /** - * Default — [ 0.990, 0.998, 1.000 ]. - */ - shadowCascadeFarZ: number[]; - - /** - * Default — [ ]. - */ - shadowCascadeArray: DirectionalLight[]; - - /** - * Default — null. - */ - shadowMap: RenderTarget; - - /** - * Default — null. - */ - shadowMapSize: number; - - /** - * Default — null. - */ - shadowCamera: Camera; - - /** - * Default — null. - */ - shadowMatrix: Matrix4; - } - - export class HemisphereLight extends Light { - constructor(skyColorHex?: number, groundColorHex?: number, intensity?: number); - groundColor: Color; - position: Vector3; - intensity: number; - } - - /** - * Affects objects using {@link MeshLambertMaterial} or {@link MeshPhongMaterial}. - * - * @example - * var light = new THREE.PointLight( 0xff0000, 1, 100 ); - * light.position.set( 50, 50, 50 ); - * scene.add( light ); - */ - export class PointLight extends Light { - constructor(hex?: number, intensity?: number, distance?: number); - - /** - * Light's position. - * Default — new THREE.Vector3(). - */ - position: Vector3; - - /* - * Light's intensity. - * Default - 1.0. - */ - intensity: number; - - /** - * If non-zero, light will attenuate linearly from maximum intensity at light position down to zero at distance. - * Default — 0.0. - */ - distance: number; - } - - /** - * A point light that can cast shadow in one direction. - * - * @example - * // white spotlight shining from the side, casting shadow - * var spotLight = new THREE.SpotLight( 0xffffff ); - * spotLight.position.set( 100, 1000, 100 ); - * spotLight.castShadow = true; - * spotLight.shadowMapWidth = 1024; - * spotLight.shadowMapHeight = 1024; - * spotLight.shadowCameraNear = 500; - * spotLight.shadowCameraFar = 4000; - * spotLight.shadowCameraFov = 30; - * scene.add( spotLight ); - */ - export class SpotLight extends Light { - constructor(hex?: number, intensity?: number, distance?: number, angle?: number, exponent?: number); - - /** - * Light's position. - * Default — new THREE.Vector3(). - */ - position: Vector3; - - /** - * Spotlight focus points at target.position. - * Default position — (0,0,0). - */ - target: Object3D; - - /** - * Light's intensity. - * Default — 1.0. - */ - intensity: number; - - /** - * If non-zero, light will attenuate linearly from maximum intensity at light position down to zero at distance. - * Default — 0.0. - */ - distance: number; - - /* - * Maximum extent of the spotlight, in radians, from its direction. - * Default — Math.PI/2. - */ - angle: number; - - /** - * Rapidity of the falloff of light from its target direction. - * Default — 10.0. - */ - exponent: number; - - /** - * If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. - * Default — false. - */ - castShadow: boolean; - - /** - * If set to true light will only cast shadow but not contribute any lighting (as if intensity was 0 but cheaper to compute). - * Default — false. - */ - onlyShadow: boolean; - - /** - * Perspective shadow camera frustum near parameter. - * Default — 50. - */ - shadowCameraNear: number; - - /** - * Perspective shadow camera frustum far parameter. - * Default — 5000. - */ - shadowCameraFar: number; - - /** - * Perspective shadow camera frustum field of view parameter. - * Default — 50. - */ - shadowCameraFov: number; - - /** - * Show debug shadow camera frustum. - * Default — false. - */ - shadowCameraVisible: boolean; - - /** - * Shadow map bias. - * Default — 0. - */ - shadowBias: number; - - /** - * Darkness of shadow casted by this light (from 0 to 1). - * Default — 0.5. - */ - shadowDarkness: number; - - /** - * Shadow map texture width in pixels. - * Default — 512. - */ - shadowMapWidth: number; - - /** - * Shadow map texture height in pixels. - * Default — 512. - */ - shadowMapHeight: number; - - shadowMap: RenderTarget; - shadowMapSize: Vector2; - shadowCamera: Camera; - shadowMatrix: Matrix4; - } - - // Loaders ////////////////////////////////////////////////////////////////////////////////// - - export interface Progress { - total: number; - loaded: number; - } - - /** - * Base class for implementing loaders. - * - * Events: - * load - * Dispatched when the image has completed loading - * content — loaded image - * - * error - * - * Dispatched when the image can't be loaded - * message — error message - */ - export class Loader { - constructor(showStatus?: boolean); - - /** - * If true, show loading status in the statusDomElement. - */ - showStatus: boolean; - - /** - * This is the recipient of status messages. - */ - statusDomElement: HTMLElement; - - /** - * Will be called when load starts. - * The default is a function with empty body. - */ - onLoadStart: () => void; - - /** - * Will be called while load progresses. - * The default is a function with empty body. - */ - onLoadProgress: () => void; - - /** - * Will be called when load completes. - * The default is a function with empty body. - */ - onLoadComplete: () => void; - - /** - * default — null. - * If set, assigns the crossOrigin attribute of the image to the value of crossOrigin, prior to starting the load. - */ - crossOrigin: string; - addStatusElement(): HTMLElement; - updateProgress(progress: Progress): void; - extractUrlBase(url: string): string; - initMaterials(materials: Material[], texturePath: string): Material[]; - needsTangents(materials: Material[]): boolean; - createMaterial(m: Material, texturePath: string): boolean; - } - - /** - * A loader for loading an image. - * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. - */ - export class ImageLoader extends EventDispatcher { - constructor(); - crossOrigin: string; - - /** - * Begin loading from url - * @param url - */ - load(url: string, image?: HTMLImageElement): void; - } - - - /** - * A loader for loading objects in JSON format. - */ - export class JSONLoader extends Loader { - constructor(showStatus?: boolean); - withCredentials: boolean; - - /** - * @param url - * @param callback. This function will be called with the loaded model as an instance of geometry when the load is completed. - * @param texturePath If not specified, textures will be assumed to be in the same folder as the Javascript model file. - */ - load(url: string, callback: (geometry: Geometry, materials: Material[]) => void , texturePath?: string): void; - - loadAjaxJSON(context: JSONLoader, url: string, callback: (geometry: Geometry, materials: Material[]) => void , texturePath?: string, callbackProgress?: (progress: Progress) => void ): void; - createModel(json: any, callback: (geometry: Geometry, materials: Material[]) => void , texturePath?: string): void; - } - - export class LoadingMonitor extends EventDispatcher { - constructor(); - add(loader: Loader): void; - } - - interface SceneLoaderResult{ - scene: Scene; - geometries: {[id:string]:Geometry;}; - face_materials: {[id:string]:Material;}; - materials: {[id:string]:Material;}; - textures: {[id:string]:Texture;}; - objects: {[id:string]:Object3D;}; - cameras: {[id:string]:Camera;}; - lights: {[id:string]:Light;}; - fogs: {[id:string]:IFog;}; - empties: {[id:string]:any;}; - groups: {[id:string]:any;}; - } - - interface SceneLoaderProgress{ - totalModels: number; - totalTextures: number; - loadedModels: number; - loadedTextures: number; - } - - /** - * A loader for loading a complete scene out of a JSON file. - */ - export class SceneLoader { - constructor(); - - /** - * Will be called when load starts. - * The default is a function with empty body. - */ - onLoadStart: () => void; - - /** - * Will be called while load progresses. - * The default is a function with empty body. - */ - onLoadProgress: () => void; - - /** - * Will be called when each element in the scene completes loading. - * The default is a function with empty body. - */ - onLoadComplete: () => void; - - /** - * Will be called when load completes. - * The default is a function with empty body. - */ - callbackSync: (result: SceneLoaderResult) => void; - - /** - * Will be called as load progresses. - * The default is a function with empty body. - */ - callbackProgress: (progress: SceneLoaderProgress, result: SceneLoaderResult) => void; - - geometryHandlerMap: any; - hierarchyHandlerMap: any; - - - /** - * @param url - * @param callbackFinished This function will be called with the loaded model as an instance of scene when the load is completed. - */ - load(url: string, callbackFinished: (scene: Scene) => void ): void; - - addGeometryHandler(typeID: string, loaderClass: Object): void; - - addHierarchyHandler(typeID: string, loaderClass: Object): void; - - static parse(json: any, callbackFinished:(result: SceneLoaderResult)=>void, url: string): void; - } - - /** - * Class for loading a texture. - * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. - */ - export class TextureLoader extends EventDispatcher { - constructor(); - - /** - * Begin loading from url - * - * @param url - */ - load(url: string): void; - } - - // Materials ////////////////////////////////////////////////////////////////////////////////// - - /** - * Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use a different renderer. - */ - export class Material { - constructor(); - - /** - * Unique number of this material instance. - */ - id: number; - - /** - * Material name. Default is an empty string. - */ - name: string; - - /** - * Opacity. Default is 1. - */ - opacity: number; - - /** - * Defines whether this material is transparent. This has an effect on rendering, as transparent objects need an special treatment, and are rendered after the opaque (i.e. non transparent) objects. For a working example of this behaviour, check the {@link WebGLRenderer} code. - * Default is false. - */ - transparent: boolean; - - /** - * Which blending to use when displaying objects with this material. Default is {@link NormalBlending}. - */ - blending: Blending; - - /** - * Blending source. It's one of the blending mode constants defined in Three.js. Default is {@link SrcAlphaFactor}. - */ - blendSrc: BlendingDstFactor; - - /** - * Blending destination. It's one of the blending mode constants defined in Three.js. Default is {@link OneMinusSrcAlphaFactor}. - */ - blendDst: BlendingSrcFactor; - - /** - * Blending equation to use when applying blending. It's one of the constants defined in Three.js. Default is AddEquation. - */ - blendEquation: BlendingEquation; - - /** - * Whether to have depth test enabled when rendering this material. Default is true. - */ - depthTest: boolean; - - /** - * Whether rendering this material has any effect on the depth buffer. Default is true. - * When drawing 2D overlays it can be useful to disable the depth writing in order to layer several things together without creating z-index artifacts. - */ - depthWrite: boolean; - - /** - * Whether to use polygon offset. Default is false. This corresponds to the POLYGON_OFFSET_FILL WebGL feature. - */ - polygonOffset: boolean; - - /** - * Sets the polygon offset factor. Default is 0. - */ - polygonOffsetFactor: number; - - /** - * Sets the polygon offset units. Default is 0. - */ - polygonOffsetUnits: number; - - /** - * Sets the alpha value to be used when running an alpha test. Default is 0. - */ - alphaTest: number; - - /** - * Enables/disables overdraw. If enabled, polygons are drawn slightly bigger in order to fix antialiasing gaps when using the CanvasRenderer. Default is false. - */ - overdraw: boolean; - - /** - * Defines whether this material is visible. Default is true. - */ - visible: boolean; - - /** - * Defines which of the face sides will be rendered - front, back or both. - * Default is THREE.FrontSide. Other options are THREE.BackSide and THREE.DoubleSide. - */ - side: Side; - - /** - * Specifies that the material needs to be updated, WebGL wise. Set it to true if you made changes that need to be reflected in WebGL. - * This property is automatically set to true when instancing a new material. - */ - needsUpdate: boolean; - - clone(): Material; - - dispose(): void; - } - - var MaterialLibrary: Material[]; - var MaterialIdCount: number; - - export interface LineBasicMaterialParameters { - color?: number; - opacity?: number; - blending?: Blending; - depthTest?: boolean; - linewidth?: number; - linecap?: string; - linejoin?: string; - vertexColors?: Colors; - fog?: boolean; - } - - export class LineBasicMaterial extends Material { - constructor(parameters?: LineBasicMaterialParameters); - color: Color; - linewidth: number; - linecap: string; - linejoin: string; - vertexColors: boolean; - fog: boolean; - clone(): LineBasicMaterial; - } - - export interface LineDashedMaterialParameters { - color?: number; - opacity?: number; - blending?: Blending; - depthTest?: boolean; - linewidth?: number; - scale?: number; - dashSize?: number; - gapSize?: number; - vertexColors?: number; - fog?: boolean; - } - - export class LineDashedMaterial extends Material { - constructor(parameters?: LineDashedMaterialParameters); - color: Color; - linewidth: number; - scale: number; - dashSize: number; - gapSize: number; - vertexColors: boolean; - fog: boolean; - clone(): LineDashedMaterial; - } - - - /** - * parameters is an object with one or more properties defining the material's appearance. - */ - export interface MeshBasicMaterialParameters { - /** - * geometry color in hexadecimal. Default is 0xffffff. - */ - color?: number; - opacity?: number; - map?: Texture; - /** - * Default is null. - */ - lightMap?: Texture; - /** - * Default is null. - */ - specularMap?: Texture; - /** - * Default is null. - */ - envMap?: Texture; - combine?: Combine; - reflectivity?: number; - refractionRatio?: number; - /** - * Define shading type. Default is THREE.SmoothShading. - */ - shading?: Shading; - blending?: Blending; - depthTest?: boolean; - /** - * render geometry as wireframe. Default is false. - */ - wireframe?: boolean; - /** - * Line thickness. Default is 1. - */ - wireframeLinewidth?: number; - /** - * Define whether the material uses vertex colors, or not. Default is false. - */ - vertexColors?: Colors; - /** - * Default is false. - */ - skinning?: boolean; - /** - * Default is false. - */ - morphTargets?: boolean; - /** - * Define whether the material color is affected by global fog settings. Default is true. - */ - fog?: boolean; - } - - export class MeshBasicMaterial extends Material { - constructor(parameters?: MeshBasicMaterialParameters); - color: Color; - map: Texture; - lightMap: Texture; - specularMap: Texture; - envMap: Texture; - combine: Combine; - reflectivity: number; - refractionRatio: number; - fog: boolean; - shading: Shading; - wireframe: boolean; - wireframeLinewidth: number; - wireframeLinecap: string; - wireframeLinejoin: string; - vertexColors: Colors; - skinning: boolean; - morphTargets: boolean; - clone(): MeshBasicMaterial; - } - - export interface MeshDepthMaterialParameters { - opacity?: number; - blending?: Blending; - depthTest?: boolean; - wireframe?: boolean; - wireframeLinewidth?: number; - } - - export class MeshDepthMaterial extends Material { - constructor(parameters?: MeshDepthMaterialParameters); - wireframe: boolean; - wireframeLinewidth: number; - clone(): MeshDepthMaterial; - } - - export class MeshFaceMaterial extends Material { - constructor(materials?: Material[]); - materials: Material[]; - clone(): MeshFaceMaterial; - } - - export interface MeshLambertMaterialParameters { - color?: number; - ambient?: number; - emissive?: number; - opacity?: number; - map?: Texture; - lightMap?: Texture; - specularMap?: Texture; - envMap?: Texture; - combine?: Combine; - reflectivity?: number; - refractionRatio?: number; - shading?: Shading; - blending?: Blending; - depthTest?: boolean; - wireframe?: boolean; - wireframeLinewidth?: number; - vertexColors?: Colors; - skinning?: boolean; - morphTargets?: boolean; - morphNormals?: boolean; - fog?: boolean; - } - - export class MeshLambertMaterial extends Material { - constructor(parameters?: MeshLambertMaterialParameters); - color: Color; - ambient: Color; - emissive: Color; - wrapAround: boolean; - wrapRGB: Vector3; - map: Texture; - lightMap: Texture; - specularMap: Texture; - envMap: Texture; - combine: Combine; - reflectivity: number; - refractionRatio: number; - fog: boolean; - shading: Shading; - wireframe: boolean; - wireframeLinewidth: number; - wireframeLinecap: string; - wireframeLinejoin: string; - vertexColors: Colors; - skinning: boolean; - morphTargets: boolean; - morphNormals: boolean; - clone(): MeshLambertMaterial; - } - - export interface MeshNormalMaterialParameters { - opacity?: number; - shading?: Shading; - blending?: Blending; - depthTest?: boolean; - wireframe?: boolean; - wireframeLinewidth?: number; - } - - export class MeshNormalMaterial extends Material { - constructor(parameters?: MeshNormalMaterialParameters); - shading: Shading; - wireframe: boolean; - wireframeLinewidth: number; - clone(): MeshNormalMaterial; - } - - export interface MeshPhongMaterialParameters { - color?: number; - ambient?: number; - emissive?: number; - specular?: number; - shininess?: number; - opacity?: number; - map?: Texture; - lightMap?: Texture; - bumpMap?: Texture; - bumpScale?: number; - normalMap?: Texture; - normalScale?: Vector2; - specularMap?: Texture; - envMap?: Texture; - combine?: Combine; - reflectivity?: number; - refractionRatio?: number; - shading?: Shading; - blending?: Blending; - depthTest?: boolean; - wireframe?: boolean; - wireframeLinewidth?: number; - vertexColors?: Colors; - skinning?: boolean; - morphTargets?: boolean; - morphNormals?: boolean; - fog?: boolean; - } - - export class MeshPhongMaterial extends Material { - constructor(parameters?: MeshPhongMaterialParameters); - color: Color; // diffuse - ambient: Color; - emissive: Color; - specular: Color; - shininess: number; - metal: boolean; - perPixel: boolean; - wrapAround: boolean; - wrapRGB: Vector3; - map: Texture; - lightMap: Texture; - bumpMap: Texture; - bumpScale: number; - normalMap: Texture; - normalScale: Vector2; - specularMap: Texture; - envMap: Texture; - combine: Combine; - reflectivity: number; - refractionRatio: number; - fog: boolean; - shading: Shading; - wireframe: boolean; - wireframeLinewidth: number; - wireframeLinecap: string; - wireframeLinejoin: string; - vertexColors: Colors; - skinning: boolean; - morphTargets: boolean; - morphNormals: boolean; - clone(): MeshPhongMaterial; - } - - export interface ParticleBasicMaterialParameters { - color?: number; - opacity?: number; - map?: Texture; - size?: number; - blending?: Blending; - depthTest?: boolean; - vertexColors?: boolean; - fog?: boolean; - } - - export class ParticleBasicMaterial extends Material { - constructor(parameters?: ParticleBasicMaterialParameters); - color: Color; - map: Texture; - size: number; - sizeAttenuation: boolean; - vertexColors: boolean; - fog: boolean; - clone(): ParticleBasicMaterial; - } - - export interface ParticleCanvasMaterialParameters { - color?: number; - program?: (context: CanvasRenderingContext2D, color: Color) => void; - opacity?: number; - blending?: Blending; - } - - export class ParticleCanvasMaterial extends Material { - constructor(parameters?: ParticleCanvasMaterialParameters); - color: Color; - program: (context: CanvasRenderingContext2D, color: Color) => void; - clone(): ParticleCanvasMaterial; - } - - export class ParticleDOMMaterial extends Material { - constructor(element: HTMLElement); - clone(): ParticleDOMMaterial; - } - - - - - export interface Uniforms { - [name: string]: { type: string; value: any; }; - //[name:string]:{type:UniformType;value:Object;}; - color?: { type: string; value: THREE.Color; }; - } - - export interface ShaderMaterialParameters { - fragmentShader?: string; - vertexShader?: string; - uniforms?: Uniforms; - defines?: { [label: string]: string; }; - shading?: Shading; - blending?: Blending; - depthTest?: boolean; - wireframe?: boolean; - wireframeLinewidth?: number; - lights?: boolean; - vertexColors?: Colors; - skinning?: boolean; - morphTargets?: boolean; - morphNormals?: boolean; - fog?: boolean; - } - - export class ShaderMaterial extends Material { - constructor(parameters?: ShaderMaterialParameters); - fragmentShader: string; - vertexShader: string; - uniforms: Uniforms; - defines: { [label: string]: string; }; - attributes: { [name: string]: Object; }; - shading: Shading; - wireframe: boolean; - wireframeLinewidth: number; - fog: boolean; - lights: boolean; - vertexColors: Colors; - skinning: boolean; - morphTargets: boolean; - morphNormals: boolean; - clone(): ShaderMaterial; - } - - // Objects ////////////////////////////////////////////////////////////////////////////////// - - export class Bone extends Object3D { - constructor(belongsToSkin: SkinnedMesh); - skin: SkinnedMesh; - skinMatrix: Matrix4; - update(parentSkinMatrix?: Matrix4, forceUpdate?: boolean): void; - } - - export class Line extends Object3D { - constructor(geometry?: Geometry, material?: LineDashedMaterial, type?: number); - constructor(geometry?: Geometry, material?: LineBasicMaterial, type?: number); - constructor(geometry?: Geometry, material?: ShaderMaterial, type?: number); - constructor(geometry?: BufferGeometry, material?: LineDashedMaterial, type?: number); - constructor(geometry?: BufferGeometry, material?: LineBasicMaterial, type?: number); - constructor(geometry?: BufferGeometry, material?: ShaderMaterial, type?: number); - geometry: Geometry; - material: Material; - type: LineType; - clone(object?: Line): Line; - } - - enum LineType{} - var LineStrip: LineType; - var LinePieces: LineType; - - export class LOD extends Object3D { - constructor(); - LODs: Object3D[]; - addLevel(object3D: Object3D, visibleAtDistance?: number): void; - update(camera: Camera): void; - clone(): LOD; - } - - export class Mesh extends Object3D { - constructor(geometry?: Geometry, material?: MeshBasicMaterial); - constructor(geometry?: Geometry, material?: MeshDepthMaterial); - constructor(geometry?: Geometry, material?: MeshFaceMaterial); - constructor(geometry?: Geometry, material?: MeshLambertMaterial); - constructor(geometry?: Geometry, material?: MeshNormalMaterial); - constructor(geometry?: Geometry, material?: MeshPhongMaterial); - constructor(geometry?: Geometry, material?: ShaderMaterial); - - constructor(geometry?: BufferGeometry , material?: MeshBasicMaterial); - constructor(geometry?: BufferGeometry , material?: MeshDepthMaterial); - constructor(geometry?: BufferGeometry , material?: MeshFaceMaterial); - constructor(geometry?: BufferGeometry , material?: MeshLambertMaterial); - constructor(geometry?: BufferGeometry , material?: MeshNormalMaterial); - constructor(geometry?: BufferGeometry , material?: MeshPhongMaterial); - constructor(geometry?: BufferGeometry , material?: ShaderMaterial); - - geometry: Geometry; - material: Material; - morphTargetBase: number; - morphTargetForcedOrder: number; - morphTargetInfluences: number[]; - morphTargetDictionary: { [key: string]: number; }; - updateMorphTargets(): void; - getMorphTargetIndexByName(name: string): number; - clone(object?: Mesh): Mesh; - } - - export class MorphAnimMesh extends Mesh { - constructor(geometry?: Geometry, material?: MeshBasicMaterial); - constructor(geometry?: Geometry, material?: MeshDepthMaterial); - constructor(geometry?: Geometry, material?: MeshFaceMaterial); - constructor(geometry?: Geometry, material?: MeshLambertMaterial); - constructor(geometry?: Geometry, material?: MeshNormalMaterial); - constructor(geometry?: Geometry, material?: MeshPhongMaterial); - constructor(geometry?: Geometry, material?: ShaderMaterial); - duration: number; // milliseconds - mirroredLoop: boolean; - time: number; - lastKeyframe: number; - currentKeyframe: number; - direction: number; - directionBackwards: boolean; - setFrameRange(start: number, end: number): void; - setDirectionForward(): void; - setDirectionBackward(): void; - parseAnimations(): void; - setAnimationLabel(label: string, start: number, end: number): void; - playAnimation(label: string, fps: number): void; - updateAnimation(delta: number): void; - clone(object?: MorphAnimMesh): MorphAnimMesh; - } - - export class Particle extends Object3D { - constructor(material: Material); - clone(object?: Particle): Particle; - } - - /** - * A class for displaying particles in the form of variable size points. For example, if using the WebGLRenderer, the particles are displayed using GL_POINTS. - * - * @see src/objects/ParticleSystem.js - */ - export class ParticleSystem extends Object3D { - - /** - * @param geometry An instance of Geometry. - * @param material An instance of Material (optional). - */ - constructor(geometry: Geometry, material?: ParticleBasicMaterial); - constructor(geometry: Geometry, material?: ParticleCanvasMaterial); - constructor(geometry: Geometry, material?: ParticleDOMMaterial); - constructor(geometry: Geometry, material?: ShaderMaterial); - constructor(geometry: BufferGeometry, material?: ParticleBasicMaterial); - constructor(geometry: BufferGeometry, material?: ParticleCanvasMaterial); - constructor(geometry: BufferGeometry, material?: ParticleDOMMaterial); - constructor(geometry: BufferGeometry, material?: ShaderMaterial); - - /** - * An instance of Geometry, where each vertex designates the position of a particle in the system. - */ - geometry: Geometry; - - /** - * An instance of Material, defining the object's appearance. Default is a ParticleBasicMaterial with randomised colour. - */ - material: Material; - - /** - * Specifies whether the particle system will be culled if it's outside the camera's frustum. By default this is set to false. - */ - sortParticles: boolean; - - clone(object?: ParticleSystem): ParticleSystem; - } - - export class Ribbon extends Object3D { - constructor(geometry: Geometry, material: Material); - geometry: Geometry; - material: Material; - clone(object?: Ribbon): Ribbon; - } - - export class SkinnedMesh extends Mesh { - constructor(geometry?: Geometry, material?: MeshBasicMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry, material?: MeshDepthMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry, material?: MeshFaceMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry, material?: MeshLambertMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry, material?: MeshNormalMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry, material?: MeshPhongMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry, material?: ShaderMaterial, useVertexTexture?: boolean); - useVertexTexture: boolean; - identityMatrix: Matrix4; - bones: Bone[]; - boneMatrices: Float32Array; - boneTextureWidth: number; - boneTextureHeight: number; - boneTexture: DataTexture; - addBone(bone?: Bone): Bone; - updateMatrixWorld(force?: boolean): void; - pose(): void; - clone(object?: SkinnedMesh): SkinnedMesh; - static offsetMatrix: Matrix4; - } - - export interface SpriteParameters { - color?: Color; - map?: Texture; - blending?: Blending; - blendSrc?: BlendingSrcFactor; - blendDst?: BlendingDstFactor; - blendEquation?: BlendingEquation; - useScreenCoordinates?: boolean; - mergeWith3D?: boolean; - affectedByDistance?: boolean; - alignment?: Vector2; - fog?: boolean; - uvOffset?: Vector2; - uvScale?: Vector2; - depthTest?: boolean; - sizeAttenuation?: boolean; - scaleByViewport?: boolean; - } - - export class SpriteMaterial extends Material { - constructor(parameters?: SpriteParameters); - color: Color; - map: Texture; - blending: Blending; - blendEquation: BlendingEquation; - useScreenCoordinates: boolean; - scaleByViewport: boolean; - alignment: Vector2; - fog: boolean; - uvOffset: Vector2; - uvScale: Vector2; - depthTest: boolean; - sizeAttenuation: boolean; - clone(): SpriteMaterial; - } - - export class Sprite extends Object3D { - constructor(material?: SpriteMaterial); - updateMatrix(): void; - clone(object?: Sprite): Sprite; - } - export class SpriteAlignment { - static topLeft: Vector2; - static topCenter: Vector2; - static topRight: Vector2; - static centerLeft: Vector2; - static center: Vector2; - static centerRight: Vector2; - static bottomLeft: Vector2; - static bottomCenter: Vector2; - static bottomRight: Vector2; - } - - // Renderers ////////////////////////////////////////////////////////////////////////////////// - - export interface Renderer { - render(scene: Scene, camera: Camera): void; - } - - export interface CanvasRendererParameters { - canvas?: HTMLCanvasElement; - devicePixelRatio?: number; - } - - export class CanvasRenderer implements Renderer { - constructor(parameters?: CanvasRendererParameters); - domElement: HTMLCanvasElement; - autoClear: boolean; - sortObjects: boolean; - sortElements: boolean; - devicePixelRatio: number; - info: { render: { vertices: number; faces: number; }; }; - setSize(width: number, height: number): void; - setClearColor(color: Color, opacity?: number): void; - setClearColorHex(hex: number, opacity?: number): void; - getMaxAnisotropy(): number; - clear(): void; - render(scene: Scene, camera: Camera): void; - } - - export interface ShaderChunk { - [name: string]: string; - fog_pars_fragment: string; - fog_fragment: string; - envmap_pars_fragment: string; - envmap_fragment: string; - envmap_pars_vertex: string; - worldpos_vertex: string; - envmap_vertex: string; - map_particle_pars_fragment: string; - map_particle_fragment: string; - map_pars_vertex: string; - map_pars_fragment: string; - map_vertex: string; - map_fragment: string; - lightmap_pars_fragment: string; - lightmap_pars_vertex: string; - lightmap_fragment: string; - lightmap_vertex: string; - bumpmap_pars_fragment: string; - normalmap_pars_fragment: string; - specularmap_pars_fragment: string; - specularmap_fragment: string; - lights_lambert_pars_vertex: string; - lights_lambert_vertex: string; - lights_phong_pars_vertex: string; - lights_phong_vertex: string; - lights_phong_pars_fragment: string; - lights_phong_fragment: string; - color_pars_fragment: string; - color_fragment: string; - color_pars_vertex: string; - color_vertex: string; - skinning_pars_vertex: string; - skinbase_vertex: string; - skinning_vertex: string; - morphtarget_pars_vertex: string; - morphtarget_vertex: string; - default_vertex: string; - morphnormal_vertex: string; - skinnormal_vertex: string; - defaultnormal_vertex: string; - shadowmap_pars_fragment: string; - shadowmap_fragment: string; - shadowmap_pars_vertex: string; - shadowmap_vertex: string; - alphatest_fragment: string; - linear_to_gamma_fragment: string; - } - - export var ShaderChunk: ShaderChunk; - - export interface RendererPlugin { - init(renderer: WebGLRenderer): void; - render(scene: Scene, camera: Camera, currentWidth: number, currentHeight: number): void; - } - - export interface WebGLRendererParameters { - /** - * A Canvas where the renderer draws its output. - */ - canvas?: HTMLCanvasElement; - - /** - * shader precision. Can be "highp", "mediump" or "lowp". - */ - precision?: string; - - /** - * default is true. - */ - alpha?: boolean; - - /** - * default is true. - */ - premultipliedAlpha?: boolean; - - /** - * default is false. - */ - antialias?: boolean; - - /** - * default is true. - */ - stencil?: boolean; - - /** - * default is false. - */ - preserveDrawingBuffer?: boolean; - - /** - * default is 0x000000. - */ - clearColor?: number; - - /** - * default is 0. - */ - clearAlpha?: number; - - devicePixelRatio?: number; - } - - - /** - * The WebGL renderer displays your beautifully crafted scenes using WebGL, if your device supports it. - * This renderer has way better performance than CanvasRenderer. - * - * @see src/renderers/WebGLRenderer.js - */ - export class WebGLRenderer implements Renderer { - /** - * parameters is an optional object with properties defining the renderer's behaviour. The constructor also accepts no parameters at all. In all cases, it will assume sane defaults when parameters are missing. - */ - constructor(parameters?: WebGLRendererParameters); - - /** - * A Canvas where the renderer draws its output. - * This is automatically created by the renderer in the constructor (if not provided already); you just need to add it to your page. - */ - domElement: HTMLCanvasElement; - - /** - * The HTML5 Canvas's 'webgl' context obtained from the canvas where the renderer will draw. - */ - // If you are using three.d.ts with other complete definitions of webgl, context:WebGLRenderingContext is suitable. - //context:WebGLRenderingContext; - context: any; - - /** - * Defines whether the renderer should automatically clear its output before rendering. - */ - autoClear: boolean; - - /** - * If autoClear is true, defines whether the renderer should clear the color buffer. Default is true. - */ - autoClearColor: boolean; - - /** - * If autoClear is true, defines whether the renderer should clear the depth buffer. Default is true. - */ - autoClearDepth: boolean; - - /** - * If autoClear is true, defines whether the renderer should clear the stencil buffer. Default is true. - */ - autoClearStencil: boolean; - - /** - * Defines whether the renderer should sort objects. Default is true. - */ - sortObjects: boolean; - - /** - * Defines whether the renderer should auto update objects. Default is true. - */ - autoUpdateObjects: boolean; - - /** - * Defines whether the renderer should auto update the scene. Default is true. - */ - autoUpdateScene: boolean; - - /** - * Default is false. - */ - gammaInput: boolean; - - /** - * Default is false. - */ - gammaOutput: boolean; - - /** - * Default is false. - */ - physicallyBasedShading: boolean; - - /** - * Default is false. - */ - shadowMapEnabled: boolean; - - /** - * Default is true. - */ - shadowMapAutoUpdate: boolean; - - /** - * Defines shadow map type (unfiltered, percentage close filtering, percentage close filtering with bilinear filtering in shader) - * Options are THREE.BasicShadowMap, THREE.PCFShadowMap, THREE.PCFSoftShadowMap. Default is THREE.PCFShadowMap. - */ - shadowMapType: ShadowMapType; - - shadowMapSoft: boolean; - - /** - * Default is true - */ - shadowMapCullFace: CullFace; - - /** - * Default is false. - */ - shadowMapDebug: boolean; - - /** - * Default is false. - */ - shadowMapCascade: boolean; - - /** - * Default is 8. - */ - maxMorphTargets: number; - - /** - * Default is 4. - */ - maxMorphNormals: number; - - /** - * Default is true. - */ - autoScaleCubemaps: boolean; - - /** - * An array with render plugins to be applied before rendering. - * Default is an empty array, or []. - */ - renderPluginsPre: RendererPlugin[]; - - /** - * An array with render plugins to be applied after rendering. - * Default is an empty array, or []. - */ - renderPluginsPost: RendererPlugin[]; - - devicePixelRatio: number; - - /** - * An object with a series of statistical information about the graphics board memory and the rendering process. Useful for debugging or just for the sake of curiosity. The object contains the following fields: - */ - info: { - memory: { - programs: number; - geometries: number; - textures: number; - }; - render: { - calls: number; - vertices: number; - faces: number; - points: number; - }; - }; - - /** - * Return the WebGL context. - */ - getContext(): WebGLRenderingContext; - - /** - * Return a Boolean true if the context supports vertex textures. - */ - supportsVertexTextures(): boolean; - - getMaxAnisotropy(): number; - - /** - * Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0). - */ - setSize(width: number, height: number): void; - - /** - * Sets the viewport to render from (x, y) to (x + width, y + height). - */ - setViewport(x?: number, y?: number, width?: number, height?: number): void; - - /** - * Sets the scissor area from (x, y) to (x + width, y + height). - */ - setScissor(x: number, y: number, width: number, height: number): void; - - /** - * Enable the scissor test. When this is enabled, only the pixels within the defined scissor area will be affected by further renderer actions. - */ - enableScissorTest(enable: boolean): void; - - /** - * Sets the clear color, using hex for the color and alpha for the opacity. - * - * @example - * // Creates a renderer with black background - * var renderer = new THREE.WebGLRenderer(); - * renderer.setSize(200, 100); - * renderer.setClearColorHex(0x000000, 1); - */ - setClearColorHex(hex: number, alpha: number): void; - - /** - * Sets the clear color, using color for the color and alpha for the opacity. - */ - setClearColor(color: Color, alpha: number): void; - - /** - * Returns a THREE.Color instance with the current clear color. - */ - getClearColor(): Color; - - /** - * Returns a float with the current clear alpha. Ranges from 0 to 1. - */ - getClearAlpha(): number; - - /** - * Tells the renderer to clear its color, depth or stencil drawing buffer(s). - * If no parameters are passed, no buffer will be cleared. - */ - clear(color?: boolean, depth?: boolean, stencil?: boolean): void; - - /** - * Initialises the postprocessing plugin, and adds it to the renderPluginsPost array. - */ - addPostPlugin(plugin: RendererPlugin): void; - - /** - * Initialises the preprocessing plugin, and adds it to the renderPluginsPre array. - */ - addPrePlugin(plugin: RendererPlugin): void; - - deallocateObject(object: Object3D): void; - - deallocateTexture(texture: Texture): void; - - deallocateRenderTarget(renderTarget: RenderTarget): void; - - /** - * Tells the shadow map plugin to update using the passed scene and camera parameters. - * - * @param scene an instance of Scene - * @param camera — an instance of Camera - */ - updateShadowMap(scene: Scene, camera: Camera): void; - - renderBufferImmediate(object: Object3D, program: Object, material: Material): void; - - renderBufferDirect(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; - - renderBuffer(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; - - /** - * Render a scene using a camera. - * The render is done to the renderTarget (if specified) or to the canvas as usual. - * If forceClear is true, the canvas will be cleared before rendering, even if the renderer's autoClear property is false. - */ - render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; - renderImmediateObject(camera: Camera, lights: Light[], fog: Fog, material: Material, object: Object3D): void; - initWebGLObjects(scene: Scene): void; - initMaterial(material: Material, lights: Light[], fog: Fog, object: Object3D): void; - - /** - * Used for setting the gl frontFace, cullFace states in the GPU, thus enabling/disabling face culling when rendering. - * If cullFace is false, culling will be disabled. - * @param cullFace "back", "front", "front_and_back", or false. - * @param frontFace "ccw" or "cw - */ - setFaceCulling(cullFace?: string, frontFace?: FrontFaceDirection): void; - setMaterialFaces(material: Material): void; - setDepthTest(depthTest: boolean): void; - setDepthWrite(depthWrite: boolean): void; - setBlending(blending: Blending, blendEquation: BlendingEquation, blendSrc: BlendingSrcFactor, blendDst: BlendingDstFactor): void; - setTexture(texture: Texture, slot: number): void; - setRenderTarget(renderTarget: RenderTarget): void; - } - - export class WebGLRenderer2 implements Renderer { - constructor(parameters?: WebGLRendererParameters); - domElement: HTMLCanvasElement; - context: WebGLRenderingContext; - autoClear: boolean; - autoClearColor: boolean; - autoClearDepth: boolean; - autoClearStencil: boolean; - sortObjects: boolean; - autoUpdateObjects: boolean; - autoUpdateScene: boolean; - gammaInput: boolean; - gammaOutput: boolean; - physicallyBasedShading: boolean; - shadowMapEnabled: boolean; - shadowMapAutoUpdate: boolean; - shadowMapType: ShadowMapType; - shadowMapSoft: boolean; - shadowMapCullFace: CullFace; - shadowMapDebug: boolean; - shadowMapCascade: boolean; - maxMorphTargets: number; - maxMorphNormals: number; - autoScaleCubemaps: boolean; - renderPluginsPre: RendererPlugin[]; - renderPluginsPost: RendererPlugin[]; - devicePixelRatio: number; - info: { - memory: { - programs: number; - geometries: number; - textures: number; - }; - render: { - calls: number; - vertices: number; - faces: number; - points: number; - }; - }; - getContext(): WebGLRenderingContext; - supportsVertexTextures(): boolean; - getMaxAnisotropy(): number; - setSize(width: number, height: number): void; - setViewport(x?: number, y?: number, width?: number, height?: number): void; - setScissor(x: number, y: number, width: number, height: number): void; - enableScissorTest(enable: boolean): void; - setClearColorHex(hex: number, alpha: number): void; - setClearColor(color: Color, alpha: number): void; - getClearColor(): Color; - getClearAlpha(): number; - clear(color?: boolean, depth?: boolean, stencil?: boolean): void; - addPostPlugin(plugin: RendererPlugin): void; - addPrePlugin(plugin: RendererPlugin): void; - deallocateObject(object: Object3D): void; - deallocateTexture(texture: Texture): void; - deallocateRenderTarget(renderTarget: RenderTarget): void; - updateShadowMap(scene: Scene, camera: Camera): void; - renderBufferImmediate(object: Object3D, program: Object, material: Material): void; - renderBufferDirect(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; - renderBuffer(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; - render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; - renderImmediateObject(camera: Camera, lights: Light[], fog: Fog, material: Material, object: Object3D): void; - initWebGLObjects(scene: Scene): void; - initMaterial(material: Material, lights: Light[], fog: Fog, object: Object3D): void; - setFaceCulling(cullFace?: string, frontFace?: FrontFaceDirection): void; - setMaterialFaces(material: Material): void; - setDepthTest(depthTest: boolean): void; - setDepthWrite(depthWrite: boolean): void; - setBlending(blending: Blending, blendEquation: BlendingEquation, blendSrc: BlendingSrcFactor, blendDst: BlendingDstFactor): void; - setTexture(texture: Texture, slot: number): void; - setRenderTarget(renderTarget: RenderTarget): void; - } - - export interface RenderTarget { - } - - export interface WebGLRenderTargetOptions { - wrapS?: Wrapping; - wrapT?: Wrapping; - magFilter?: TextureFilter; - minFilter?: TextureFilter; - anisotropy?: number; // 1; - format?: number; // RGBAFormat; - type?: TextureDataType; // UnsignedByteType; - depthBuffer?: boolean; // true; - stencilBuffer?: boolean; // true; - } - - export class WebGLRenderTarget implements RenderTarget { - constructor(width: number, height: number, options?: WebGLRenderTargetOptions); - width: number; - height: number; - wrapS: Wrapping; - wrapT: Wrapping; - magFilter: TextureFilter; - minFilter: TextureFilter; - anisotropy: number; - offset: Vector2; - repeat: Vector2; - format: number; - type: number; - depthBuffer: boolean; - stencilBuffer: boolean; - generateMipmaps: boolean; - clone(): WebGLRenderTarget; - dispose(): void; - } - - export class WebGLRenderTargetCube extends WebGLRenderTarget { - constructor(width: number, height: number, options?: WebGLRenderTargetOptions); - activeCubeFace: number; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - } - - // Renderers / Renderables ///////////////////////////////////////////////////////////////////// - - export class RenderableFace3 { - constructor(); - v1: RenderableVertex; - v2: RenderableVertex; - v3: RenderableVertex; - centroidWorld: Vector3; - centroidScreen: Vector3; - normalWorld: Vector3; - vertexNormalsWorld: Vector3[]; - vertexNormalsLength: number; - color: number; - material: Material; - uvs: Vector2[][]; - z: number; - } - - export class RenderableFace4 { - constructor(); - v1: RenderableVertex; - v2: RenderableVertex; - v3: RenderableVertex; - v4: RenderableVertex; - centroidWorld: Vector3; - centroidScreen: Vector3; - normalWorld: Vector3; - vertexNormalsWorld: Vector3[]; - vertexNormalsLength: number; - color: number; - material: Material; - uvs: Vector2[][]; - z: number; - } - - export class RenderableLine { - constructor(); - z: number; - v1: RenderableVertex; - v2: RenderableVertex; - material: Material; - } - - export class RenderableObject { - constructor(); - object: Object; - z: number; - } - - export class RenderableParticle { - constructor(); - object: Object; - x: number; - y: number; - z: number; - rotation: number; - scale: Vector2; - material: Material; - } - - export class RenderableVertex { - constructor(); - positionWorld: Vector3; - positionScreen: Vector4; - visible: boolean; - copy(vertex: RenderableVertex): void; - } - - // Scenes ///////////////////////////////////////////////////////////////////// - - export interface IFog { - name:string; - color: Color; - clone():IFog; - } - - - /** - * This class contains the parameters that define linear fog, i.e., that grows linearly denser with the distance. - */ - export class Fog implements IFog { - constructor(hex: number, near?: number, far?: number); - name:string; - - /** - * Fog color. - */ - color: Color; - - /** - * The minimum distance to start applying fog. Objects that are less than 'near' units from the active camera won't be affected by fog. - */ - near: number; - - /** - * The maximum distance at which fog stops being calculated and applied. Objects that are more than 'far' units away from the active camera won't be affected by fog. - * Default is 1000. - */ - far: number; - - clone(): Fog; - } - - /** - * This class contains the parameters that define linear fog, i.e., that grows exponentially denser with the distance. - */ - export class FogExp2 implements IFog { - constructor(hex: number, density?: number); - name: string; - color: Color; - - /** - * Defines how fast the fog will grow dense. - * Default is 0.00025. - */ - density: number; - - clone(): FogExp2; - } - - /** - * Scenes allow you to set up what and where is to be rendered by three.js. This is where you place objects, lights and cameras. - */ - export class Scene extends Object3D { - - /** - * A fog instance defining the type of fog that affects everything rendered in the scene. Default is null. - */ - fog: IFog; - - /** - * If not null, it will force everything in the scene to be rendered with that material. Default is null. - */ - overrideMaterial: Material; - - /** - * Default is false. - */ - matrixAutoUpdate: boolean; - - constructor(); - } - - // Textures ///////////////////////////////////////////////////////////////////// - - export class Texture { - constructor( - image: HTMLImageElement, - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - constructor( - image: HTMLCanvasElement, - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - id: number; - name: string; - image: Object; // HTMLImageElement or ImageData ; - mapping: Mapping; - wrapS: Wrapping; - wrapT: Wrapping; - magFilter: TextureFilter; - minFilter: TextureFilter; - anisotropy: number; - format: PixelFormat; - type: TextureDataType; - offset: Vector2; - repeat: Vector2; - generateMipmaps: boolean; - premultiplyAlpha: boolean; - flipY: boolean; - needsUpdate: boolean; - onUpdate: () => void; - clone(): Texture; - dispose(): void; - } - var TextureIdCount: number; - var TextureLibrary: Texture[]; - - - export class CompressedTexture extends Texture { - constructor(mipmaps: ImageData[], width: number, height: number, format?: PixelFormat, type?: TextureDataType, mapping?: Mapping, wrapS?: Wrapping, wrapT?: Wrapping, magFilter?: TextureFilter, minFilter?: TextureFilter); - mipmaps: ImageData[]; - clone(): CompressedTexture; - } - - export class DataTexture extends Texture { - constructor(data: ImageData, width: number, height: number, format: PixelFormat, type: TextureDataType, mapping: Mapping, wrapS: Wrapping, wrapT: Wrapping, magFilter: TextureFilter, minFilter: TextureFilter); - clone(): DataTexture; - } - - // Extras ///////////////////////////////////////////////////////////////////// - - export interface TypefaceData { - familyName: string; - cssFontWeight: string; - cssFontStyle: string; - } - - export var FontUtils: { - faces: { [weight: string]: { [style: string]: Face; }; }; - face: string; - weight: string; - style: string; - size: number; - divisions: number; - getFace(): Face; - loadFace(data: TypefaceData): TypefaceData; - drawText(text: string): { paths: Path[]; offset: number; }; - extractGlyphPoints(c: string, face: Face, scale: number, offset: number, path: Path): { offset: number; path: Path; }; - generateShapes(text: string, parameters?: { size?: number; curveSegments?: number; font?: string; weight?: string; style?: string; }): Shape[]; - Triangulate: { - (contour: Vector2[], indices: boolean): Vector2[]; - area(contour: Vector2[]): number; - }; - }; - - export var GeometryUtils: { - merge(geometry1: Geometry, object2: Mesh): void; - merge(geometry1: Geometry, object2: Geometry): void; - removeMaterials(geometry: Geometry, materialIndexArray: number[]): void; - randomPointInTriangle(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): Vector3; - randomPointInFace(face: Face, geometry: Geometry, useCachedAreas: boolean): Vector3; - randomPointsInGeometry(geometry: Geometry, n: number): Vector3; - triangleArea(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): number; - center(geometry: Geometry): Vector3; - normalizeUVs(geometry: Geometry): void; - triangulateQuads(geometry: Geometry): void; - setMaterialIndex(geometry: Geometry, index: number, startFace?: number, endFace?: number); - }; - - export var ImageUtils: { - crossOrigin: string; - loadTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void , onError?: (message: string) => void ): Texture; - loadCompressedTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void , onError?: (message: string) => void ): Texture; - loadTextureCube(array: string[], mapping?: Mapping, onLoad?: () => void , onError?: (message: string) => void ): Texture; - loadCompressedTextureCube(array: string[], mapping?: Mapping, onLoad?: () => void , onError?: (message: string) => void ): Texture; - parseDDS(buffer: ArrayBuffer, loadMipmaps: boolean): { mipmaps: { data: Uint8Array; width: number; height: number; }[]; width: number; height: number; format: number; mipmapCount: number; }; - getNormalMap(image: HTMLImageElement, depth?: number): HTMLCanvasElement; - generateDataTexture(width: number, height: number, color: Color): DataTexture; - }; - - export var SceneUtils: { - createMultiMaterialObject(geometry: Geometry, materials: Material[]): Object3D; - detach(child: Object3D, parent: Object3D, scene: Scene): void; - attach(child: Object3D, scene: Scene, parent: Object3D): void; - }; - - // Extras / Animation ///////////////////////////////////////////////////////////////////// - - export interface KeyFrame { - pos: number[]; - rot: number[]; - scl: number[]; - time: number; - } - - export interface KeyFrames { - keys: KeyFrame[]; - parent: number; - } - - export interface AnimationData { - JIT: number; - fps: number; - hierarchy: KeyFrames[]; - length: number; - name: string; - } - - export class Animation { - constructor(root: Mesh, name: string, interpolationType?: AnimationInterpolation); - - interpolateCatmullRom(points: Vector3[], scale: number): Vector3[]; - interpolate(p0: number, p1: number, p2: number, p3: number, t: number, t2: number, t3: number): number; - - root: Mesh; - data: AnimationData; - hierarchy: Bone[]; - currentTime: number; - timeScale: number; - isPlaying: boolean; - isPaused: boolean; - loop: boolean; - interpolationType: AnimationInterpolation; - points: Vector3[]; - target: Vector3; - play(loop?: boolean, startTimeMS?: number): void; - pause(): void; - stop(): void; - update(deltaTimeMS: number): void; - - getNextKeyWith(type: string, h: number, key: number): KeyFrame; // ???? - getPrevKeyWith(type: string, h: number, key: number): KeyFrame; - - JITCompile: boolean; // https://github.com/mrdoob/three.js/blob/master/examples/webgl_animation_skinning_morph.html#L251 - } - - export class AnimationInterpolation { } - - export var AnimationHandler: { - update(deltaTimeMS: number): void; - addToUpdate(animation: Animation): void; - removeFromUpdate(animation: Animation): void; - add(data: AnimationData): void; - get (name: string): AnimationData; - parse(root: SkinnedMesh): Object3D[]; - - LINEAR: AnimationInterpolation; - CATMULLROM: AnimationInterpolation; - CATMULLROM_FORWARD: AnimationInterpolation; - }; - - export class AnimationMorphTarget { - constructor(root: Bone, data: any); - influence: number; - - root: Bone; - data: Object; - hierarchy: KeyFrames[]; - currentTime: number; - timeScale: number; - isPlaying: boolean; - isPaused: boolean; - loop: boolean; - play(loop?: boolean, startTimeMS?: number): void; - pause(): void; - stop(): void; - update(deltaTimeMS: number): void; - } - - export class KeyFrameAnimation { - constructor(root: Mesh, data: any, JITCompile?: boolean); - JITCompile: number; - - root: Mesh; - data: Object; - hierarchy: KeyFrames[]; - currentTime: number; - timeScale: number; - isPlaying: number; - isPaused: number; - loop: number; - play(loop?: number, startTimeMS?: number): void; - pause(): void; - stop(): void; - update(deltaTimeMS: number): void; - - getNextKeyWith(type: string, h: number, key: number): KeyFrame; // ???? - getPrevKeyWith(type: string, h: number, key: number): KeyFrame; - } - - // Extras / Cameras ///////////////////////////////////////////////////////////////////// - - export class CombinedCamera extends Camera { - constructor(width: number, height: number, fov: number, near: number, far: number, orthoNear: number, orthoFar: number); - fov: number; - left: number; - right: number; - top: number; - bottom: number; - cameraO: OrthographicCamera; - cameraP: PerspectiveCamera; - zoom: number; - near: number; - far: number; - inPerspectiveMode: boolean; - inOrthographicMode: boolean; - toPerspective(): void; - toOrthographic(): void; - setSize(width: number, height: number): void; - setFov(fov: number): void; - updateProjectionMatrix(): void; - setLens(focalLength: number, frameHeight?: number): number; - setZoom(zoom: number): void; - toFrontView(): void; - toBackView(): void; - toLeftView(): void; - toRightView(): void; - toTopView(): void; - toBottomView(): void; - } - - export class CubeCamera extends Object3D { - constructor(near: number, far: number, cubeResolution: number); - renderTarget: WebGLRenderTargetCube; - updateCubeMap(renderer: Renderer, scene: Scene): void; - } - - // Extras / Core ///////////////////////////////////////////////////////////////////// - - /** - * An extensible curve object which contains methods for interpolation - * class Curve<T extends Vector> - */ - export class Curve { - constructor(); - - /** - * Returns a vector for point t of the curve where t is between 0 and 1 - * getPoint(t: number): T; - */ - getPoint(t: number): Vector; - - /** - * Returns a vector for point at relative position in curve according to arc length - * getPointAt(u: number): T; - */ - getPointAt(u: number): Vector; - - /** - * Get sequence of points using getPoint( t ) - * getPoints(divisions?: number): T[]; - */ - getPoints(divisions?: number): Vector[]; - - /** - * Get sequence of equi-spaced points using getPointAt( u ) - * getSpacedPoints(divisions?: number): T[]; - */ - getSpacedPoints(divisions?: number): Vector[]; - - /** - * Get total curve arc length - */ - getLength(): number; - - /** - * Get list of cumulative segment lengths - */ - getLengths(divisions?: number): number[]; - - needsUpdate: boolean; - - /** - * Update the cumlative segment distance cache - */ - updateArcLengths(): void; - - /** - * Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance - */ - getUtoTmapping(u: number, distance: number): number; - - /** - * getNormalVector(t: number): T; - */ - getNormalVector(t: number): Vector; - - /** - * Returns a unit vector tangent at t. If the subclassed curve do not implement its tangent derivation, 2 points a small delta apart will be used to find its gradient which seems to give a reasonable approximation - * getTangent(t: number): T; - */ - getTangent(t: number): Vector; - - /** - * Returns tangent at equidistance point u on the curve - * getTangentAt(u: number): T; - */ - getTangentAt(u: number): Vector; - - static Utils: { - tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; - tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; - tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; - interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; - }; - - static create(constructorFunc: Function, getPointFunc: Function): Function; - } - - /** - * class LineCurve extends Curve - */ - export class LineCurve extends Curve { - constructor(v1: Vector2, v2: Vector2); - getPoint(t: number): Vector2; - getPointAt(u: number): Vector2; - getPoints(divisions?: number): Vector2[]; - getSpacedPoints(divisions?: number): Vector2[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector2; - getTangent(t: number): Vector2; - getTangentAt(u: number): Vector2; - } - - /** - * class QuadraticBezierCurve extends Curve - */ - export class QuadraticBezierCurve extends Curve { - constructor(v0: Vector2, v1: Vector2, v2: Vector2); - getPoint(t: number): Vector2; - getPointAt(u: number): Vector2; - getPoints(divisions?: number): Vector2[]; - getSpacedPoints(divisions?: number): Vector2[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector2; - getTangent(t: number): Vector2; - getTangentAt(u: number): Vector2; - } - /** - * class CubicBezierCurve extends Curve - */ - export class CubicBezierCurve extends Curve { - constructor(v0: number, v1: number, v2: number, v3: number); - getPoint(t: number): Vector2; - getPointAt(u: number): Vector2; - getPoints(divisions?: number): Vector2[]; - getSpacedPoints(divisions?: number): Vector2[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector2; - getTangent(t: number): Vector2; - getTangentAt(u: number): Vector2; - } - /** - * class SplineCurve extends Curve - */ - export class SplineCurve extends Curve { - constructor(points?: Vector2[]); - getPoint(t: number): Vector2; - getPointAt(u: number): Vector2; - getPoints(divisions?: number): Vector2[]; - getSpacedPoints(divisions?: number): Vector2[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector2; - getTangent(t: number): Vector2; - getTangentAt(u: number): Vector2; - } - /** - * class EllipseCurve extends Curve - */ - export class EllipseCurve extends Curve { - constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean); - aX: number; - aY: number; - xRadius: number; - yRadius: number; - aStartAngle: number; - aEndAngle: number; - aClockwise: boolean; - - getPoint(t: number): Vector2; - getPointAt(u: number): Vector2; - getPoints(divisions?: number): Vector2[]; - getSpacedPoints(divisions?: number): Vector2[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector2; - getTangent(t: number): Vector2; - getTangentAt(u: number): Vector2; - } - /** - * class ArcCurve extends EllipseCurve - */ - export class ArcCurve extends EllipseCurve { - constructor(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean); - getPoint(t: number): Vector2; - getPointAt(u: number): Vector2; - getPoints(divisions?: number): Vector2[]; - getSpacedPoints(divisions?: number): Vector2[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector2; - getTangent(t: number): Vector2; - getTangentAt(u: number): Vector2; - } - - /** - * class LineCurve3 extends Curve - */ - export class LineCurve3 extends Curve { - constructor(v1: Vector3, v2: Vector3); - getPoint(t: number): Vector3; - getPointAt(u: number): Vector3; - getPoints(divisions?: number): Vector3[]; - getSpacedPoints(divisions?: number): Vector3[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector3; - getTangent(t: number): Vector3; - getTangentAt(u: number): Vector3; - } - - /** - * class QuadraticBezierCurve3 extends Curve - */ - export class QuadraticBezierCurve3 extends Curve { - constructor(v0: Vector3, v1: Vector3, v2: Vector3); - getPoint(t: number): Vector3; - getPointAt(u: number): Vector3; - getPoints(divisions?: number): Vector3[]; - getSpacedPoints(divisions?: number): Vector3[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector3; - getTangent(t: number): Vector3; - getTangentAt(u: number): Vector3; - } - - /** - * class CubicBezierCurve3 extends Curve - */ - export class CubicBezierCurve3 extends Curve { - constructor(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3); - getPoint(t: number): Vector3; - getPointAt(u: number): Vector3; - getPoints(divisions?: number): Vector3[]; - getSpacedPoints(divisions?: number): Vector3[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector3; - getTangent(t: number): Vector3; - getTangentAt(u: number): Vector3; - } - - /** - * class SplineCurve3 extends Curve - */ - export class SplineCurve3 extends Curve { - constructor(points?: Vector3[]); - points: Vector3[]; - getPoint(t: number): Vector3; - getPointAt(u: number): Vector3; - getPoints(divisions?: number): Vector3[]; - getSpacedPoints(divisions?: number): Vector3[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector3; - getTangent(t: number): Vector3; - getTangentAt(u: number): Vector3; - } - - /** - * class ClosedSplineCurve3 extends Curve - */ - export class ClosedSplineCurve3 extends Curve { - constructor(points?: Vector3[]); - points: Vector3[]; - getPoint(t: number): Vector3; - getPointAt(u: number): Vector3; - getPoints(divisions?: number): Vector3[]; - getSpacedPoints(divisions?: number): Vector3[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector3; - getTangent(t: number): Vector3; - getTangentAt(u: number): Vector3; - } - - export interface BoundingBox { - minX: number; - minY: number; - maxX: number; - maxY: number; - centroid: Vector; - } - - export class CurvePath extends Curve { - constructor(); - curves: Curve[]; - bends: Path[]; - autoClose: boolean; - add(curve: Curve): void; - checkConnection(): boolean; - closePath(): void; - getBoundingBox(): BoundingBox; - createPointsGeometry(divisions: number): Geometry; - createSpacedPointsGeometry(divisions: number): Geometry; - createGeometry(points: Vector2[]): Geometry; - addWrapPath(bendpath: Path): void; - getTransformedPoints(segments: number, bends?: Path): Vector2[]; - getTransformedSpacedPoints(segments: number, bends?: Path[]): Vector2[]; - getWrapPoints(oldPts: Vector2[], path: Path): Vector2[]; - } - - export enum PathActions { - MOVE_TO, - LINE_TO, - QUADRATIC_CURVE_TO, // Bezier quadratic curve - BEZIER_CURVE_TO, // Bezier cubic curve - CSPLINE_THRU, // Catmull-rom spline - ARC, // Circle - ELLIPSE, - } - - /** - * a 2d path representation, comprising of points, lines, and cubes, similar to the html5 2d canvas api. It extends CurvePath. - */ - export class Path extends CurvePath { - constructor(points?: Vector2); - actions: PathActions[]; - fromPoints(vectors: Vector2[]): void; - moveTo(x: number, y: number): void; - lineTo(x: number, y: number): void; - quadraticCurveTo(aCPx: number, aCPy: number, aX: number, aY: number): void; - bezierCurveTo(aCP1x: number, aCP1y: number, aCP2x: number, aCP2y: number, aX: number, aY: number): void; - splineThru(pts: Vector2[]): void; - arc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - absarc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - toShapes(): Shape[]; - } - - export class Gyroscope extends Object3D { - constructor(); - updateMatrixWorld(force?: boolean): void; - translationWorld: Vector3; - translationObject: Vector3; - rotationWorld: Quaternion; - rotationObject: Quaternion; - scaleWorld: Vector3; - scaleObject: Vector3; - } - - /** - * Defines a 2d shape plane using paths. - */ - export class Shape /* extends Path */ implements Path { - constructor(points?: Vector2[]); - holes: Path[]; - extrude(options?: any): ExtrudeGeometry; - makeGeometry(options?: any): ShapeGeometry; - getPointsHoles(divisions: number): Vector2[][]; - getSpacedPointsHoles(divisions: number): Vector2[][]; - extractAllPoints(divisions: number): { - shape: Vector2[]; - holes: Vector2[][]; - }; - useSpacedPoints: boolean; - extractPoints(divisions: number): Vector2[]; - extractAllSpacedPoints(divisions: Vector2): { - shape: Vector2[]; - holes: Vector2[][]; - }; - - static Utils: { - removeHoles(contour: Vector2[], holes: Vector2[][]): { - shape: Shape; - isolatedPts: Vector2[]; - allpoints: Vector2[]; - }; - triangulateShape(contour: Vector2[], holes: Vector2[][]): Vector2[]; - isClockWise(pts: Vector2[]): boolean; - b2p0(t: number, p: number): number; - b2p1(t: number, p: number): number; - b2p2(t: number, p: number): number; - b2(t: number, p0: number, p1: number, p2: number): number; - b3p0(t: number, p: number): number; - b3p1(t: number, p: number): number; - b3p2(t: number, p: number): number; - b3p3(t: number, p: number): number; - b3(t: number, p0: number, p1: number, p2: number, p3: number): number; - }; - - // trick for TypeScript 0.9.5 compile passed - // from Path - actions: PathActions[]; - fromPoints(vectors: Vector2[]): void; - moveTo(x: number, y: number): void; - lineTo(x: number, y: number): void; - quadraticCurveTo(aCPx: number, aCPy: number, aX: number, aY: number): void; - bezierCurveTo(aCP1x: number, aCP1y: number, aCP2x: number, aCP2y: number, aX: number, aY: number): void; - splineThru(pts: Vector2[]): void; - arc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - absarc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - toShapes(): Shape[]; - // from CurvePath - curves: Curve[]; - bends: Path[]; - autoClose: boolean; - add(curve: Curve): void; - checkConnection(): boolean; - closePath(): void; - getBoundingBox(): BoundingBox; - createPointsGeometry(divisions: number): Geometry; - createSpacedPointsGeometry(divisions: number): Geometry; - createGeometry(points: Vector2[]): Geometry; - addWrapPath(bendpath: Path): void; - getTransformedPoints(segments: number, bends?: Path): Vector2[]; - getTransformedSpacedPoints(segments: number, bends?: Path[]): Vector2[]; - getWrapPoints(oldPts: Vector2[], path: Path): Vector2[]; - getPoint(t: number): Vector; - getPointAt(u: number): Vector; - getPoints(divisions?: number): Vector[]; - getSpacedPoints(divisions?: number): Vector[]; - getLength(): number; - getLengths(divisions?: number): number[]; - needsUpdate: boolean; - updateArcLengths(): void; - getUtoTmapping(u: number, distance: number): number; - getNormalVector(t: number): Vector; - getTangent(t: number): Vector; - getTangentAt(u: number): Vector; - } - - - - // Extras / Geomerties ///////////////////////////////////////////////////////////////////// - - export class AsteriskGeometry extends Geometry { - constructor(innerRadius: number, outerRadius: number); - } - - export class CircleGeometry extends Geometry { - constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); - } - - export class ConvexGeometry extends Geometry { - constructor(vertices: Vector3[]); - } - - /** - * CubeGeometry is the quadrilateral primitive geometry class. It is typically used for creating a cube or irregular quadrilateral of the dimensions provided within the (optional) 'width', 'height', & 'depth' constructor arguments. - */ - export class CubeGeometry extends Geometry { - /** - * @param width — Width of the sides on the X axis. - * @param height — Height of the sides on the Y axis. - * @param depth — Depth of the sides on the Z axis. - * @param widthSegments — Number of segmented faces along the width of the sides. - * @param heightSegments — Number of segmented faces along the height of the sides. - * @param depthSegments — Number of segmented faces along the depth of the sides. - */ - constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number); - } - - export class CylinderGeometry extends Geometry { - /** - * @param radiusTop — Radius of the cylinder at the top. - * @param radiusBottom — Radius of the cylinder at the bottom. - * @param height — Height of the cylinder. - * @param radiusSegments — Number of segmented faces around the circumference of the cylinder. - * @param heightSegments — Number of rows of faces along the height of the cylinder. - * @param openEnded - A Boolean indicating whether or not to cap the ends of the cylinder. - */ - constructor(radiusTop?: number, radiusBottom?: number, height?: number, radiusSegments?: number, heightSegments?: number, openEnded?: boolean); - } - - export class ExtrudeGeometry extends Geometry { - constructor(shape?: Shape, options?: any); - constructor(shapes?: Shape[], options?: any); - shapebb: BoundingBox; - addShapeList(shapes: Shape[], options?: any): void; - addShape(shape: Shape, options?: any): void; - static WorldUVGenerator: { - generateTopUV(geometry: Geometry, extrudedShape: Shape, extrudeOptions: Object, indexA: number, indexB: number, indexC: number): Vector2[]; - generateBottomUV(geometry: Geometry, extrudedShape: Shape, extrudeOptions: Object, indexA: number, indexB: number, indexC: number): Vector2[]; - generateSideWallUV(geometry: Geometry, extrudedShape: Shape, wallContour: Object, extrudeOptions: Object, - indexA: number, indexB: number, indexC: number, indexD: number, stepIndex: number, stepsLength: number, - contourIndex1: number, contourIndex2: number): Vector2[]; - }; - } - - export class IcosahedronGeometry extends PolyhedronGeometry { - constructor(radius: number, detail: number); - } - - export class LatheGeometry extends Geometry { - constructor(points: Vector3[], steps?: number, angle?: number); - } - - export class OctahedronGeometry extends PolyhedronGeometry { - constructor(radius: number, detail: number); - } - - export class ParametricGeometry extends Geometry { - constructor(func: (u: number, v: number) => Vector3, slices: number, stacks: number, useTris?: boolean); - } - - export class PlaneGeometry extends Geometry { - constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); - width: number; - height: number; - widthSegments: number; - heightSegments: number; - } - - export class PolyhedronGeometry extends Geometry { - constructor(vertices: Vector3[], faces: Face[], radius?: number, detail?: number); - } - - export class ShapeGeometry extends Geometry { - constructor(shape: Shape, options?: any); - constructor(shapes: Shape[], options?: any); - shapebb: BoundingBox; - addShapeList(shapes: Shape[], options: any): ShapeGeometry; - addShape(shape: Shape, options?: any): void; - } - - /** - * A class for generating sphere geometries - */ - export class SphereGeometry extends Geometry { - /** - * The geometry is created by sweeping and calculating vertexes around the Y axis (horizontal sweep) and the Z axis (vertical sweep). Thus, incomplete spheres (akin to 'sphere slices') can be created through the use of different values of phiStart, phiLength, thetaStart and thetaLength, in order to define the points in which we start (or end) calculating those vertices. - * - * @param radius — sphere radius. Default is 50. - * @param segmentsWidth — number of horizontal segments. Minimum value is 3, and the default is 8. - * @param segmentsHeight — number of vertical segments. Minimum value is 2, and the default is 6. - * @param phiStart — specify horizontal starting angle. Default is 0. - * @param phiLength — specify horizontal sweep angle size. Default is Math.PI * 2. - * @param thetaStart — specify vertical starting angle. Default is 0. - * @param thetaLength — specify vertical sweep angle size. Default is Math.PI. - */ - constructor(radius: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number); - radius: number; - widthSegments: number; - heightSegments: number; - phiStart: number; - phiLength: number; - thetaStart: number; - thetaLength: number; - } - - export class TetrahedronGeometry extends PolyhedronGeometry { - constructor(radius?: number, detail?: number); - } - - export interface TextGeometryParameters { - size?: number; // size of the text - height?: number; // thickness to extrude text - curveSegments?: number; // number of points on the curves - font?: string; // font name - weight?: string; // font weight (normal, bold) - style?: string; // font style (normal, italics) - bevelEnabled?: boolean; // turn on bevel - bevelThickness?: number; // how deep into text bevel goes - bevelSize?: number; // how far from text outline is bevel - } - - export class TextGeometry extends ExtrudeGeometry { - constructor(text: string, TextGeometryParameters?: TextGeometryParameters); - } - - export class TorusGeometry extends Geometry { - constructor(radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, arc?: number); - radius: number; - tube: number; - radialSegments: number; - tubularSegments: number; - arc: number; - } - - export class TorusKnotGeometry extends Geometry { - constructor(radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, p?: number, q?: number, heightScale?: number); - radius: number; - tube: number; - radialSegments: number; - tubularSegments: number; - p: number; - q: number; - heightScale: number; - grid: number[][]; - } - - export class TubeGeometry extends Geometry { - constructor(path: Path, segments?: number, radius?: number, radiusSegments?: number, closed?: boolean, debug?: Object3D); - - // https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_extrude_shapes.html#L208 - // Hmmm? - constructor(path: SplineCurve3, segments?: number, radius?: number, radiusSegments?: number, closed?: boolean, debug?: boolean); - - path: Path; - segments: number; - radius: number; - radiusSegments: number; - closed: boolean; - grid: number[][]; - tangents: Vector3[]; - normals: Vector3[]; - binormals: Vector3[]; - FrenetFrames(path: Path, segments: number, closed: boolean): void; - } - - // Extras / Helpers ///////////////////////////////////////////////////////////////////// - - export class AxisHelper extends Line { - constructor(size: number); - } - - export class ArrowHelper extends Object3D { - constructor(dir: Vector3, origin?: Vector3, length?: number, hex?: number); - line: Line; - cone: Mesh; - setDirection(dir: Vector3): void; - setLength(length: number): void; - setColor(hex: number): void; - } - - export class CameraHelper extends Line { - constructor(camera: Camera); - pointMap: { [id: string]: number[]; }; - camera: Camera; - } - - export class DirectionalLightHelper extends Object3D { - constructor(light: Light, sphereSize: number, arrowLength: number); - light: Light; - direction: Vector3; - color: Color; - lightArrow: ArrowHelper; - lightSphere: Mesh; - lightRays: Line; - targetSphere: Mesh; - targetLine: Line; - } - - export class HemisphereLightHelper extends Object3D { - constructor(light: Light, sphereSize: number, arrowLength: number, domeSize: number); - light: Light; - color: Color; - groundColor: Color; - lightSphere: Mesh; - lightArrow: ArrowHelper; - lightArrowGround: ArrowHelper; - target: Vector3; - } - - export class PointLightHelper extends Object3D { - constructor(light: Light, sphereSize: number); - light: Light; - color: Color; - lightSphere: Mesh; - lightRays: Line; - lightDistance: Mesh; - } - - export class SpotLightHelper extends Object3D { - constructor(light: Light, sphereSize: number, arrowLength: number); - light: Light; - direction: Vector3; - color: Color; - lightArrow: ArrowHelper; - lightSphere: Mesh; - lightCone: Mesh; - lightRays: Line; - gyroscope: Gyroscope; - targetSphere: Mesh; - targetLine: Line; - } - - // Extras / Objects ///////////////////////////////////////////////////////////////////// - - export class ImmediateRenderObject extends Object3D { - constructor(); - // render(renderCallback):void; - } - - export interface LensFlareProperty { - texture: Texture; // Texture - size: number; // size in pixels (-1 = use texture.width) - distance: number; // distance (0-1) from light source (0=at light source) - x: number; - y: number; - z: number; // screen position (-1 => 1) z = 0 is ontop z = 1 is back - scale: number; // scale - rotation: number; // rotation - opacity: number; // opacity - color: Color; // color - blending: Blending; - } - - export class LensFlare extends Object3D { - constructor(texture?: Texture, size?: number, distance?: number, blending?: Blending, color?: Color); - lensFlares: LensFlareProperty[]; - positionScreen: Vector3; - customUpdateCallback: (object: LensFlare) => void; - add(object: Object3D): void; - add(texture?: Texture, size?: number, distance?: number, blending?: Blending, color?: Color, opacity?: number): void; - updateLensFlares(): void; - } - - export interface MorphBlendMeshAnimation { - startFrame: number; - endFrame: number; - length: number; - fps: number; - duration: number; - lastFrame: number; - currentFrame: number; - active: boolean; - time: number; - direction: number; - weight: number; - directionBackwards: boolean; - mirroredLoop: boolean; - } - - export class MorphBlendMesh extends Mesh { - constructor(geometry: Geometry, material: Material); - animationsMap: { [name: string]: MorphBlendMeshAnimation; }; - animationsList: MorphBlendMeshAnimation[]; - createAnimation(name: string, start: number, end: number, fps: number): void; - autoCreateAnimations(fps: number): void; - firstAnimation: string; - setAnimationDirectionForward(name: string): void; - setAnimationDirectionBackward(name: string): void; - setAnimationFPS(name: string, fps: number): void; - setAnimationDuration(name: string, duration: number): void; - setAnimationWeight(name: string, weight: number): void; - setAnimationTime(name: string, time: number): void; - getAnimationTime(name: string): number; - getAnimationDuration(name: string): number; - playAnimation(name: string): void; - stopAnimation(name: string): void; - update(delta: number): void; - } - - // Extras / Renderers / Plugins ///////////////////////////////////////////////////////////////////// - - export class DepthPassPlugin implements RendererPlugin { - constructor(); - enabled: boolean; - renderTarget: RenderTarget; - init(renderer: Renderer): void; - render(scene: Scene, camera: Camera): void; - update(scene: Scene, camera: Camera): void; - } - - export class LensFlarePlugin implements RendererPlugin { - constructor(); - init(renderer: Renderer): void; - render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; - } - - export class ShadowMapPlugin implements RendererPlugin { - constructor(); - init(renderer: Renderer): void; - render(scene: Scene, camera: Camera): void; - update(scene: Scene, camera: Camera): void; - } - - export class SpritePlugin implements RendererPlugin { - constructor(); - init(renderer: Renderer): void; - render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; - } - - // renderers ///////////////////////////////////////////////////////////////////// - - export interface ShaderLibrary { - [name: string]: { - vertexShader: string; - fragmentShader: string; - }; - } - export var ShaderFlares: ShaderLibrary; - export var ShaderSprite: ShaderLibrary; - - export var UniformsUtils: { - merge(uniforms: Object[]): Uniforms; - merge(uniforms: Uniforms[]): Uniforms; - clone(uniforms_src: Uniforms): Uniforms; - }; - - export var UniformsLib: { - common: Uniforms; - bump: Uniforms; - normalmap: Uniforms; - fog: Uniforms; - lights: Uniforms; - particle: Uniforms; - shadowmap: Uniforms; - }; - - export interface Shader { - uniforms: Uniforms; - vertexShader: string; - fragmentShader: string; - } - - export var ShaderLib: { - [name: string]: Shader; - basic: Shader; - lambert: Shader; - phong: Shader; - particle_basic: Shader; - depth: Shader; - dashed: Shader; - normal: Shader; - normalmap: Shader; - cube: Shader; - depthRGBA: Shader; - }; -} +// Type definitions for three.js -- r66 +// Project: http://mrdoob.github.com/three.js/ +// Definitions by: Kon , Satoru Kimura +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface WebGLRenderingContext {} + +declare module THREE { + export var REVISION: string; + + // custom blending equations + // (numbers start from 100 not to clash with other + // mappings to OpenGL constants defined in Texture.js) + export enum BlendingEquation { } + export var AddEquation: BlendingEquation; + export var SubtractEquation: BlendingEquation; + export var ReverseSubtractEquation: BlendingEquation; + + // custom blending destination factors + export enum BlendingDstFactor { } + export var ZeroFactor: BlendingDstFactor; + export var OneFactor: BlendingDstFactor; + export var SrcColorFactor: BlendingDstFactor; + export var OneMinusSrcColorFactor: BlendingDstFactor; + export var SrcAlphaFactor: BlendingDstFactor; + export var OneMinusSrcAlphaFactor: BlendingDstFactor; + export var DstAlphaFactor: BlendingDstFactor; + export var OneMinusDstAlphaFactor: BlendingDstFactor; + + // custom blending source factors + export enum BlendingSrcFactor { } + export var DstColorFactor: BlendingSrcFactor; + export var OneMinusDstColorFactor: BlendingSrcFactor; + export var SrcAlphaSaturateFactor: BlendingSrcFactor; + + // GL STATE CONSTANTS + + export enum CullFace { } + export var CullFaceNone: CullFace; + export var CullFaceBack: CullFace; + export var CullFaceFront: CullFace; + export var CullFaceFrontBack: CullFace; + + export enum FrontFaceDirection { } + export var FrontFaceDirectionCW: FrontFaceDirection; + export var FrontFaceDirectionCCW: FrontFaceDirection; + + // MATERIAL CONSTANTS + + // side + export enum Side { } + export var FrontSide: Side; + export var BackSide: Side; + export var DoubleSide: Side; + + // shading + export enum Shading { } + export var NoShading: Shading; + export var FlatShading: Shading; + export var SmoothShading: Shading; + + // colors + export enum Colors { } + export var NoColors: Colors; + export var FaceColors: Colors; + export var VertexColors: Colors; + + // blending modes + export enum Blending { } + export var NoBlending: Blending; + export var NormalBlending: Blending; + export var AdditiveBlending: Blending; + export var SubtractiveBlending: Blending; + export var MultiplyBlending: Blending; + export var CustomBlending: Blending; + + // Shadowing Type + export enum ShadowMapType { } + export var BasicShadowMap: ShadowMapType; + export var PCFShadowMap: ShadowMapType; + export var PCFSoftShadowMap: ShadowMapType; + + // TEXTURE CONSTANTS + // Operations + export enum Combine { } + export var MultiplyOperation: Combine; + export var MixOperation: Combine; + export var AddOperation: Combine; + + // Mapping modes + export enum Mapping { } + export interface MappingConstructor { + new (): Mapping; + } + export var UVMapping: MappingConstructor; + export var CubeReflectionMapping: MappingConstructor; + export var CubeRefractionMapping: MappingConstructor; + export var SphericalReflectionMapping: MappingConstructor; + export var SphericalRefractionMapping: MappingConstructor; + + // Wrapping modes + export enum Wrapping { } + export var RepeatWrapping: Wrapping; + export var ClampToEdgeWrapping: Wrapping; + export var MirroredRepeatWrapping: Wrapping; + + // Filters + export enum TextureFilter { } + export var NearestFilter: TextureFilter; + export var NearestMipMapNearestFilter: TextureFilter; + export var NearestMipMapLinearFilter: TextureFilter; + export var LinearFilter: TextureFilter; + export var LinearMipMapNearestFilter: TextureFilter; + export var LinearMipMapLinearFilter: TextureFilter; + + // Data types + export enum TextureDataType { } + export var UnsignedByteType: TextureDataType; + export var ByteType: TextureDataType; + export var ShortType: TextureDataType; + export var UnsignedShortType: TextureDataType; + export var IntType: TextureDataType; + export var UnsignedIntType: TextureDataType; + export var FloatType: TextureDataType; + + // Pixel types + export enum PixelType { } + + export var UnsignedShort4444Type: PixelType; + export var UnsignedShort5551Type: PixelType; + export var UnsignedShort565Type: PixelType; + + // Pixel formats + export enum PixelFormat { } + export var AlphaFormat: PixelFormat; + export var RGBFormat: PixelFormat; + export var RGBAFormat: PixelFormat; + export var LuminanceFormat: PixelFormat; + export var LuminanceAlphaFormat: PixelFormat; + + // Compressed texture formats + export enum CompressedPixelFormat { } + export var RGB_S3TC_DXT1_Format: CompressedPixelFormat; + export var RGBA_S3TC_DXT1_Format: CompressedPixelFormat; + export var RGBA_S3TC_DXT3_Format: CompressedPixelFormat; + export var RGBA_S3TC_DXT5_Format: CompressedPixelFormat; + + // Cameras //////////////////////////////////////////////////////////////////////////////////////// + + /** + * Abstract base class for cameras. This class should always be inherited when you build a new camera. + */ + export class Camera extends Object3D { + /** + * This constructor sets following properties to the correct type: matrixWorldInverse, projectionMatrix and projectionMatrixInverse. + */ + constructor(); + + /** + * This is the inverse of matrixWorld. MatrixWorld contains the Matrix which has the world transform of the Camera. + */ + matrixWorldInverse: Matrix4; + + /** + * This is the matrix which contains the projection. + */ + projectionMatrix: Matrix4; + + /** + * This make the camera look at the vector position in local space. + * @param vector point to look at + */ + lookAt(vector: Vector3): void; + } + + /** + * Camera with orthographic projection + * + * @example + * var camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); + * scene.add( camera ); + * + * @see src/cameras/OrthographicCamera.js + */ + export class OrthographicCamera extends Camera { + /** + * @param left Camera frustum left plane. + * @param right Camera frustum right plane. + * @param top Camera frustum top plane. + * @param bottom Camera frustum bottom plane. + * @param near Camera frustum near plane. + * @param far Camera frustum far plane. + */ + constructor(left: number, right: number, top: number, bottom: number, near?: number, far?: number); + + /** + * Camera frustum left plane. + */ + left: number; + + /** + * Camera frustum right plane. + */ + right: number; + + /** + * Camera frustum top plane. + */ + top: number; + + /** + * Camera frustum bottom plane. + */ + bottom: number; + + /** + * Camera frustum near plane. + */ + near: number; + + /** + * Camera frustum far plane. + */ + far: number; + + /** + * Updates the camera projection matrix. Must be called after change of parameters. + */ + updateProjectionMatrix(): void; + } + + /** + * Camera with perspective projection. + * + * # example + * var camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 ); + * scene.add( camera ); + * + * @source https://github.com/mrdoob/three.js/blob/master/src/cameras/PerspectiveCamera.js + */ + export class PerspectiveCamera extends Camera { + /** + * @param fov Camera frustum vertical field of view. Default value is 50. + * @param aspect Camera frustum aspect ratio. Default value is 1. + * @param near Camera frustum near plane. Default value is 0.1. + * @param far Camera frustum far plane. Default value is 2000. + */ + constructor(fov?: number, aspect?: number, near?: number, far?: number); + + /** + * Camera frustum vertical field of view, from bottom to top of view, in degrees. + */ + fov: number; + + /** + * Camera frustum aspect ratio, window width divided by window height. + */ + aspect: number; + + /** + * Camera frustum near plane. + */ + near: number; + + /** + * Camera frustum far plane. + */ + far: number; + + /** + * Uses focal length (in mm) to estimate and set FOV 35mm (fullframe) camera is used if frame size is not specified. + * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html + * @param focalLength focal length + * @param frameHeight frame size. Default value is 24. + */ + setLens(focalLength: number, frameHeight?: number): void; + + /** + * Sets an offset in a larger frustum. This is useful for multi-window or multi-monitor/multi-machine setups. + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and the monitors are in grid like this: + * + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + * + * then for each monitor you would call it like this: + * + * var w = 1920; + * var h = 1080; + * var fullWidth = w * 3; + * var fullHeight = h * 2; + * + * // A + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * // B + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * // C + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * // D + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * // E + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * // F + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); Note there is no reason monitors have to be the same size or in a grid. + * + * @param fullWidth full width of multiview setup + * @param fullHeight full height of multiview setup + * @param x horizontal offset of subcamera + * @param y vertical offset of subcamera + * @param width width of subcamera + * @param height height of subcamera + */ + setViewOffset(fullWidth: number, fullHeight: number, x: number, y: number, width: number, height: number): void; + + /** + * Updates the camera projection matrix. Must be called after change of parameters. + */ + updateProjectionMatrix(): void; + } + + // Core /////////////////////////////////////////////////////////////////////////////////////////////// + + interface BufferGeometryAttributeArray extends ArrayBufferView{ + length: number; + } + + interface BufferGeometryAttribute{ + itemSize: number; + array: BufferGeometryAttributeArray; + numItems: number; + } + + interface BufferGeometryAttributes{ + [name: string]: BufferGeometryAttribute; + index?: BufferGeometryAttribute; + position?: BufferGeometryAttribute; + normal?: BufferGeometryAttribute; + color?: BufferGeometryAttribute; + } + + /** + * This is a superefficent class for geometries because it saves all data in buffers. + * It reduces memory costs and cpu cycles. But it is not as easy to work with because of all the nessecary buffer calculations. + * It is mainly interesting when working with static objects. + * + * @see src/core/BufferGeometry.js + */ + export class BufferGeometry { + /** + * This creates a new BufferGeometry. It also sets several properties to an default value. + */ + constructor(); + + /** + * Unique number of this buffergeometry instance + */ + id: number; + + /** + * This hashmap has as id the name of the attribute to be set and as value the buffer to set it to. + */ + attributes: BufferGeometryAttributes; + + /** + * When set, it holds certain buffers in memory to have faster updates for this object. When unset, it deletes those buffers and saves memory. + */ + dynamic: boolean; + + offsets: { start: number; count: number; index: number; }[]; + + /** + * Bounding box. + */ + boundingBox: BoundingBox3D; + + /** + * Bounding sphere. + */ + boundingSphere: BoundingSphere; + + morphTargets: any[]; + hasTangents: boolean; + + /** + * Bakes matrix transform directly into vertex coordinates. + */ + applyMatrix(matrix: Matrix4): void; + + /** + * Computes vertex normals by averaging face normals. + */ + computeVertexNormals(): void; + + /** + * Computes vertex tangents. + * Based on http://www.terathon.com/code/tangent.html + * Geometry must have vertex UVs (layer 0 will be used). + */ + computeTangents(): void; + + /** + * Computes bounding box of the geometry, updating Geometry.boundingBox attribute. + * Bounding boxes aren't computed by default. They need to be explicitly computed, otherwise they are null. + */ + computeBoundingBox(): void; + + /** + * Computes bounding sphere of the geometry, updating Geometry.boundingSphere attribute. + * Bounding spheres aren't' computed by default. They need to be explicitly computed, otherwise they are null. + */ + computeBoundingSphere(): void; + + /** + * Disposes the object from memory. + * You need to call this when you want the bufferGeometry removed while the application is running. + */ + dispose(): void; + + normalizeNormals(): void; + } + + /** + * Object for keeping track of time. + * + * @see src/core/Clock.js + */ + export class Clock { + /** + * @param autoStart Automatically start the clock. + */ + constructor(autoStart?: boolean); + + /** + * If set, starts the clock automatically when the first update is called. + */ + autoStart: boolean; + + /** + * When the clock is running, It holds the starttime of the clock. + * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. + */ + startTime: number; + + /** + * When the clock is running, It holds the previous time from a update. + * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. + */ + oldTime: number; + + /** + * When the clock is running, It holds the time elapsed btween the start of the clock to the previous update. + * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. + */ + elapsedTime: number; + + /** + * This property keeps track whether the clock is running or not. + */ + running: boolean; + + /** + * Starts clock. + */ + start(): void; + + /** + * Stops clock. + */ + stop(): void; + + /** + * Get milliseconds passed since the clock started. + */ + getElapsedTime(): number; + + /** + * Get the milliseconds passed since the last call to this method. + */ + getDelta(): number; + } + + /** + * JavaScript events for custom objects + * + * # Example + * var Car = function () { + * + * EventDispatcher.call( this ); + * this.start = function () { + * + * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } ); + * + * }; + * + * }; + * + * var car = new Car(); + * car.addEventListener( 'start', function ( event ) { + * + * alert( event.message ); + * + * } ); + * car.start(); + * + * @source src/core/EventDispatcher.js + */ + export class EventDispatcher { + /** + * Creates eventDispatcher object. It needs to be call with '.call' to add the functionality to an object. + */ + constructor(); + + /** + * Adds a listener to an event type. + * @param type The type of the listener that gets removed. + * @param listener The listener function that gets removed. + */ + addEventListener(type: string, listener: (event: any) => void ): void; + + /** + * Adds a listener to an event type. + * @param type The type of the listener that gets removed. + * @param listener The listener function that gets removed. + */ + hasEventListener(type: string, listener: (event: any) => void): void; + + /** + * Removes a listener from an event type. + * @param type The type of the listener that gets removed. + * @param listener The listener function that gets removed. + */ + removeEventListener(type: string, listener: (event: any) => void): void; + + /** + * Fire an event type. + * @param type The type of event that gets fired. + */ + dispatchEvent(event: { type: string; target: any; }): void; + } + + export interface Face { + /** + * Face normal. + */ + normal: Vector3; + + /** + * Face color. + */ + color: Color; + + /** + * Array of 4 vertex normals. + */ + vertexNormals: Vector3[]; + + /** + * Array of 4 vertex normals. + */ + vertexColors: Color[]; + + /** + * Array of 4 vertex tangets. + */ + vertexTangents: number[]; + + /** + * Material index (points to {@link Geometry.materials}). + */ + materialIndex: number; + + /** + * Face centroid. + */ + centroid: Vector3; + + clone(): Face; + } + + /** + * Triangle face. + * + * # Example + * var normal = new THREE.Vector3( 0, 1, 0 ); + * var color = new THREE.Color( 0xffaa00 ); + * var face = new THREE.Face3( 0, 1, 2, normal, color, 0 ); + * + * @source https://github.com/mrdoob/three.js/blob/master/src/core/Face3.js + */ + export class Face3 implements Face { + /** + * @param a Vertex A index. + * @param b Vertex B index. + * @param c Vertex C index. + * @param normal Face normal or array of vertex normals. + * @param color Face color or array of vertex colors. + * @param materialIndex Material index. + */ + constructor(a: number, b: number, c: number, normal?: Vector3, color?: Color, materialIndex?: number); + constructor(a: number, b: number, c: number, normal?: Vector3, vertexColors?: Color[], materialIndex?: number); + constructor(a: number, b: number, c: number, vertexNormals?: Vector3[], color?: Color, materialIndex?: number); + constructor(a: number, b: number, c: number, vertexNormals?: Vector3[], vertexColors?: Color[], materialIndex?: number); + + /** + * Vertex A index. + */ + a: number; + + /** + * Vertex B index. + */ + b: number; + + /** + * Vertex C index. + */ + c: number; + + // properties inherits from Face /////////////////////////////////// + + /** + * Face normal. + */ + normal: Vector3; + + /** + * Face color. + */ + color: Color; + + /** + * Array of 4 vertex normals. + */ + vertexNormals: Vector3[]; + + /** + * Array of 4 vertex normals. + */ + vertexColors: Color[]; + + /** + * Array of 4 vertex tangets. + */ + vertexTangents: number[]; + + /** + * Material index (points to {@link Geometry.materials}). + */ + materialIndex: number; + + /** + * Face centroid. + */ + centroid: Vector3; + clone(): Face3; + } + + export interface MorphTarget { + name: string; + vertices: Vector3[]; + } + + export interface MorphColor { + name: string; + color: Color[]; + } + + export interface MorphNormals { + name: string; + normals: Vector3[]; + } + + export interface BoundingBox3D { + min: Vector3; + max: Vector3; + } + + export interface BoundingSphere { + radius: number; + } + + + /** + * Base class for geometries + * + * # Example + * var geometry = new THREE.Geometry(); + * geometry.vertices.push( new THREE.Vector3( -10, 10, 0 ) ); + * geometry.vertices.push( new THREE.Vector3( -10, -10, 0 ) ); + * geometry.vertices.push( new THREE.Vector3( 10, -10, 0 ) ); + * geometry.faces.push( new THREE.Face3( 0, 1, 2 ) ); + * geometry.computeBoundingSphere(); + * + * @see https://github.com/mrdoob/three.js/blob/master/src/core/Geometry.js + */ + export class Geometry { + constructor(); + + /** + * Unique number of this geometry instance + */ + id: number; + + /** + * Name for this geometry. Default is an empty string. + */ + name: string; + + /** + * The array of vertices hold every position of points of the model. + * To signal an update in this array, Geometry.verticesNeedUpdate needs to be set to true. + */ + vertices: Vector3[]; + + /** + * Array of vertex colors, matching number and order of vertices. + * Used in ParticleSystem, Line and Ribbon. + * Meshes use per-face-use-of-vertex colors embedded directly in faces. + * To signal an update in this array, Geometry.colorsNeedUpdate needs to be set to true. + */ + colors: Color[]; + + /** + * Array of vertex normals, matching number and order of vertices. + * Normal vectors are nessecary for lighting + * To signal an update in this array, Geometry.normalsNeedUpdate needs to be set to true. + */ +// normals: Vector3[]; + + /** + * Array of triangles or/and quads. + * The array of faces describe how each vertex in the model is connected with each other. + * To signal an update in this array, Geometry.elementsNeedUpdate needs to be set to true. + */ + faces: Face[]; + + /** + * Array of face UV layers. + * Each UV layer is an array of UV matching order and number of faces. + * To signal an update in this array, Geometry.uvsNeedUpdate needs to be set to true. + */ +// faceUvs: Vector2[][]; + + /** + * Array of face UV layers. + * Each UV layer is an array of UV matching order and number of vertices in faces. + * To signal an update in this array, Geometry.uvsNeedUpdate needs to be set to true. + */ + faceVertexUvs: Vector2[][][]; + + /** + * Array of morph targets. Each morph target is a Javascript object: + * + * { name: "targetName", vertices: [ new THREE.Vector3(), ... ] } + * + * Morph vertices match number and order of primary vertices. + */ + morphTargets: MorphTarget[]; + + /** + * Array of morph colors. Morph colors have similar structure as morph targets, each color set is a Javascript object: + * + * morphColor = { name: "colorName", colors: [ new THREE.Color(), ... ] } + */ + morphColors: MorphColor[]; + + /** + * Array of morph normals. Morph normals have similar structure as morph targets, each normal set is a Javascript object: + * + * morphNormal = { name: "NormalName", normals: [ new THREE.Vector3(), ... ] } + */ + morphNormals: MorphNormals[]; + + /** + * Array of skinning weights, matching number and order of vertices. + */ + skinWeights: number[]; + + /** + * Array of skinning indices, matching number and order of vertices. + */ + skinIndices: number[]; + + /** + * Bounding box. + */ + boundingBox: BoundingBox3D; + + /** + * Bounding sphere. + */ + boundingSphere: BoundingSphere; + + /** + * True if geometry has tangents. Set in Geometry.computeTangents. + */ + hasTangents: boolean; + + /** + * Set to true if attribute buffers will need to change in runtime (using "dirty" flags). + * Unless set to true internal typed arrays corresponding to buffers will be deleted once sent to GPU. + * Defaults to true. + */ + dynamic: boolean; + + /** + * Set to true if the vertices array has been updated. + */ + verticesNeedUpdate: boolean; + + /** + * Set to true if the faces array has been updated. + */ + elementsNeedUpdate: boolean; + + /** + * Set to true if the uvs array has been updated. + */ + uvsNeedUpdate: boolean; + + /** + * Set to true if the normals array has been updated. + */ + normalsNeedUpdate: boolean; + + /** + * Set to true if the tangents in the faces has been updated. + */ + tangentsNeedUpdate: boolean; + + /** + * Set to true if the colors array has been updated. + */ + colorsNeedUpdate: boolean; + + /** + * Set to true if the linedistances array has been updated. + */ + lineDistancesNeedUpdate: boolean; + + /** + * Set to true if an array has changed in length. + */ + buffersNeedUpdate: boolean; + + /** + * + */ + lineDistances: number[]; + + /** + * Bakes matrix transform directly into vertex coordinates. + */ + applyMatrix(matrix: Matrix4): void; + + /** + * Computes centroids for all faces. + */ + computeCentroids(): void; + + /** + * Computes face normals. + */ + computeFaceNormals(): void; + + /** + * Computes vertex normals by averaging face normals. + * Face normals must be existing / computed beforehand. + */ + computeVertexNormals(areaWeighted?: boolean): void; + + /** + * Computes morph normals. + */ + computeMorphNormals(): void; + + /** + * Computes vertex tangents. + * Based on http://www.terathon.com/code/tangent.html + * Geometry must have vertex UVs (layer 0 will be used). + */ + computeTangents(): void; + + /** + * Computes bounding box of the geometry, updating {@link Geometry.boundingBox} attribute. + */ + computeBoundingBox(): void; + + /** + * Computes bounding sphere of the geometry, updating Geometry.boundingSphere attribute. + * Neither bounding boxes or bounding spheres are computed by default. They need to be explicitly computed, otherwise they are null. + */ + computeBoundingSphere(): void; + + /** + * Checks for duplicate vertices using hashmap. + * Duplicated vertices are removed and faces' vertices are updated. + */ + mergeVertices(): number; + + /** + * Creates a new clone of the Geometry. + */ + clone(): Geometry; + + /** + * Removes The object from memory. + * Don't forget to call this method when you remove an geometry because it can cuase meomory leaks. + */ + dispose(): void; + + computeLineDistances(): void; + } + + /** + * Base class for scene graph objects + */ + export class Object3D { + constructor(); + + /** + * Unique number of this object instance. + */ + id: number; + + /** + * Optional name of the object (doesn't need to be unique). + */ + name: string; + + /** + * Object's parent in the scene graph. + */ + parent: Object3D; + + /** + * Array with object's children. + */ + children: Object3D[]; + + /** + * Object's local position. + */ + position: Vector3; + + /** + * Object's local rotation (Euler angles), in radians. + */ + rotation: Euler; + + /** + * Order of axis for Euler angles. + */ + eulerOrder: string; + // eulerOrder:EulerOrder; + + /** + * Object's local scale. + */ + scale: Vector3; + + /** + * Up direction. + */ + up: Vector3; + + /** + * Local transform. + */ + matrix: Matrix4; + + /** + * Global rotation. + */ + quaternion: Quaternion; + + /** + * Use quaternion instead of Euler angles for specifying local rotation. + */ + useQuaternion: boolean; + + /** + * Override depth-sorting order if non null. + */ + renderDepth: number; + + /** + * Object gets rendered if true. + */ + visible: boolean; + + /** + * Gets rendered into shadow map. + */ + castShadow: boolean; + + /** + * Material gets baked in shadow receiving. + */ + receiveShadow: boolean; + + /** + * When this is set, it checks every frame if the object is in the frustum of the camera. Otherwise the object gets drawn every frame even if it isn't visible. + */ + frustumCulled: boolean; + + /** + * When this is set, it calculates the matrix of position, (rotation or quaternion) and scale every frame and also recalculates the matrixWorld property. + */ + matrixAutoUpdate: boolean; + + /** + * When this is set, it calculates the matrixWorld in that frame and resets this property to false. + */ + matrixWorldNeedsUpdate: boolean; + + /** + * When this is set, then the rotationMatrix gets calculated every frame. + */ + rotationAutoUpdate: boolean; + + /** + * An object that can be used to store custom data about the Object3d. It should not hold references to functions as these will not be cloned. + */ + userData: any; + + /** + * The global transform of the object. If the Object3d has no parent, then it's identical to the local transform. + */ + matrixWorld: Matrix4; + + + /** + * This updates the position, rotation and scale with the matrix. + */ + applyMatrix(matrix: Matrix4): void; + + /** + * Translates object along x axis by distance. + * @param distance Distance. + */ + translateX(distance: number): void; + + /** + * Translates object along y axis by distance. + * @param distance Distance. + */ + translateY(distance: number): void; + + /** + * Translates object along z axis by distance. + * @param distance Distance. + */ + translateZ(distance: number): void; + + /** + * Updates the vector from local space to world space. + * @param vector A local vector. + */ + localToWorld(vector: Vector3): Vector3; + + /** + * Updates the vector from world space to local space. + * @param vector A world vector. + */ + worldToLocal(vector: Vector3): Vector3; + + /** + * Rotates object to face point in space. + * @param vector A world vector to look at. + */ + lookAt(vector: Vector3): void; + + /** + * Adds object as child of this object. + */ + add(object: Object3D): void; + + /** + * Removes object as child of this object. + */ + remove(object: Object3D): void; + + /** + * Translates object along arbitrary axis by distance. + * @param distance Distance. + * @param axis Translation direction. + */ + traverse(callback: (object: Object3D) => any): void; + + /** + * Searches whole subgraph recursively to add all objects in the array. + * @param array optional argument that returns the the array with descendants. + */ + getDescendants(array?: Object3D[]): Object3D[]; + + /** + * Updates local transform. + */ + updateMatrix(): void; + + /** + * Updates global transform of the object and its children. + */ + updateMatrixWorld(force: boolean): void; + + clone(object?: Object3D, recursive?: boolean): Object3D; + + /** + * Creates a new clone of this object and all descendants. + */ + clone(object?: Object3D): Object3D; + + /** + * Searches through the object's children and returns the first with a matching name, optionally recursive. + * @param name String to match to the children's Object3d.name property. + * @param recursive Boolean whether to search through the children's children. Default is false. + */ + getObjectByName(name: string, recursive: boolean): Object3D; + + /** + * Searches through the object's children and returns the first with a matching id, optionally recursive. + * @param id Unique number of the object instance + * @param recursive Boolean whether to search through the children's children. Default is false. + */ + getObjectById(id: string, recursive: boolean): Object3D; + + /** + * @param axis A normalized vector in object space. + * @param distance The distance to translate. + */ + translateOnAxis(axis: Vector3, distance: number): Object3D; + + /** + * Rotate an object along an axis in object space. The axis is assumed to be normalized. + * @param axis A normalized vector in object space. + * @param angle The angle in radians. + */ + rotateOnAxis(axis: Vector3, angle: number): Object3D; + } + + /** + * Projects points between spaces. + */ + export class Projector { + constructor(); + + projectVector(vector: Vector3, camera: Camera): Vector3; + + unprojectVector(vector: Vector3, camera: Camera): Vector3; + + /** + * Translates a 2D point from NDC (Normalized Device Coordinates) to a Raycaster that can be used for picking. NDC range from [-1..1] in x (left to right) and [1.0 .. -1.0] in y (top to bottom). + */ + pickingRay(vector: Vector3, camera: Camera): Raycaster; + + /** + * Transforms a 3D scene object into 2D render data that can be rendered in a screen with your renderer of choice, projecting and clipping things out according to the used camera. + * If the scene were a real scene, this method would be the equivalent of taking a picture with the camera (and developing the film would be the next step, using a Renderer). + * + * @param scene scene to project. + * @param camera camera to use in the projection. + * @param sort select whether to sort elements using the Painter's algorithm. + */ + projectScene(scene: Scene, camera: Camera, sortObjects: boolean, sortElements?: boolean): { + objects: Object3D[]; // Mesh, Line or other object + sprites: Object3D[]; // Sprite or Particle + lights: Light[]; + elements: Face[]; // Line, Particle, Face3 or Face4 + }; + } + + export interface Intersection { + distance: number; + point: Vector3; + face: Face; + object: Object3D; + } + + export class Raycaster { + constructor(origin?: Vector3, direction?: Vector3, near?: number, far?: number); + ray: Ray; + near: number; + far: number; + precision: number; + set(origin: Vector3, direction: Vector3): void; + intersectObject(object: Object3D, recursive?: boolean): Intersection[]; + intersectObjects(objects: Object3D[], recursive?: boolean): Intersection[]; + } + + // Lights ////////////////////////////////////////////////////////////////////////////////// + + /** + * Abstract base class for lights. + */ + export class Light extends Object3D { + constructor(hex?: number); + color: Color; + } + + /** + * This light's color gets applied to all the objects in the scene globally. + * + * # example + * var light = new THREE.AmbientLight( 0x404040 ); // soft white light + * scene.add( light ); + * + * @source https://github.com/mrdoob/three.js/blob/master/src/lights/AmbientLight.js + */ + export class AmbientLight extends Light { + /** + * This creates a Ambientlight with a color. + * @param hex Numeric value of the RGB component of the color. + */ + constructor(hex?: number); + } + + export class AreaLight extends Light{ + constructor(hex: number, intensity?: number); + + position: Vector3; + right: Vector3; + normal: Vector3; + quadraticAttenuation: number; + height: number; + linearAttenuation: number; + width: number; + intensity: number; + constantAttenuation: number; + } + + /** + * Affects objects using MeshLambertMaterial or MeshPhongMaterial. + * + * @example + * // White directional light at half intensity shining from the top. + * var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); + * directionalLight.position.set( 0, 1, 0 ); + * scene.add( directionalLight ); + * + * @see src/lights/DirectionalLight.js + */ + export class DirectionalLight extends Light { + + constructor(hex?: number, intensity?: number); + + /** + * Direction of the light is normalized vector from position to (0,0,0). + * Default — new THREE.Vector3(). + */ + position: Vector3; + + /** + * Target used for shadow camera orientation. + */ + target: Object3D; + + /** + * Light's intensity. + * Default — 1.0. + */ + intensity: number; + + /** + * If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. + * Default — false. + */ + castShadow: boolean; + + /** + * If set to true light will only cast shadow but not contribute any lighting (as if intensity was 0 but cheaper to compute). + * Default — false. + */ + onlyShadow: boolean; + + /** + * Orthographic shadow camera frustum parameter. + * Default — 50. + */ + shadowCameraNear: number; + + /** + * Orthographic shadow camera frustum parameter. + * Default — 5000. + */ + shadowCameraFar: number; + + /** + * Orthographic shadow camera frustum parameter. + * Default — -500. + */ + shadowCameraLeft: number; + + /** + * Orthographic shadow camera frustum parameter. + * Default — 500. + */ + shadowCameraRight: number; + + /** + * Orthographic shadow camera frustum parameter. + * Default — 500. + */ + shadowCameraTop: number; + + /** + * Orthographic shadow camera frustum parameter. + * Default — -500. + */ + shadowCameraBottom: number; + + /** + * Show debug shadow camera frustum. + * Default — false. + */ + shadowCameraVisible: boolean; + + /** + * Shadow map bias. + * Default — 0. + */ + shadowBias: number; + + /** + * Darkness of shadow casted by this light (from 0 to 1). + * Default — 0.5. + */ + shadowDarkness: number; + + /** + * Shadow map texture width in pixels. + * Default — 512. + */ + shadowMapWidth: number; + + /** + * Shadow map texture height in pixels. + * Default — 512. + */ + shadowMapHeight: number; + + /** + * Default — false. + */ + shadowCascade: boolean; + + /** + * Three.Vector3( 0, 0, -1000 ). + */ + shadowCascadeOffset: Vector3; + + /** + * Default — 2. + */ + shadowCascadeCount: number; + + /** + * Default — [ 0, 0, 0 ]. + */ + shadowCascadeBias: number[]; + + /** + * Default — [ 512, 512, 512 ]. + */ + shadowCascadeWidth: number[]; + + /** + * Default — [ 512, 512, 512 ]. + */ + shadowCascadeHeight: number[]; + + /** + * Default — [ -1.000, 0.990, 0.998 ]. + */ + shadowCascadeNearZ: number[]; + + /** + * Default — [ 0.990, 0.998, 1.000 ]. + */ + shadowCascadeFarZ: number[]; + + /** + * Default — [ ]. + */ + shadowCascadeArray: DirectionalLight[]; + + /** + * Default — null. + */ + shadowMap: RenderTarget; + + /** + * Default — null. + */ + shadowMapSize: number; + + /** + * Default — null. + */ + shadowCamera: Camera; + + /** + * Default — null. + */ + shadowMatrix: Matrix4; + } + + export class HemisphereLight extends Light { + constructor(skyColorHex?: number, groundColorHex?: number, intensity?: number); + + position: Vector3; + groundColor: Color; + intensity: number; + } + + /** + * Affects objects using {@link MeshLambertMaterial} or {@link MeshPhongMaterial}. + * + * @example + * var light = new THREE.PointLight( 0xff0000, 1, 100 ); + * light.position.set( 50, 50, 50 ); + * scene.add( light ); + */ + export class PointLight extends Light { + constructor(hex?: number, intensity?: number, distance?: number); + + /** + * Light's position. + * Default — new THREE.Vector3(). + */ + position: Vector3; + + /* + * Light's intensity. + * Default - 1.0. + */ + intensity: number; + + /** + * If non-zero, light will attenuate linearly from maximum intensity at light position down to zero at distance. + * Default — 0.0. + */ + distance: number; + } + + /** + * A point light that can cast shadow in one direction. + * + * @example + * // white spotlight shining from the side, casting shadow + * var spotLight = new THREE.SpotLight( 0xffffff ); + * spotLight.position.set( 100, 1000, 100 ); + * spotLight.castShadow = true; + * spotLight.shadowMapWidth = 1024; + * spotLight.shadowMapHeight = 1024; + * spotLight.shadowCameraNear = 500; + * spotLight.shadowCameraFar = 4000; + * spotLight.shadowCameraFov = 30; + * scene.add( spotLight ); + */ + export class SpotLight extends Light { + constructor(hex?: number, intensity?: number, distance?: number, angle?: number, exponent?: number); + + /** + * Light's position. + * Default — new THREE.Vector3(). + */ + position: Vector3; + + /** + * Spotlight focus points at target.position. + * Default position — (0,0,0). + */ + target: Object3D; + + /** + * Light's intensity. + * Default — 1.0. + */ + intensity: number; + + /** + * If non-zero, light will attenuate linearly from maximum intensity at light position down to zero at distance. + * Default — 0.0. + */ + distance: number; + + /* + * Maximum extent of the spotlight, in radians, from its direction. + * Default — Math.PI/2. + */ + angle: number; + + /** + * Rapidity of the falloff of light from its target direction. + * Default — 10.0. + */ + exponent: number; + + /** + * If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. + * Default — false. + */ + castShadow: boolean; + + /** + * If set to true light will only cast shadow but not contribute any lighting (as if intensity was 0 but cheaper to compute). + * Default — false. + */ + onlyShadow: boolean; + + /** + * Perspective shadow camera frustum near parameter. + * Default — 50. + */ + shadowCameraNear: number; + + /** + * Perspective shadow camera frustum far parameter. + * Default — 5000. + */ + shadowCameraFar: number; + + /** + * Perspective shadow camera frustum field of view parameter. + * Default — 50. + */ + shadowCameraFov: number; + + /** + * Show debug shadow camera frustum. + * Default — false. + */ + shadowCameraVisible: boolean; + + /** + * Shadow map bias. + * Default — 0. + */ + shadowBias: number; + + /** + * Darkness of shadow casted by this light (from 0 to 1). + * Default — 0.5. + */ + shadowDarkness: number; + + /** + * Shadow map texture width in pixels. + * Default — 512. + */ + shadowMapWidth: number; + + /** + * Shadow map texture height in pixels. + * Default — 512. + */ + shadowMapHeight: number; + shadowMatrix: Matrix4; + + shadowMapSize: Vector2; + shadowCamera: Camera; + shadowMap: RenderTarget; + } + + // Loaders ////////////////////////////////////////////////////////////////////////////////// + + export interface Progress { + total: number; + loaded: number; + } + + /** + * Base class for implementing loaders. + * + * Events: + * load + * Dispatched when the image has completed loading + * content — loaded image + * + * error + * + * Dispatched when the image can't be loaded + * message — error message + */ + export class Loader { + constructor(showStatus?: boolean); + + /** + * If true, show loading status in the statusDomElement. + */ + showStatus: boolean; + + /** + * This is the recipient of status messages. + */ + statusDomElement: HTMLElement; + + /** + * Will be called when load starts. + * The default is a function with empty body. + */ + onLoadStart: () => void; + + /** + * Will be called while load progresses. + * The default is a function with empty body. + */ + onLoadProgress: () => void; + + /** + * Will be called when load completes. + * The default is a function with empty body. + */ + onLoadComplete: () => void; + + /** + * default — null. + * If set, assigns the crossOrigin attribute of the image to the value of crossOrigin, prior to starting the load. + */ + crossOrigin: string; + + needsTangents(materials: Material[]): boolean; + updateProgress(progress: Progress): void; + createMaterial(m: Material, texturePath: string): boolean; + initMaterials(materials: Material[], texturePath: string): Material[]; + extractUrlBase(url: string): string; + addStatusElement(): HTMLElement; + } + + /** + * A loader for loading an image. + * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. + */ + export class ImageLoader extends EventDispatcher { + constructor(); + crossOrigin: string; + + /** + * Begin loading from url + * @param url + */ + load(url: string, onLoad?: (event: any) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement; + setCrossOrigin(crossOrigin: string): void; + } + + + /** + * A loader for loading objects in JSON format. + */ + export class JSONLoader extends Loader { + constructor(showStatus?: boolean); + withCredentials: boolean; + + /** + * @param url + * @param callback. This function will be called with the loaded model as an instance of geometry when the load is completed. + * @param texturePath If not specified, textures will be assumed to be in the same folder as the Javascript model file. + */ + load(url: string, callback: (geometry: Geometry, materials: Material[]) => void , texturePath?: string): void; + parse(json:string, texturePath:string): any; + loadAjaxJSON(context: JSONLoader, url: string, callback: (geometry: Geometry, materials: Material[]) => void , texturePath?: string, callbackProgress?: (progress: Progress) => void ): void; + + } + + /** + * Handles and keeps track of loaded and pending data. + */ + export class LoadingManager { + constructor(onLoad?: (event: any) => void, onProgress?: (event: any) => void, onError?: (event: any) => void); + + /** + * Will be called when load starts. + * The default is a function with empty body. + */ + onLoad: () => void; + + /** + * Will be called while load progresses. + * The default is a function with empty body. + */ + onProgress: (item:any, loaded:number, total:number) => void; + + /** + * Will be called when each element in the scene completes loading. + * The default is a function with empty body. + */ + onError: (event: () => void) => void; + + itemStart(url: string): void; + itemEnd(url: string): void; + + } + + interface SceneLoaderResult{ + scene: Scene; + geometries: {[id:string]:Geometry;}; + face_materials: {[id:string]:Material;}; + materials: {[id:string]:Material;}; + textures: {[id:string]:Texture;}; + objects: {[id:string]:Object3D;}; + cameras: {[id:string]:Camera;}; + lights: {[id:string]:Light;}; + fogs: {[id:string]:IFog;}; + empties: {[id:string]:any;}; + groups: {[id:string]:any;}; + } + + interface SceneLoaderProgress{ + totalModels: number; + totalTextures: number; + loadedModels: number; + loadedTextures: number; + } + + /** + * A loader for loading a complete scene out of a JSON file. + */ + export class SceneLoader { + constructor(); + + /** + * Will be called when load starts. + * The default is a function with empty body. + */ + onLoadStart: () => void; + + /** + * Will be called while load progresses. + * The default is a function with empty body. + */ + onLoadProgress: () => void; + + /** + * Will be called when each element in the scene completes loading. + * The default is a function with empty body. + */ + onLoadComplete: () => void; + + + /** + * Will be called when load completes. + * The default is a function with empty body. + */ + callbackSync: (result: SceneLoaderResult) => void; + + /** + * Will be called as load progresses. + * The default is a function with empty body. + */ + callbackProgress: (progress: SceneLoaderProgress, result: SceneLoaderResult) => void; + hierarchyHandlerMap: any; + geometryHandlerMap: any; + + /** + * @param url + * @param callbackFinished This function will be called with the loaded model as an instance of scene when the load is completed. + */ + load(url: string, callbackFinished: (scene: Scene) => void ): void; + addHierarchyHandler(typeID: string, loaderClass: Object): void; + parse(json: any, callbackFinished: (result: SceneLoaderResult) => void, url: string): void; + addGeometryHandler(typeID: string, loaderClass: Object): void; + } + + /** + * Class for loading a texture. + * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. + */ + export class TextureLoader extends EventDispatcher { + constructor(); + crossOrigin: string; + /** + * Begin loading from url + * + * @param url + */ + load(url: string): void; + } + + // Materials ////////////////////////////////////////////////////////////////////////////////// + + /** + * Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use a different renderer. + */ + export class Material { + constructor(); + + /** + * Unique number of this material instance. + */ + id: number; + + /** + * Material name. Default is an empty string. + */ + name: string; + + /** + * Opacity. Default is 1. + */ + opacity: number; + + /** + * Defines whether this material is transparent. This has an effect on rendering, as transparent objects need an special treatment, and are rendered after the opaque (i.e. non transparent) objects. For a working example of this behaviour, check the {@link WebGLRenderer} code. + * Default is false. + */ + transparent: boolean; + + /** + * Which blending to use when displaying objects with this material. Default is {@link NormalBlending}. + */ + blending: Blending; + + /** + * Blending source. It's one of the blending mode constants defined in Three.js. Default is {@link SrcAlphaFactor}. + */ + blendSrc: BlendingDstFactor; + + /** + * Blending destination. It's one of the blending mode constants defined in Three.js. Default is {@link OneMinusSrcAlphaFactor}. + */ + blendDst: BlendingSrcFactor; + + /** + * Blending equation to use when applying blending. It's one of the constants defined in Three.js. Default is AddEquation. + */ + blendEquation: BlendingEquation; + + /** + * Whether to have depth test enabled when rendering this material. Default is true. + */ + depthTest: boolean; + + /** + * Whether rendering this material has any effect on the depth buffer. Default is true. + * When drawing 2D overlays it can be useful to disable the depth writing in order to layer several things together without creating z-index artifacts. + */ + depthWrite: boolean; + + /** + * Whether to use polygon offset. Default is false. This corresponds to the POLYGON_OFFSET_FILL WebGL feature. + */ + polygonOffset: boolean; + + /** + * Sets the polygon offset factor. Default is 0. + */ + polygonOffsetFactor: number; + + /** + * Sets the polygon offset units. Default is 0. + */ + polygonOffsetUnits: number; + + /** + * Sets the alpha value to be used when running an alpha test. Default is 0. + */ + alphaTest: number; + + /** + * Enables/disables overdraw. If enabled, polygons are drawn slightly bigger in order to fix antialiasing gaps when using the CanvasRenderer. Default is false. + */ + overdraw: boolean; + + /** + * Defines whether this material is visible. Default is true. + */ + visible: boolean; + + /** + * Defines which of the face sides will be rendered - front, back or both. + * Default is THREE.FrontSide. Other options are THREE.BackSide and THREE.DoubleSide. + */ + side: Side; + + /** + * Specifies that the material needs to be updated, WebGL wise. Set it to true if you made changes that need to be reflected in WebGL. + * This property is automatically set to true when instancing a new material. + */ + needsUpdate: boolean; + + clone(): Material; + + dispose(): void; + setValues(values: Object): void; + } + + export interface LineBasicMaterialParameters { + color?: number; + linewidth?: number; + linecap?: string; + linejoin?: string; + vertexColors?: Colors; + fog?: boolean; + } + + export class LineBasicMaterial extends Material { + + constructor(parameters?: LineBasicMaterialParameters); + color: Color; + linewidth: number; + linecap: string; + linejoin: string; + vertexColors: Colors; + fog: boolean; + + clone(): LineBasicMaterial; + } + + export interface LineDashedMaterialParameters { + scale?: number; + color?: number; + vertexColors?: boolean; + dashSize?: number; + fog?: boolean; + gapSize?: number; + linewidth?: number; + } + + export class LineDashedMaterial extends Material { + constructor(parameters?: LineDashedMaterialParameters); + scale: number; + color: Color; + vertexColors: boolean; + dashSize: number; + fog: boolean; + gapSize: number; + linewidth: number; + + clone(): LineDashedMaterial; + } + + + /** + * parameters is an object with one or more properties defining the material's appearance. + */ + export interface MeshBasicMaterialParameters { + color?: number; + wireframe?: boolean; + wireframeLinewidth?: number; + wireframeLinecap?: string; + wireframeLinejoin?: string; + shading?: Shading; + vertexColors?: Colors; + fog?: boolean; + lightMap?: Texture; + specularMap?: Texture; + envMap?: Texture; + skinning?: boolean; + morphTargets?: boolean; + map?: Texture; + combine?: Combine; + reflectivity?: number; + refractionRatio?: number; + } + + export class MeshBasicMaterial extends Material { + constructor(parameters?: MeshBasicMaterialParameters); + + color: Color; + wireframe: boolean; + wireframeLinewidth: number; + wireframeLinecap: string; + wireframeLinejoin: string; + shading: Shading; + vertexColors: Colors; + fog: boolean; + lightMap: Texture; + specularMap: Texture; + envMap: Texture; + skinning: boolean; + morphTargets: boolean; + map: Texture; + combine: Combine; + reflectivity: number; + refractionRatio: number; + + clone(): MeshBasicMaterial; + } + + export interface MeshDepthMaterialParameters { + wireframe?: boolean; + wireframeLinewidth?: number; + } + + export class MeshDepthMaterial extends Material { + constructor(parameters?: MeshDepthMaterialParameters); + wireframe: boolean; + wireframeLinewidth: number; + + clone(): MeshDepthMaterial; + } + + export class MeshFaceMaterial extends Material { + constructor(materials?: Material[]); + materials: Material[]; + + clone(): MeshFaceMaterial; + } + + export interface MeshLambertMaterialParameters { + color?: number; + ambient?: number; + emissive?: number; + shading?: Shading; + wireframe?: boolean; + wireframeLinewidth?: number; + wireframeLinecap?: string; + wireframeLinejoin?: string; + vertexColors?: Colors; + fog?: boolean; + map?: Texture; + lightMap?: Texture; + specularMap?: Texture; + envMap?: Texture; + reflectivity?: number; + refractionRatio?: number; + combine?: Combine; + skinning?: boolean; + morphTargets?: boolean; + wrapRGB?: Vector3; + morphNormals?: boolean; + wrapAround?: boolean; + } + + export class MeshLambertMaterial extends Material { + constructor(parameters?: MeshLambertMaterialParameters); + color: Color; + ambient: Color; + emissive: Color; + shading: Shading; + wireframe: boolean; + wireframeLinewidth: number; + wireframeLinecap: string; + wireframeLinejoin: string; + vertexColors: Colors; + fog: boolean; + map: Texture; + lightMap: Texture; + specularMap: Texture; + envMap: Texture; + reflectivity: number; + refractionRatio: number; + combine: Combine; + skinning: boolean; + morphTargets: boolean; + wrapRGB: Vector3; + morphNormals: boolean; + wrapAround: boolean; + + clone(): MeshLambertMaterial; + } + + export interface MeshNormalMaterialParameters { + morphTargets?: boolean; + shading?: Shading; + wireframe?: boolean; + wireframeLinewidth?: number; + } + + export class MeshNormalMaterial extends Material { + constructor(parameters?: MeshNormalMaterialParameters); + morphTargets: boolean; + shading: Shading; + wireframe: boolean; + wireframeLinewidth: number; + + clone(): MeshNormalMaterial; + } + + export interface MeshPhongMaterialParameters { + color?: number; // diffuse + ambient?: number; + emissive?: number; + specular?: number; + shininess?: number; + shading?: Shading; + wireframe?: boolean; + wireframeLinewidth?: number; + wireframeLinecap?: string; + wireframeLinejoin?: string; + vertexColors?: Colors; + fog?: boolean; + map?: Texture; + lightMap?: Texture; + specularMap?: Texture; + envMap?: Texture; + reflectivity?: number; + refractionRatio?: number; + combine?: Combine; + skinning?: boolean; + morphTargets?: boolean; + normalScale?: Vector2; + morphNormals?: boolean; + metal?: boolean; + bumpScale?: number; + wrapAround?: boolean; + perPixel?: boolean; + normalMap?: Texture; + bumpMap?: Texture; + wrapRGB?: Vector3; + } + + export class MeshPhongMaterial extends Material { + constructor(parameters?: MeshPhongMaterialParameters); + color: Color; // diffuse + ambient: Color; + emissive: Color; + specular: Color; + shininess: number; + shading: Shading; + wireframe: boolean; + wireframeLinewidth: number; + wireframeLinecap: string; + wireframeLinejoin: string; + vertexColors: Colors; + fog: boolean; + map: Texture; + lightMap: Texture; + specularMap: Texture; + envMap: Texture; + reflectivity: number; + refractionRatio: number; + combine: Combine; + skinning: boolean; + morphTargets: boolean; + normalScale: Vector2; + morphNormals: boolean; + metal: boolean; + bumpScale: number; + wrapAround: boolean; + + normalMap: Texture; + bumpMap: Texture; + wrapRGB: Vector3; + + clone(): MeshPhongMaterial; + } + + export interface ParticleSystemMaterialParameters { + color?: number; + map?: Texture; + size?: number; + sizeAttenuation?: boolean; + vertexColors?: boolean; + fog?: boolean; + } + + export class ParticleSystemMaterial extends Material { + constructor(parameters?: ParticleSystemMaterialParameters); + color: Color; + map: Texture; + size: number; + sizeAttenuation: boolean; + vertexColors: boolean; + fog: boolean; + + clone(): ParticleSystemMaterial; + } + + export interface Uniforms { + [name: string]: { type: string; value: any; }; + + color?: { type: string; value: THREE.Color; }; + } + + export interface ShaderMaterialParameters { + uniforms?: Uniforms; + fragmentShader?: string; + vertexShader?: string; + morphTargets?: boolean; + lights?: boolean; + morphNormals?: boolean; + wireframe?: boolean; + vertexColors?: Colors; + skinning?: boolean; + fog?: boolean; + attributes?: any; + shading?: Shading; + linewidth?: number; + wireframeLinewidth?: number; + defines?: any; + } + + export class ShaderMaterial extends Material { + constructor(parameters?: ShaderMaterialParameters); + + uniforms: Uniforms; + fragmentShader: string; + vertexShader: string; + morphTargets: boolean; + lights: boolean; + morphNormals: boolean; + wireframe: boolean; + vertexColors: Colors; + skinning: boolean; + fog: boolean; + attributes: any; + shading: Shading; + linewidth: number; + wireframeLinewidth: number; + defines: any; + + clone(): ShaderMaterial; + } + + export interface SpriteMaterialParameters { + map?: Texture; + uvScale?: Vector2; + sizeAttenuation?: boolean; + color?: number; + uvOffset?: Vector2; + fog?: boolean; + useScreenCoordinates?: boolean; + scaleByViewport?: boolean; + alignment?: Vector2; + } + + export class SpriteMaterial extends Material { + constructor(parameters?: SpriteMaterialParameters); + + map: Texture; + uvScale: Vector2; + sizeAttenuation: boolean; + color: Color; + uvOffset: Vector2; + fog: boolean; + useScreenCoordinates: boolean; + scaleByViewport: boolean; + alignment: Vector2; + + clone(): SpriteMaterial; + } + + export interface SpriteCanvasMaterialParameters { + color?: number; + + } + + export class SpriteCanvasMaterial extends Material { + constructor(parameters?: SpriteCanvasMaterialParameters); + + color: Color; + + program(context: any, color: Color): void; + clone(): SpriteCanvasMaterial; + } + + // Math ////////////////////////////////////////////////////////////////////////////////// + + export class Box2 { + constructor(min?: Vector2, max?: Vector2); + max: Vector2; + min: Vector2; + + set(min: Vector2, max: Vector2): Box2; + expandByPoint(point: Vector2): Box2; + clampPoint(point: Vector2, optionalTarget?: Vector2): Vector2; + isIntersectionBox(box: Box2): boolean; + setFromPoints(points: Vector2[]): Box2; + size(optionalTarget?: Vector2): Vector2; + union(box: Box2): Box2; + getParameter(point: Vector2): Vector2; + expandByScalar(scalar: number): Box2; + intersect(box: Box2): Box2; + containsBox(box: Box2): boolean; + translate(offset: Vector2): Box2; + empty(): boolean; + clone(): Box2; + equals(box: Box2): boolean; + expandByVector(vector: Vector2): Box2; + copy(box: Box2): Box2; + makeEmpty(): Box2; + center(optionalTarget?: Vector2): Vector2; + distanceToPoint(point: Vector2): number; + containsPoint(point: Vector2): boolean; + setFromCenterAndSize(center: Vector2, size: number): Box2; + } + + export class Box3 { + constructor(min?: Vector3, max?: Vector3); + max: Vector3; + min: Vector3; + + set(min: Vector3, max: Vector3): Box3; + applyMatrix4(matrix: Matrix4): Box3; + expandByPoint(point: Vector3): Box3; + clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + isIntersectionBox(box: Box3): boolean; + setFromPoints(points: Vector3[]): Box3; + size(optionalTarget?: Vector3): Vector3; + union(box: Box3): Box3; + getParameter(point: Vector3): Vector3; + expandByScalar(scalar: number): Box3; + intersect(box: Box3): Box3; + containsBox(box: Box3): boolean; + translate(offset: Vector3): Box3; + empty(): boolean; + clone(): Box3; + equals(box: Box3): boolean; + expandByVector(vector: Vector3): Box3; + copy(box: Box3): Box3; + makeEmpty(): Box3; + center(optionalTarget?: Vector3): Vector3; + getBoundingSphere(): Sphere; + distanceToPoint(point: Vector3): number; + containsPoint(point: Vector3): boolean; + setFromCenterAndSize(center: Vector3, size: number): Box3; + } + + export interface HSL { + h: number; + s: number; + l: number; + } + + /** + * Represents a color. See also {@link ColorUtils}. + * + * @example + * var color = new THREE.Color( 0xff0000 ); + * + * @see src/math/Color.js + */ + export class Color { + constructor(hex?: string); + + /** + * @param hex initial color in hexadecimal + */ + constructor(hex?: number); + + /** + * Red channel value between 0 and 1. Default is 1. + */ + r: number; + + /** + * Green channel value between 0 and 1. Default is 1. + */ + g: number; + + /** + * Blue channel value between 0 and 1. Default is 1. + */ + b: number; + + /** + * Copies given color. + * @param color Color to copy. + */ + copy(color: Color): Color; + + /** + * Copies given color making conversion from gamma to linear space. + * @param color Color to copy. + */ + copyGammaToLinear(color: Color): Color; + + /** + * Copies given color making conversion from linear to gamma space. + * @param color Color to copy. + */ + copyLinearToGamma(color: Color): Color; + + /** + * Converts this color from gamma to linear space. + */ + convertGammaToLinear(): Color; + + /** + * Converts this color from linear to gamma space. + */ + convertLinearToGamma(): Color; + + /** + * Sets this color from RGB values. + * @param r Red channel value between 0 and 1. + * @param g Green channel value between 0 and 1. + * @param b Blue channel value between 0 and 1. + */ + setRGB(r: number, g: number, b: number): Color; + + /** + * Returns the hexadecimal value of this color. + */ + getHex(): number; + + /** + * Returns the string formated hexadecimal value of this color. + */ + getHexString(): string; + + setHex(hex: number): Color; + + /** + * Sets this color from a CSS context style string. + * @param contextStyle Color in CSS context style format. + */ + setStyle(style: string): Color; + + /** + * Returns the value of this color in CSS context style. + * Example: rgb(r, g, b) + */ + getStyle(): string; + + /** + * Sets this color from HSL values. + * Based on MochiKit implementation by Bob Ippolito. + * + * @param h Hue channel value between 0 and 1. + * @param s Saturation value channel between 0 and 1. + * @param l Value channel value between 0 and 1. + */ + setHSL(h: number, s: number, l: number): Color; + + getHSL(): HSL; + + offsetHSL(h: number, s: number, l: number): Color; + + add(color: Color): Color; + addColors(color1: Color, color2: Color): Color; + addScalar(s: number): Color; + multiply(color: Color): Color; + multiplyScalar(s: number): Color; + lerp(color: Color, alpha: number): Color; + equals(color: Color): boolean; + + /** + * Clones this color. + */ + clone(): Color; + + set(value: number): void; + set(value: string): void; + } + + export class Euler { + constructor(x?: number, y?: number, z?: number, order?: string); + + x: number; + y: number; + z: number; + order: string; + + set(x: number, y: number, z: number, order?: string): Euler; + copy(euler: Euler): Euler; + setFromRotationMatrix(m: Matrix4, order: string): Euler; + setFromQuaternion(q:Quaternion, order: string): Euler; + reorder(newOrder: string): Euler; + fromArray(xyzo: any[]): Euler; + toArray(): any[]; + equals(euler: Euler): boolean; + clone(): Euler; + } + + /** + * Frustums are used to determine what is inside the camera's field of view. They help speed up the rendering process. + */ + export class Frustum { + constructor(p0?: Plane, p1?: Plane, p2?: Plane, p3?: Plane, p4?: Plane, p5?: Plane); + + /** + * Array of 6 vectors. + */ + planes: Plane[]; + + setFromMatrix(m: Matrix4): Frustum; + intersectsObject(object: Object3D): boolean; + clone(): Frustum; + set(p0?: number, p1?: number, p2?: number, p3?: number, p4?: number, p5?: number): Frustum; + copy(frustum: Frustum): Frustum; + containsPoint(point: Vector3): boolean; + intersectsSphere(sphere: Sphere): boolean; + } + + export class Line3 { + constructor(start?: Vector3, end?: Vector3); + start: Vector3; + end: Vector3; + + set(start?: Vector3, end?: Vector3): Line3; + copy(line: Line3): Line3; + clone(): Line3; + equals(line: Line3): boolean; + distance(): number; + distanceSq(): number; + applyMatrix4(matrix: Matrix4): Line3; + at(t: number, optionalTarget?: Vector3): Vector3; + center(optionalTarget?: Vector3): Vector3; + delta(optionalTarget?: Vector3): Vector3; + closestPointToPoint(point: Vector3, clampToLine?: boolean, optionalTarget?: Vector3): Vector3; + closestPointToPointParameter(point: Vector3, clampToLine?: boolean): number; + } + + interface Math { + /** + * Clamps the x to be between a and b. + * + * @param x Value to be clamped. + * @param a Minimum value + * @param b Maximum value. + */ + clamp(x: number, a: number, b: number): number; + + /** + * Clamps the x to be larger than a. + * + * @param x — Value to be clamped. + * @param a — Minimum value + */ + clampBottom(x: number, a: number): number; + + /** + * Linear mapping of x from range [a1, a2] to range [b1, b2]. + * + * @param x Value to be mapped. + * @param a1 Minimum value for range A. + * @param a2 Maximum value for range A. + * @param b1 Minimum value for range B. + * @param b2 Maximum value for range B. + */ + mapLinear(x: number, a1: number, a2: number, b1: number, b2: number): number; + + /** + * Random float from 0 to 1 with 16 bits of randomness. + * Standard Math.random() creates repetitive patterns when applied over larger space. + */ + random16(): number; + + /** + * Random integer from low to high interval. + */ + randInt(low: number, high: number): number; + + /** + * Random float from low to high interval. + */ + randFloat(low: number, high: number): number; + + /** + * Random float from - range / 2 to range / 2 interval. + */ + randFloatSpread(range: number): number; + + /** + * Returns -1 if x is less than 0, 1 if x is greater than 0, and 0 if x is zero. + */ + sign(x: number): number; + + degToRad(degrees: number): number; + + radToDeg(radians: number): number; + + smoothstep(x: number, min: number, max: number): number; + + smootherstep(x: number, min: number, max: number): number; + } + + /** + * + * @see src/math/Math.js + */ + export var Math: Math; + + /** + * ( interface Matrix<T> ) + */ + export interface Matrix { + /** + * Float32Array with matrix values. + */ + elements: Float32Array; + + /** + * identity():T; + */ + identity(): Matrix; + + /** + * copy(m:T):T; + */ + copy(m: Matrix): Matrix; + + multiplyVector3Array(a: number[]): number[]; + + /** + * multiplyScalar(s:number):T; + */ + multiplyScalar(s: number): Matrix; + + determinant(): number; + + /** + * getInverse(matrix:T, throwOnInvertible?:boolean):T; + */ + getInverse(matrix: Matrix, throwOnInvertible?: boolean): Matrix; + + /** + * transpose():T; + */ + transpose(): Matrix; + + /** + * clone():T; + */ + clone(): Matrix; + } + + /** + * ( class Matrix3 implements Matrix<Matrix3> ) + */ + export class Matrix3 implements Matrix { + /** + * Creates an identity matrix. + */ + constructor(); + + /** + * Initialises the matrix with the supplied n11..n33 values. + */ + constructor(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number); + + /** + * Float32Array with matrix values. + */ + elements: Float32Array; + + /** + * Transposes this matrix in place. + */ + transpose(): Matrix3; + + /** + * Transposes this matrix into the supplied array r, and returns itself. + */ + transposeIntoArray(r: number[]): number[]; + + determinant(): number; + set(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): Matrix3; + multiplyScalar(s: number): Matrix3; + multiplyVector3Array(a: number[]): number[]; + getNormalMatrix(m: Matrix4): Matrix3; + getInverse(matrix: Matrix3, throwOnInvertible?: boolean): Matrix3; + getInverse(matrix: Matrix4, throwOnInvertible?: boolean): Matrix3; + copy(m: Matrix3): Matrix3; + clone(): Matrix3; + identity(): Matrix3; + } + + /** + * A 4x4 Matrix. + * + * @example + * // Simple rig for rotating around 3 axes + * var m = new THREE.Matrix4(); + * var m1 = new THREE.Matrix4(); + * var m2 = new THREE.Matrix4(); + * var m3 = new THREE.Matrix4(); + * var alpha = 0; + * var beta = Math.PI; + * var gamma = Math.PI/2; + * m1.makeRotationX( alpha ); + * m2.makeRotationY( beta ); + * m3.makeRotationZ( gamma ); + * m.multiplyMatrices( m1, m2 ); + * m.multiply( m3 ); + */ + export class Matrix4 implements Matrix { + + /** + * Creates an identity matrix. + */ + constructor(); + + + /** + * Initialises the matrix with the supplied n11..n44 values. + */ + constructor(n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number); + + /** + * Float32Array with matrix values. + */ + elements: Float32Array; + + /** + * Sets all fields of this matrix. + */ + set(n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number): Matrix4; + + /** + * Resets this matrix to identity. + */ + identity(): Matrix4; + + /** + * Copies a matrix m into this matrix. + */ + copy(m: Matrix4): Matrix4; + copyPosition(m: Matrix4): Matrix4; + + /** + * Copies the rotation component of the supplied matrix m into this matrix rotation component. + */ + extractRotation(m: Matrix4): Matrix4; + + /** + * Constructs a rotation matrix, looking from eye towards center with defined up vector. + */ + lookAt(eye: Vector3, target: Vector3, up: Vector3): Matrix4; + + /** + * Multiplies this matrix by m. + */ + multiply(m: Matrix4): Matrix4; + + /** + * Sets this matrix to a x b. + */ + multiplyMatrices(a: Matrix4, b: Matrix4): Matrix4; + + /** + * Sets this matrix to a x b and stores the result into the flat array r. + * r can be either a regular Array or a TypedArray. + */ + multiplyToArray(a: Matrix4, b: Matrix4, r: number[]): Matrix4; + + /** + * Multiplies this matrix by s. + */ + multiplyScalar(s: number): Matrix4; + + /** + * Computes determinant of this matrix. + * Based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + */ + determinant(): number; + + /** + * Transposes this matrix. + */ + transpose(): Matrix4; + + /** + * Flattens this matrix into supplied flat array. + */ + flattenToArray(flat: number[]): number[]; + + /** + * Flattens this matrix into supplied flat array starting from offset position in the array. + */ + flattenToArrayOffset(flat: number[], offset: number): number[]; + + /** + * Sets the position component for this matrix from vector v. + */ + setPosition(v: Vector3): Vector3; + + /** + * Sets this matrix to the inverse of matrix m. + * Based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm. + */ + getInverse(m: Matrix4, throwOnInvertible?: boolean): Matrix4; + + makeRotationFromEuler(euler: Euler): Matrix4; + makeRotationFromQuaternion(q: Quaternion): Matrix4; + + /** + * Multiplies the columns of this matrix by vector v. + */ + scale(v: Vector3): Matrix4; + + /** + * Sets this matrix to the transformation composed of translation, rotation and scale. + */ + compose(translation: Vector3, rotation: Quaternion, scale: Vector3): Matrix4; + + /** + * Decomposes this matrix into the translation, rotation and scale components. + * If parameters are not passed, new instances will be created. + */ + decompose(translation?: Vector3, rotation?: Quaternion, scale?: Vector3): Object[]; // [Vector3, Quaternion, Vector3] + + /** + * Sets this matrix as translation transform. + */ + makeTranslation(x: number, y: number, z: number): Matrix4; + + /** + * Sets this matrix as rotation transform around x axis by theta radians. + * + * @param theta Rotation angle in radians. + */ + makeRotationX(theta: number): Matrix4; + + /** + * Sets this matrix as rotation transform around y axis by theta radians. + * + * @param theta Rotation angle in radians. + */ + makeRotationY(theta: number): Matrix4; + + /** + * Sets this matrix as rotation transform around z axis by theta radians. + * + * @param theta Rotation angle in radians. + */ + makeRotationZ(theta: number): Matrix4; + + /** + * Sets this matrix as rotation transform around axis by angle radians. + * Based on http://www.gamedev.net/reference/articles/article1199.asp. + * + * @param axis Rotation axis. + * @param theta Rotation angle in radians. + */ + makeRotationAxis(axis: Vector3, angle: number): Matrix4; + + /** + * Sets this matrix as scale transform. + */ + makeScale(x: number, y: number, z: number): Matrix4; + + /** + * Creates a frustum matrix. + */ + makeFrustum(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix4; + + /** + * Creates a perspective projection matrix. + */ + makePerspective(fov: number, aspect: number, near: number, far: number): Matrix4; + + /** + * Creates an orthographic projection matrix. + */ + makeOrthographic(left: number, right: number, top: number, bottom: number, near: number, far: number): Matrix4; + + /** + * Clones this matrix. + */ + clone(): Matrix4; + + multiplyVector3Array(a: number[]): number[]; + getMaxScaleOnAxis(): number; + } + + export class Plane { + constructor(normal?: Vector3, constant?: number); + + normal: Vector3; + constant: number; + + normalize(): Plane; + set(normal: Vector3, constant: number): Plane; + copy(plane: Plane): Plane; + applyMatrix4(matrix: Matrix4, optionalNormalMatrix?: Matrix3): Plane; + orthoPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + isIntersectionLine(line: Line3): boolean; + intersectLine(line: Line3, optionalTarget?: Vector3): Vector3; + setFromNormalAndCoplanarPoint(normal: Vector3, point: Vector3): Plane; + clone(): Plane; + distanceToPoint(point: Vector3): number; + equals(plane: Plane): boolean; + setComponents(x: number, y: number, z: number, w: number): Plane; + distanceToSphere(sphere: Sphere): number; + setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): Plane; + projectPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + negate(): Plane; + translate(offset: Vector3): Plane; + coplanarPoint(optionalTarget?: boolean): Vector3; + } + + /** + * Implementation of a quaternion. This is used for rotating things without incurring in the dreaded gimbal lock issue, amongst other advantages. + * + * @example + * var quaternion = new THREE.Quaternion(); + * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 ); + * var vector = new THREE.Vector3( 1, 0, 0 ); + * vector.applyQuaternion( quaternion ); + */ + export class Quaternion { + /** + * @param x x coordinate + * @param y y coordinate + * @param z z coordinate + * @param w w coordinate + */ + constructor(x?: number, y?: number, z?: number, w?: number); + + x: number; + y: number; + z: number; + w: number; + + /** + * Sets values of this quaternion. + */ + set(x: number, y: number, z: number, w: number): Quaternion; + + /** + * Copies values of q to this quaternion. + */ + copy(q: Quaternion): Quaternion; + setFromEuler(euler: Euler, update?: boolean): Quaternion; + /** + * Sets this quaternion from rotation specified by Euler angles. + */ + setFromEuler(v: Vector3, order: string): Quaternion; + + /** + * Sets this quaternion from rotation specified by axis and angle. + * Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm. + * Axis have to be normalized, angle is in radians. + */ + setFromAxisAngle(axis: Vector3, angle: number): Quaternion; + + /** + * Sets this quaternion from rotation component of m. Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm. + */ + setFromRotationMatrix(m: Matrix4): Quaternion; + + /** + * Inverts this quaternion. + */ + inverse(): Quaternion; + /** + * Computes length of this quaternion. + */ + length(): number; + + /** + * Normalizes this quaternion. + */ + normalize(): Quaternion; + + /** + * Multiplies this quaternion by b. + */ + multiply(q: Quaternion): Quaternion; + + /** + * Sets this quaternion to a x b + * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm. + */ + multiplyQuaternions(a: Quaternion, b: Quaternion): Quaternion; + + multiplyVector3(vector: Vector3, dest: Vector3): Quaternion; + + /** + * Clones this quaternion. + */ + clone(): Quaternion; + + /** + * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/. + */ + static slerp(qa: Quaternion, qb: Quaternion, qm: Quaternion, t: number): Quaternion; + + slerp(qb: Quaternion, t: number): Quaternion; + + toArray(): number[]; + + equals(v: Quaternion): boolean; + + lengthSq(): number; + + fromArray(n: number[]): Quaternion; + + conjugate(): Quaternion; + } + + export class Ray { + constructor(origin?: Vector3, direction?: Vector3); + + origin: Vector3; + direction: Vector3; + + applyMatrix4(matrix4: Matrix4): Ray; + at(t: number, optionalTarget?: Vector3): Vector3; + clone(): Ray; + closestPointToPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + copy(ray: Ray): Ray; + distanceSqToSegment(v0: Vector3, v1: Vector3, optionalPointOnRay?: Vector3, optionalPointOnSegment?: Vector3): number; + distanceToPlane(plane: Plane): number; + distanceToPoint(point: Vector3): number; + equals(ray: Ray): boolean; + intersectBox(box: Box3, optionalTarget?: Vector3): Vector3; + intersectPlane(plane: Plane, optionalTarget?: Vector3): Vector3; + intersectTriangle(a: Vector3, b: Vector3, c: Vector3, backfaceCulling: boolean, optionalTarget?: Vector3): Vector3; + isIntersectionBox(box: Box3): boolean; + isIntersectionPlane(plane: Plane): boolean; + isIntersectionSphere(sphere: Sphere): boolean; + recast(t: number): Ray; + set(origin: Vector3, direction: Vector3): Ray; + } + + export class Sphere { + constructor(center?: Vector3, radius?: number); + + center: Vector3; + radius: number; + + set(center: Vector3, radius: number): Sphere; + applyMatrix4(matrix: Matrix4): Sphere; + clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + translate(offset: Vector3): Sphere; + clone(): Sphere; + equals(sphere: Sphere): boolean; + setFromPoints(points: Vector3[], optionalCenter?: Vector3): Sphere; + distanceToPoint(point: Vector3): number; + getBoundingBox(optionalTarget?: Box3): Box3; + containsPoint(point: Vector3): boolean; + copy(sphere: Sphere): Sphere; + intersectsSphere(sphere: Sphere): boolean; + empty(): boolean; + } + + export interface SplineControlPoint { + x: number; + y: number; + z: number; + } + + /** + * Represents a spline. + * + * @see src/math/Spline.js + */ + export class Spline { + /** + * Initialises the spline with points, which are the places through which the spline will go. + */ + constructor(points: SplineControlPoint[]); + + points: SplineControlPoint[]; + + /** + * Initialises using the data in the array as a series of points. Each value in a must be another array with three values, where a[n] is v, the value for the nth point, and v[0], v[1] and v[2] are the x, y and z coordinates of that point n, respectively. + * + * @param a array of triplets containing x, y, z coordinates + */ + initFromArray(a: number[][]): void; + + /** + * Return the interpolated point at k. + * + * @param k point index + */ + getPoint(k: number): SplineControlPoint; + + /** + * Returns an array with triplets of x, y, z coordinates that correspond to the current control points. + */ + getControlPointsArray(): number[][]; + + /** + * Returns the length of the spline when using nSubDivisions. + * @param nSubDivisions number of subdivisions between control points. Default is 100. + */ + getLength(nSubDivisions?: number): { chunks: number[]; total: number; }; + + /** + * Modifies the spline so that it looks similar to the original but has its points distributed in such way that moving along the spline it's done at a more or less constant speed. The points should also appear more uniformly spread along the curve. + * This is done by resampling the original spline, with the density of sampling controlled by samplingCoef. Here it's interesting to note that denser sampling is not necessarily better: if sampling is too high, you may get weird kinks in curvature. + * + * @param samplingCoef how many intermediate values to use between spline points + */ + reparametrizeByArcLength(samplingCoef: number): void; + } + + class Triangle { + constructor(a?: Vector3, b?: Vector3, c?: Vector3); + + a: Vector3; + b: Vector3; + c: Vector3; + + setFromPointsAndIndices(points: Vector3[], i0: number, i1: number, i2: number): Triangle; + set(a: Vector3, b: Vector3, c: Vector3): Triangle; + normal(optionalTarget?: Vector3): Vector3; + barycoordFromPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + clone(): Triangle; + area(): number; + midpoint(optionalTarget?: Vector3): Vector3; + equals(triangle: Triangle): boolean; + plane(optionalTarget?: Vector3): Plane; + containsPoint(point: Vector3): boolean; + copy(triangle: Triangle): Triangle; + + static normal(a: Vector3, b: Vector3, c: Vector3, optionalTarget?: Vector3): Vector3; + static barycoordFromPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3, optionalTarget: Vector3): Vector3; + static containsPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3): boolean; + } + + + /** + * ( interface Vector<T> ) + * + * Abstruct interface of Vector2, Vector3 and Vector4. + * Currently the members of Vector is NOT type safe because it accepts different typed vectors. + * Those definitions will be changed when TypeScript innovates Generics to be type safe. + * + * @example + * var v:THREE.Vector = new THREE.Vector3(); + * v.addVectors(new THREE.Vector2(0, 1), new THREE.Vector2(2, 3)); // invalid but compiled successfully + */ + export interface Vector { + setComponent(index: number, value: number): void; + + getComponent(index: number): number; + + /** + * copy(v:T):T; + */ + copy(v: Vector): Vector; + + /** + * add(v:T):T; + */ + add(v: Vector): Vector; + + /** + * addVectors(a:T, b:T):T; + */ + addVectors(a: Vector, b: Vector): Vector; + + /** + * sub(v:T):T; + */ + sub(v: Vector): Vector; + + /** + * subVectors(a:T, b:T):T; + */ + subVectors(a: Vector, b: Vector): Vector; + + /** + * multiplyScalar(s:number):T; + */ + multiplyScalar(s: number): Vector; + + /** + * divideScalar(s:number):T; + */ + divideScalar(s: number): Vector; + + /** + * negate():T; + */ + negate(): Vector; + + /** + * dot(v:T):T; + */ + dot(v: Vector): number; + + /** + * lengthSq():number; + */ + lengthSq(): number; + + /** + * length():number; + */ + length(): number; + + /** + * normalize():T; + */ + normalize(): Vector; + + /** + * NOTE: Vector4 doesn't have the property. + * + * distanceTo(v:T):number; + */ + distanceTo(v: Vector): number; + + /** + * NOTE: Vector4 doesn't have the property. + * + * distanceToSquared(v:T):number; + */ + distanceToSquared(v: Vector): number; + + /** + * setLength(l:number):T; + */ + setLength(l: number): Vector; + + /** + * lerp(v:T, alpha:number):T; + */ + lerp(v: Vector, alpha: number): Vector; + + /** + * equals(v:T):boolean; + */ + equals(v: Vector): boolean; + + /** + * clone():T; + */ + clone(): Vector; + } + + /** + * 2D vector. + * + * ( class Vector2 implements Vector ) + */ + export class Vector2 implements Vector { + constructor(x?: number, y?: number); + + x: number; + y: number; + + /** + * Sets value of this vector. + */ + set(x: number, y: number): Vector2; + + /** + * Copies value of v to this vector. + */ + copy(v: Vector2): Vector2; + + /** + * Adds v to this vector. + */ + add(v: Vector2): Vector2; + + /** + * Sets this vector to a + b. + */ + addVectors(a: Vector2, b: Vector2): Vector2; + + /** + * Subtracts v from this vector. + */ + sub(v: Vector2): Vector2; + + /** + * Sets this vector to a - b. + */ + subVectors(a: Vector2, b: Vector2): Vector2; + + /** + * Multiplies this vector by scalar s. + */ + multiplyScalar(s: number): Vector2; + + /** + * Divides this vector by scalar s. + * Set vector to ( 0, 0 ) if s == 0. + */ + divideScalar(s: number): Vector2; + + /** + * Inverts this vector. + */ + negate(): Vector2; + + /** + * Computes dot product of this vector and v. + */ + dot(v: Vector2): number; + + /** + * Computes squared length of this vector. + */ + lengthSq(): number; + + /** + * Computes length of this vector. + */ + length(): number; + + /** + * Normalizes this vector. + */ + normalize(): Vector2; + + /** + * Computes distance of this vector to v. + */ + distanceTo(v: Vector2): number; + + /** + * Computes squared distance of this vector to v. + */ + distanceToSquared(v: Vector2): number; + + /** + * Normalizes this vector and multiplies it by l. + */ + setLength(l: number): Vector2; + + /** + * Checks for strict equality of this vector and v. + */ + equals(v: Vector2): boolean; + + /** + * Clones this vector. + */ + clone(): Vector2; + + clamp(min: Vector2, max: Vector2): Vector2; + clampScalar(min: number, max: number): Vector2; + floor(): Vector2; + ceil(): Vector2; + round(): Vector2; + roundToZero(): Vector2; + lerp(v: Vector2, alpha: number): Vector2; + + /** + * Sets a component of this vector. + */ + setComponent(index: number, value: number): void; + + addScalar(s: number): Vector2; + + /** + * Gets a component of this vector. + */ + getComponent(index: number): number; + + fromArray(xy: number[]): Vector2; + + toArray(): number[]; + + min(v: Vector2): Vector2; + + max(v: Vector2): Vector2; + + /** + * Sets X component of this vector. + */ + setX(x: number): Vector2; + + /** + * Sets Y component of this vector. + */ + setY(y: number): Vector2; + } + + /** + * 3D vector. + * + * @example + * var a = new THREE.Vector3( 1, 0, 0 ); + * var b = new THREE.Vector3( 0, 1, 0 ); + * var c = new THREE.Vector3(); + * c.crossVectors( a, b ); + * + * @see src/math/Vector3.js + * + * ( class Vector3 implements Vector ) + */ + export class Vector3 implements Vector { + + constructor(x?: number, y?: number, z?: number); + + x: number; + y: number; + z: number; + + /** + * Sets value of this vector. + */ + set(x: number, y: number, z: number): Vector3; + + /** + * Sets x value of this vector. + */ + setX(x: number): Vector3; + + /** + * Sets y value of this vector. + */ + setY(y: number): Vector3; + + /** + * Sets z value of this vector. + */ + setZ(z: number): Vector3; + + /** + * Copies value of v to this vector. + */ + copy(v: Vector3): Vector3; + + /** + * Adds v to this vector. + */ + add(a: Object): Vector3; + + /** + * Sets this vector to a + b. + */ + addVectors(a: Vector3, b: Vector3): Vector3; + + /** + * Subtracts v from this vector. + */ + sub(a: Vector3): Vector3; + + /** + * Sets this vector to a - b. + */ + subVectors(a: Vector3, b: Vector3): Vector3; + + /** + * Multiplies this vector by scalar s. + */ + multiplyScalar(s: number): Vector3; + + /** + * Divides this vector by scalar s. + * Set vector to ( 0, 0, 0 ) if s == 0. + */ + divideScalar(s: number): Vector3; + + /** + * Inverts this vector. + */ + negate(): Vector3; + + /** + * Computes dot product of this vector and v. + */ + dot(v: Vector3): number; + + /** + * Computes squared length of this vector. + */ + lengthSq(): number; + + /** + * Computes length of this vector. + */ + length(): number; + + /** + * Computes Manhattan length of this vector. + * http://en.wikipedia.org/wiki/Taxicab_geometry + */ + lengthManhattan(): number; + + /** + * Normalizes this vector. + */ + normalize(): Vector3; + + /** + * Computes distance of this vector to v. + */ + distanceTo(v: Vector3): number; + + /** + * Computes squared distance of this vector to v. + */ + distanceToSquared(v: Vector3): number; + + /** + * Normalizes this vector and multiplies it by l. + */ + setLength(l: number): Vector3; + + /** + * Sets this vector to cross product of itself and v. + */ + cross(a: Vector3): Vector3; + + /** + * Sets this vector to cross product of a and b. + */ + crossVectors(a: Vector3, b: Vector3): Vector3; + + setFromMatrixPosition(m: Matrix4): Vector3; + setFromMatrixScale(m: Matrix4): Vector3; + /** + * Checks for strict equality of this vector and v. + */ + equals(v: Vector3): boolean; + /** + * Clones this vector. + */ + clone(): Vector3; + clamp(min: Vector3, max: Vector3): Vector3; + clampScalar(min: number, max: number): Vector3; + floor(): Vector3; + ceil(): Vector3; + round(): Vector3; + roundToZero(): Vector3; + applyMatrix3(m: Matrix3): Vector3; + applyMatrix4(m: Matrix4): Vector3; + projectOnPlane(planeNormal: Vector3): Vector3; + projectOnVector(v: Vector3): Vector3; + addScalar(s: number): Vector3; + divide(v: Vector3): Vector3; + min(v: Vector3): Vector3; + max(v: Vector3): Vector3; + setComponent(index: number, value: number): void; + transformDirection(m: Matrix4): Vector3; + multiplyVectors(a: Vector3, b: Vector3): Vector3; + getComponent(index: number): number; + applyAxisAngle(axis: Vector3, angle: number): Vector3; + lerp(v: Vector3, alpha: number): Vector3; + angleTo(v: Vector3): number; + setFromMatrixColumn(index: number, matrix: Matrix4): Vector3; + reflect(vector: Vector3): Vector3; + fromArray(xyz: number[]): Vector3; + multiply(v: Vector3): Vector3; + applyProjection(m: Matrix4): Vector3; + toArray(): number[]; + applyEuler(euler: Euler): Vector3; + applyQuaternion(q: Quaternion): Vector3; + } + + /** + * 4D vector. + * + * ( class Vector4 implements Vector ) + */ + export class Vector4 implements Vector { + constructor(x?: number, y?: number, z?: number, w?: number); + x: number; + y: number; + z: number; + w: number; + + /** + * Sets value of this vector. + */ + set(x: number, y: number, z: number, w: number): Vector4; + /** + * Copies value of v to this vector. + */ + copy(v: Vector4): Vector4; + + /** + * Adds v to this vector. + */ + add(v: Vector4): Vector4; + + /** + * Sets this vector to a + b. + */ + addVectors(a: Vector4, b: Vector4): Vector4; + + /** + * Subtracts v from this vector. + */ + sub(v: Vector4): Vector4; + + /** + * Sets this vector to a - b. + */ + subVectors(a: Vector4, b: Vector4): Vector4; + + /** + * Multiplies this vector by scalar s. + */ + multiplyScalar(s: number): Vector4; + + /** + * Divides this vector by scalar s. + * Set vector to ( 0, 0, 0 ) if s == 0. + */ + divideScalar(s: number): Vector4; + /** + * Inverts this vector. + */ + negate(): Vector4; + + /** + * Computes dot product of this vector and v. + */ + dot(v: Vector4): number; + + /** + * Computes squared length of this vector. + */ + lengthSq(): number; + + /** + * Computes length of this vector. + */ + length(): number; + + /** + * Normalizes this vector. + */ + normalize(): Vector4; + /** + * Normalizes this vector and multiplies it by l. + */ + setLength(l: number): Vector4; + + /** + * Linearly interpolate between this vector and v with alpha factor. + */ + lerp(v: Vector4, alpha: number): Vector4; + /** + * Clones this vector. + */ + clone(): Vector4; + clamp(min: Vector4, max: Vector4): Vector4; + clampScalar(min: number, max: number): Vector4; + floor(): Vector4; + ceil(): Vector4; + round(): Vector4; + roundToZero(): Vector4; + applyMatrix4(m: Matrix4): Vector4; + min(v: Vector4): Vector4; + max(v: Vector4): Vector4; + addScalar(s: number): Vector4; + + /** + * Checks for strict equality of this vector and v. + */ + equals(v: Vector4): boolean; + + /** + * http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + * @param m assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + */ + setAxisAngleFromRotationMatrix(m: Matrix3): Vector4; + + /** + * http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + * @param q is assumed to be normalized + */ + setAxisAngleFromQuaternion(q: Quaternion): Vector4; + + getComponent(index: number): number; + setComponent(index: number, value: number): void; + fromArray(xyzw: number[]): number[]; + toArray(): number[]; + lengthManhattan(): number; + /** + * Sets X component of this vector. + */ + setX(x: number): Vector2; + + /** + * Sets Y component of this vector. + */ + setY(y: number): Vector2; + + /** + * Sets Z component of this vector. + */ + setZ(z: number): Vector2; + + /** + * Sets w component of this vector. + */ + setW(w: number): Vector2; + + /** + * NOTE: Vector4 doesn't have the property. + * + * distanceToSquared(v:T):number; + */ + distanceTo(v: Vector): number; + + /** + * NOTE: Vector4 doesn't have the property. + * + * distanceToSquared(v:T):number; + */ + distanceToSquared(v: Vector): number; + } + + // Objects ////////////////////////////////////////////////////////////////////////////////// + + export class Bone extends Object3D { + constructor(belongsToSkin: SkinnedMesh); + + skinMatrix: Matrix4; + skin: SkinnedMesh; + update(parentSkinMatrix?: Matrix4, forceUpdate?: boolean): void; + } + + export class Line extends Object3D { + constructor(geometry?: Geometry, material?: LineDashedMaterial, type?: number); + constructor(geometry?: Geometry, material?: LineBasicMaterial, type?: number); + constructor(geometry?: Geometry, material?: ShaderMaterial, type?: number); + constructor(geometry?: BufferGeometry, material?: LineDashedMaterial, type?: number); + constructor(geometry?: BufferGeometry, material?: LineBasicMaterial, type?: number); + constructor(geometry?: BufferGeometry, material?: ShaderMaterial, type?: number); + geometry: Geometry; + material: Material; + type: LineType; + clone(object?: Line): Line; + } + + enum LineType{} + var LineStrip: LineType; + var LinePieces: LineType; + + export class LOD extends Object3D { + constructor(); + + objects: any[]; + addLevel(object: Object3D, distance?: number): void; + getObjectForDistance(distance: number): Object3D; + update(camera: Camera): void; + clone(): LOD; + } + + export class Mesh extends Object3D { + constructor(geometry?: Geometry, material?: Material); + constructor(geometry?: BufferGeometry, material?: Material); + + geometry: Geometry; + material: Material; + + getMorphTargetIndexByName(name: string): number; + updateMorphTargets(): void; + clone(object?: Mesh): Mesh; + } + + export class MorphAnimMesh extends Mesh { + constructor(geometry?: Geometry, material?: MeshBasicMaterial); + constructor(geometry?: Geometry, material?: MeshDepthMaterial); + constructor(geometry?: Geometry, material?: MeshFaceMaterial); + constructor(geometry?: Geometry, material?: MeshLambertMaterial); + constructor(geometry?: Geometry, material?: MeshNormalMaterial); + constructor(geometry?: Geometry, material?: MeshPhongMaterial); + constructor(geometry?: Geometry, material?: ShaderMaterial); + + directionBackwards: boolean; + direction: number; + endKeyframe: number; + mirroredLoop: boolean; + startKeyframe: number; + lastKeyframe: number; + length: number; + time: number; + duration: number; // milliseconds + currentKeyframe: number; + + setDirectionForward(): void; + playAnimation(label: string, fps: number): void; + setFrameRange(start: number, end: number): void; + setDirectionBackward(): void; + parseAnimations(): void; + updateAnimation(delta: number): void; + setAnimationLabel(label: string, start: number, end: number): void; + + clone(object?: MorphAnimMesh): MorphAnimMesh; + } + + /** + * A class for displaying particles in the form of variable size points. For example, if using the WebGLRenderer, the particles are displayed using GL_POINTS. + * + * @see src/objects/ParticleSystem.js + */ + export class ParticleSystem extends Object3D { + + /** + * @param geometry An instance of Geometry. + * @param material An instance of Material (optional). + */ + constructor(geometry: Geometry, material?: ParticleSystemMaterial); + constructor(geometry: Geometry, material?: ShaderMaterial); + constructor(geometry: BufferGeometry, material?: ParticleSystemMaterial); + constructor(geometry: BufferGeometry, material?: ShaderMaterial); + + /** + * An instance of Geometry, where each vertex designates the position of a particle in the system. + */ + geometry: Geometry; + + /** + * An instance of Material, defining the object's appearance. Default is a ParticleBasicMaterial with randomised colour. + */ + material: Material; + + /** + * Specifies whether the particle system will be culled if it's outside the camera's frustum. By default this is set to false. + */ + frustrumCulled: boolean; + + sortParticles: boolean; + + clone(object?: ParticleSystem): ParticleSystem; + } + + export class SkinnedMesh extends Mesh { + constructor(geometry?: Geometry, material?: MeshBasicMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry, material?: MeshDepthMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry, material?: MeshFaceMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry, material?: MeshLambertMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry, material?: MeshNormalMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry, material?: MeshPhongMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry, material?: ShaderMaterial, useVertexTexture?: boolean); + + bones: Bone[]; + identityMatrix: Matrix4; + useVertexTexture: boolean; + boneMatrices: Float32Array; + + pose(): void; + addBone(bone?: Bone): Bone; + clone(object?: SkinnedMesh): SkinnedMesh; + } + + export class Sprite extends Object3D { + constructor(material?: Material); + + material: Material; + + updateMatrix(): void; + clone(object?: Sprite): Sprite; + } + + + // Renderers ////////////////////////////////////////////////////////////////////////////////// + + export interface Renderer { + render(scene: Scene, camera: Camera): void; + } + + export interface CanvasRendererParameters { + canvas?: HTMLCanvasElement; + devicePixelRatio?: number; + } + + export class CanvasRenderer implements Renderer { + constructor(parameters?: CanvasRendererParameters); + + info: { render: { vertices: number; faces: number; }; }; + domElement: HTMLCanvasElement; + devicePixelRatio: number; + autoClear: boolean; + sortObjects: boolean; + sortElements: boolean; + + getMaxAnisotropy(): number; + render(scene: Scene, camera: Camera): void; + clear(): void; + setClearColor(color: Color, opacity?: number): void; + setFaceCulling(): void; + supportsVertexTextures(): void; + setSize(width: number, height: number, updateStyle?: boolean): void; + setClearColorHex(hex: number, alpha?: number): void; + } + + export interface RendererPlugin { + init(renderer: WebGLRenderer): void; + render(scene: Scene, camera: Camera, currentWidth: number, currentHeight: number): void; + } + + export interface WebGLRendererParameters { + /** + * A Canvas where the renderer draws its output. + */ + canvas?: HTMLCanvasElement; + + /** + * shader precision. Can be "highp", "mediump" or "lowp". + */ + precision?: string; + + /** + * default is true. + */ + alpha?: boolean; + + /** + * default is true. + */ + premultipliedAlpha?: boolean; + + /** + * default is false. + */ + antialias?: boolean; + + /** + * default is true. + */ + stencil?: boolean; + + /** + * default is false. + */ + preserveDrawingBuffer?: boolean; + + /** + * default is 0x000000. + */ + clearColor?: number; + + /** + * default is 0. + */ + clearAlpha?: number; + + devicePixelRatio?: number; + } + + + /** + * The WebGL renderer displays your beautifully crafted scenes using WebGL, if your device supports it. + * This renderer has way better performance than CanvasRenderer. + * + * @see src/renderers/WebGLRenderer.js + */ + export class WebGLRenderer implements Renderer { + /** + * parameters is an optional object with properties defining the renderer's behaviour. The constructor also accepts no parameters at all. In all cases, it will assume sane defaults when parameters are missing. + */ + constructor(parameters?: WebGLRendererParameters); + + /** + * A Canvas where the renderer draws its output. + * This is automatically created by the renderer in the constructor (if not provided already); you just need to add it to your page. + */ + domElement: HTMLCanvasElement; + + /** + * The HTML5 Canvas's 'webgl' context obtained from the canvas where the renderer will draw. + */ + // If you are using three.d.ts with other complete definitions of webgl, context:WebGLRenderingContext is suitable. + //context:WebGLRenderingContext; + context: any; + + /** + * Defines whether the renderer should automatically clear its output before rendering. + */ + autoClear: boolean; + + /** + * If autoClear is true, defines whether the renderer should clear the color buffer. Default is true. + */ + autoClearColor: boolean; + + /** + * If autoClear is true, defines whether the renderer should clear the depth buffer. Default is true. + */ + autoClearDepth: boolean; + + /** + * If autoClear is true, defines whether the renderer should clear the stencil buffer. Default is true. + */ + autoClearStencil: boolean; + + /** + * Defines whether the renderer should sort objects. Default is true. + */ + sortObjects: boolean; + + /** + * Defines whether the renderer should auto update objects. Default is true. + */ + autoUpdateObjects: boolean; + + /** + * Default is false. + */ + gammaInput: boolean; + + /** + * Default is false. + */ + gammaOutput: boolean; + + /** + * Default is false. + */ + shadowMapEnabled: boolean; + + /** + * Default is true. + */ + shadowMapAutoUpdate: boolean; + + /** + * Defines shadow map type (unfiltered, percentage close filtering, percentage close filtering with bilinear filtering in shader) + * Options are THREE.BasicShadowMap, THREE.PCFShadowMap, THREE.PCFSoftShadowMap. Default is THREE.PCFShadowMap. + */ + shadowMapType: ShadowMapType; + + /** + * Default is true + */ + shadowMapCullFace: CullFace; + + /** + * Default is false. + */ + shadowMapDebug: boolean; + + /** + * Default is false. + */ + shadowMapCascade: boolean; + + /** + * Default is 8. + */ + maxMorphTargets: number; + + /** + * Default is 4. + */ + maxMorphNormals: number; + + /** + * Default is true. + */ + autoScaleCubemaps: boolean; + + /** + * An array with render plugins to be applied before rendering. + * Default is an empty array, or []. + */ + renderPluginsPre: RendererPlugin[]; + + /** + * An array with render plugins to be applied after rendering. + * Default is an empty array, or []. + */ + renderPluginsPost: RendererPlugin[]; + + /** + * An object with a series of statistical information about the graphics board memory and the rendering process. Useful for debugging or just for the sake of curiosity. The object contains the following fields: + */ + info: { + memory: { + programs: number; + geometries: number; + textures: number; + }; + render: { + calls: number; + vertices: number; + faces: number; + points: number; + }; + }; + + shadowMapPlugin: ShadowMapPlugin; + devicePixelRatio: number; + + /** + * Return the WebGL context. + */ + getContext(): WebGLRenderingContext; + + /** + * Return a Boolean true if the context supports vertex textures. + */ + supportsVertexTextures(): boolean; + + /** + * Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0). + */ + setSize(width: number, height: number): void; + + /** + * Sets the viewport to render from (x, y) to (x + width, y + height). + */ + setViewport(x?: number, y?: number, width?: number, height?: number): void; + + /** + * Sets the scissor area from (x, y) to (x + width, y + height). + */ + setScissor(x: number, y: number, width: number, height: number): void; + + /** + * Enable the scissor test. When this is enabled, only the pixels within the defined scissor area will be affected by further renderer actions. + */ + enableScissorTest(enable: boolean): void; + + /** + * Sets the clear color, using color for the color and alpha for the opacity. + */ + setClearColor(color: Color, alpha: number): void; + + /** + * Returns a THREE.Color instance with the current clear color. + */ + getClearColor(): Color; + + /** + * Returns a float with the current clear alpha. Ranges from 0 to 1. + */ + getClearAlpha(): number; + + /** + * Tells the renderer to clear its color, depth or stencil drawing buffer(s). + * If no parameters are passed, no buffer will be cleared. + */ + clear(color?: boolean, depth?: boolean, stencil?: boolean): void; + + /** + * Initialises the postprocessing plugin, and adds it to the renderPluginsPost array. + */ + addPostPlugin(plugin: RendererPlugin): void; + + /** + * Initialises the preprocessing plugin, and adds it to the renderPluginsPre array. + */ + addPrePlugin(plugin: RendererPlugin): void; + + /** + * Tells the shadow map plugin to update using the passed scene and camera parameters. + * + * @param scene an instance of Scene + * @param camera — an instance of Camera + */ + updateShadowMap(scene: Scene, camera: Camera): void; + + renderBufferImmediate(object: Object3D, program: Object, material: Material): void; + + renderBufferDirect(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; + + renderBuffer(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; + + /** + * Render a scene using a camera. + * The render is done to the renderTarget (if specified) or to the canvas as usual. + * If forceClear is true, the canvas will be cleared before rendering, even if the renderer's autoClear property is false. + */ + render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; + renderImmediateObject(camera: Camera, lights: Light[], fog: Fog, material: Material, object: Object3D): void; + initWebGLObjects(scene: Scene): void; + initMaterial(material: Material, lights: Light[], fog: Fog, object: Object3D): void; + + /** + * Used for setting the gl frontFace, cullFace states in the GPU, thus enabling/disabling face culling when rendering. + * If cullFace is false, culling will be disabled. + * @param cullFace "back", "front", "front_and_back", or false. + * @param frontFace "ccw" or "cw + */ + setFaceCulling(cullFace?: string, frontFace?: FrontFaceDirection): void; + setDepthTest(depthTest: boolean): void; + setDepthWrite(depthWrite: boolean): void; + setBlending(blending: Blending, blendEquation: BlendingEquation, blendSrc: BlendingSrcFactor, blendDst: BlendingDstFactor): void; + setTexture(texture: Texture, slot: number): void; + setRenderTarget(renderTarget: RenderTarget): void; + supportsCompressedTextureS3TC(): any; + getMaxAnisotropy(): number; + getPrecision(): string; + setMaterialFaces(material: Material): void; + supportsStandardDerivatives(): any; + supportsFloatTextures(): any; + clearTarget(renderTarget:WebGLRenderTarget, color: boolean, depth: boolean, stencil: boolean): void; + + /** + * Sets the clear color, using hex for the color and alpha for the opacity. + * + * @example + * // Creates a renderer with black background + * var renderer = new THREE.WebGLRenderer(); + * renderer.setSize(200, 100); + * renderer.setClearColorHex(0x000000, 1); + */ + setClearColorHex(hex: number, alpha: number): void; + } + + export interface RenderTarget { + } + + export interface WebGLRenderTargetOptions { + wrapS?: Wrapping; + wrapT?: Wrapping; + magFilter?: TextureFilter; + minFilter?: TextureFilter; + anisotropy?: number; // 1; + format?: number; // RGBAFormat; + type?: TextureDataType; // UnsignedByteType; + depthBuffer?: boolean; // true; + stencilBuffer?: boolean; // true; + } + + export class WebGLRenderTarget implements RenderTarget { + constructor(width: number, height: number, options?: WebGLRenderTargetOptions); + width: number; + height: number; + wrapS: Wrapping; + wrapT: Wrapping; + magFilter: TextureFilter; + minFilter: TextureFilter; + anisotropy: number; + offset: Vector2; + repeat: Vector2; + format: number; + type: number; + depthBuffer: boolean; + stencilBuffer: boolean; + generateMipmaps: boolean; + clone(): WebGLRenderTarget; + dispose(): void; + } + + export class WebGLRenderTargetCube extends WebGLRenderTarget { + constructor(width: number, height: number, options?: WebGLRenderTargetOptions); + activeCubeFace: number; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 + } + + // Renderers / Renderables ///////////////////////////////////////////////////////////////////// + + export class RenderableFace { + constructor(); + + vertexNormalsModelView: Vector3[]; + normalWorld: Vector3; + color: number; + material: Material; + uvs: Vector2[][]; + v1: RenderableVertex; + v2: RenderableVertex; + v3: RenderableVertex; + normalModelView: Vector3; + centroidModel: Vector3; + vertexNormalsLength: number; + z: number; + vertexNormalsModel: Vector3[]; + } + + export class RenderableLine { + constructor(); + + v1: RenderableVertex; + v2: RenderableVertex; + z: number; + material: Material; + } + + export class RenderableObject { + constructor(); + + object: Object; + z: number; + id: number; + } + + export class RenderableParticle { + constructor(); + + scale: Vector2; + material: Material; + object: Object; + y: number; + x: number; + rotation: number; + z: number; + } + + export class RenderableVertex { + constructor(); + + visible: boolean; + positionScreen: Vector4; + positionWorld: Vector3; + + copy(vertex: RenderableVertex): void; + } + + // Shaders ///////////////////////////////////////////////////////////////////// + export interface ShaderChunk { + [name: string]: string; + fog_pars_fragment: string; + fog_fragment: string; + envmap_pars_fragment: string; + envmap_fragment: string; + envmap_pars_vertex: string; + worldpos_vertex: string; + envmap_vertex: string; + map_particle_pars_fragment: string; + map_particle_fragment: string; + map_pars_vertex: string; + map_pars_fragment: string; + map_vertex: string; + map_fragment: string; + lightmap_pars_fragment: string; + lightmap_pars_vertex: string; + lightmap_fragment: string; + lightmap_vertex: string; + bumpmap_pars_fragment: string; + normalmap_pars_fragment: string; + specularmap_pars_fragment: string; + specularmap_fragment: string; + lights_lambert_pars_vertex: string; + lights_lambert_vertex: string; + lights_phong_pars_vertex: string; + lights_phong_vertex: string; + lights_phong_pars_fragment: string; + lights_phong_fragment: string; + color_pars_fragment: string; + color_fragment: string; + color_pars_vertex: string; + color_vertex: string; + skinning_pars_vertex: string; + skinbase_vertex: string; + skinning_vertex: string; + morphtarget_pars_vertex: string; + morphtarget_vertex: string; + default_vertex: string; + morphnormal_vertex: string; + skinnormal_vertex: string; + defaultnormal_vertex: string; + shadowmap_pars_fragment: string; + shadowmap_fragment: string; + shadowmap_pars_vertex: string; + shadowmap_vertex: string; + alphatest_fragment: string; + linear_to_gamma_fragment: string; + } + + export var ShaderChunk: ShaderChunk; + + export var UniformsUtils: { + merge(uniforms: Object[]): Uniforms; + merge(uniforms: Uniforms[]): Uniforms; + clone(uniforms_src: Uniforms): Uniforms; + }; + + export var UniformsLib: { + common: Uniforms; + bump: Uniforms; + normalmap: Uniforms; + fog: Uniforms; + lights: Uniforms; + particle: Uniforms; + shadowmap: Uniforms; + }; + + + export interface Shader { + uniforms: Uniforms; + vertexShader: string; + fragmentShader: string; + } + + export var ShaderLib: { + [name: string]: Shader; + basic: Shader; + lambert: Shader; + phong: Shader; + particle_basic: Shader; + depth: Shader; + dashed: Shader; + normal: Shader; + normalmap: Shader; + cube: Shader; + depthRGBA: Shader; + }; + + // Scenes ///////////////////////////////////////////////////////////////////// + + export interface IFog { + name:string; + color: Color; + clone():IFog; + } + + + /** + * This class contains the parameters that define linear fog, i.e., that grows linearly denser with the distance. + */ + export class Fog implements IFog { + constructor(hex: number, near?: number, far?: number); + + name:string; + + /** + * Fog color. + */ + color: Color; + + /** + * The minimum distance to start applying fog. Objects that are less than 'near' units from the active camera won't be affected by fog. + */ + near: number; + + /** + * The maximum distance at which fog stops being calculated and applied. Objects that are more than 'far' units away from the active camera won't be affected by fog. + * Default is 1000. + */ + far: number; + + clone(): Fog; + } + + /** + * This class contains the parameters that define linear fog, i.e., that grows exponentially denser with the distance. + */ + export class FogExp2 implements IFog { + constructor(hex: number, density?: number); + name: string; + color: Color; + + /** + * Defines how fast the fog will grow dense. + * Default is 0.00025. + */ + density: number; + + clone(): FogExp2; + } + + /** + * Scenes allow you to set up what and where is to be rendered by three.js. This is where you place objects, lights and cameras. + */ + export class Scene extends Object3D { + constructor(); + + /** + * A fog instance defining the type of fog that affects everything rendered in the scene. Default is null. + */ + fog: IFog; + + /** + * If not null, it will force everything in the scene to be rendered with that material. Default is null. + */ + overrideMaterial: Material; + + /** + * Default is false. + */ + matrixAutoUpdate: boolean; + + autoUpdate: boolean; + } + + // Textures ///////////////////////////////////////////////////////////////////// + export class CompressedTexture extends Texture { + constructor( + mipmaps: ImageData[], + width: number, + height: number, + format?: PixelFormat, + type?: TextureDataType, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + anisotropy?: number + ); + + clone(): CompressedTexture; + } + + export class DataTexture extends Texture { + constructor( + data: ImageData, + width: number, + height: number, + format: PixelFormat, + type: TextureDataType, + mapping: Mapping, + wrapS: Wrapping, + wrapT: Wrapping, + magFilter: TextureFilter, + minFilter: TextureFilter, + anisotropy?: number + ); + + clone(): DataTexture; + } + + export class Texture { + constructor( + image: HTMLImageElement, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + constructor( + image: HTMLCanvasElement, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + constructor( + image: HTMLImageElement, + mapping?: MappingConstructor, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + constructor( + image: HTMLCanvasElement, + mapping?: MappingConstructor, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + + image: Object; // HTMLImageElement or ImageData ; + mapping: Mapping; + wrapS: Wrapping; + wrapT: Wrapping; + magFilter: TextureFilter; + minFilter: TextureFilter; + format: PixelFormat; + type: TextureDataType; + anisotropy: number; + needsUpdate: boolean; + repeat: Vector2; + offset: Vector2; + name: string; + generateMipmaps: boolean; + flipY: boolean; + mipmaps: ImageData[]; + unpackAlignment: number; + premultiplyAlpha: boolean; + onUpdate: () => void; + id: number; + + clone(): Texture; + dispose(): void; + } + + // Extras ///////////////////////////////////////////////////////////////////// + + export interface TypefaceData { + familyName: string; + cssFontWeight: string; + cssFontStyle: string; + } + + export var FontUtils: { + + divisions: number; + style: string; + weight: string; + face: string; + faces: { [weight: string]: { [style: string]: Face; }; }; + size: number; + + drawText(text: string): { paths: Path[]; offset: number; }; + Triangulate: { + (contour: Vector2[], indices: boolean): Vector2[]; + area(contour: Vector2[]): number; + }; + extractGlyphPoints(c: string, face: Face, scale: number, offset: number, path: Path): { offset: number; path: Path; }; + generateShapes(text: string, parameters?: { size?: number; curveSegments?: number; font?: string; weight?: string; style?: string; }): Shape[]; + loadFace(data: TypefaceData): TypefaceData; + getFace(): Face; + }; + + export var GeometryUtils: { + merge(geometry1: Geometry, object2: Mesh, materialIndexOffset?: number): void; + merge(geometry1: Geometry, object2: Geometry, materialIndexOffset?: number): void; + randomPointInTriangle(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): Vector3; + randomPointInFace(face: Face, geometry: Geometry, useCachedAreas: boolean): Vector3; + randomPointsInGeometry(geometry: Geometry, points: number): Vector3; + triangleArea(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): number; + center(geometry: Geometry): Vector3; + triangulateQuads(geometry: Geometry): void; + }; + + export var ImageUtils: { + crossOrigin: string; + + generateDataTexture(width: number, height: number, color: Color): DataTexture; + parseDDS(buffer: ArrayBuffer, loadMipmaps: boolean): { mipmaps: { data: Uint8Array; width: number; height: number; }[]; width: number; height: number; format: number; mipmapCount: number; }; + loadCompressedTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; + loadTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; + getNormalMap(image: HTMLImageElement, depth?: number): HTMLCanvasElement; + loadCompressedTextureCube(array: string[], mapping?: Mapping, onLoad?: () => void, onError?: (message: string) => void): Texture; + loadTextureCube(array: string[], mapping?: Mapping, onLoad?: () => void , onError?: (message: string) => void ): Texture; + }; + + export var SceneUtils: { + createMultiMaterialObject(geometry: Geometry, materials: Material[]): Object3D; + attach(child: Object3D, scene: Scene, parent: Object3D): void; + detach(child: Object3D, parent: Object3D, scene: Scene): void; + }; + + // Extras / Animation ///////////////////////////////////////////////////////////////////// + + export interface KeyFrame { + pos: number[]; + rot: number[]; + scl: number[]; + time: number; + } + + export interface KeyFrames { + keys: KeyFrame[]; + parent: number; + } + + export interface AnimationData { + JIT: number; + fps: number; + hierarchy: KeyFrames[]; + length: number; + name: string; + } + + export class Animation { + constructor(root: Mesh, name: string); + + root: Mesh; + data: AnimationData; + hierarchy: Bone[]; + currentTime: number; + timeScale: number; + isPlaying: boolean; + isPaused: boolean; + loop: boolean; + interpolationType: AnimationInterpolation; + + play(loop?: boolean, startTimeMS?: number): void; + pause(): void; + stop(): void; + reset(): void; + update(deltaTimeMS: number): void; + interpolateCatmullRom(points: Vector3[], scale: number): Vector3[]; + interpolate(p0: number, p1: number, p2: number, p3: number, t: number, t2: number, t3: number): number; + getNextKeyWith(type: string, h: number, key: number): KeyFrame; // ???? + getPrevKeyWith(type: string, h: number, key: number): KeyFrame; + } + + export class AnimationInterpolation { } + + export var AnimationHandler: { + CATMULLROM: AnimationInterpolation; + CATMULLROM_FORWARD: AnimationInterpolation; + LINEAR: AnimationInterpolation; + removeFromUpdate(animation: Animation): void; + get(name: string): AnimationData; + update(deltaTimeMS: number): void; + parse(root: SkinnedMesh): Object3D[]; + add(data: AnimationData): void; + addToUpdate(animation: Animation): void; + }; + + export class AnimationMorphTarget { + constructor(root: Bone, data: any); + + root: Bone; + data: Object; + hierarchy: KeyFrames[]; + currentTime: number; + timeScale: number; + isPlaying: boolean; + isPaused: boolean; + loop: boolean; + influence: number; + + play(loop?: boolean, startTimeMS?: number): void; + pause(): void; + stop(): void; + update(deltaTimeMS: number): void; + } + + export class KeyFrameAnimation { + constructor(root: Mesh, data: any, JITCompile?: boolean); + + root: Mesh; + data: Object; + hierarchy: KeyFrames[]; + currentTime: number; + timeScale: number; + isPlaying: number; + isPaused: number; + loop: number; + JITCompile: boolean; + + play(loop?: number, startTimeMS?: number): void; + pause(): void; + stop(): void; + update(deltaTimeMS: number): void; + interpolateCatmullRom(points: Vector3[], scale: number): Vector3[]; + getNextKeyWith(type: string, h: number, key: number): KeyFrame; // ???? + getPrevKeyWith(type: string, h: number, key: number): KeyFrame; + } + + // Extras / Cameras ///////////////////////////////////////////////////////////////////// + + export class CombinedCamera extends Camera { + constructor(width: number, height: number, fov: number, near: number, far: number, orthoNear: number, orthoFar: number); + + fov: number; + right: number; + bottom: number; + cameraP: PerspectiveCamera; + top: number; + zoom: number; + far: number; + near: number; + inPerspectiveMode: boolean; + cameraO: OrthographicCamera; + inOrthographicMode: boolean; + left: number; + + toBottomView(): void; + setFov(fov: number): void; + toBackView(): void; + setZoom(zoom: number): void; + setLens(focalLength: number, frameHeight?: number): number; + toFrontView(): void; + toLeftView(): void; + updateProjectionMatrix(): void; + toTopView(): void; + toOrthographic(): void; + setSize(width: number, height: number): void; + toPerspective(): void; + toRightView(): void; + } + + export class CubeCamera extends Object3D { + constructor(near: number, far: number, cubeResolution: number); + + renderTarget: WebGLRenderTargetCube; + updateCubeMap(renderer: Renderer, scene: Scene): void; + } + + // Extras / Core ///////////////////////////////////////////////////////////////////// + + /** + * An extensible curve object which contains methods for interpolation + * class Curve<T extends Vector> + */ + export class Curve { + constructor(); + + needsUpdate: boolean; + + /** + * Returns a vector for point t of the curve where t is between 0 and 1 + * getPoint(t: number): T; + */ + getPoint(t: number): Vector; + + /** + * Returns a vector for point at relative position in curve according to arc length + * getPointAt(u: number): T; + */ + getPointAt(u: number): Vector; + + /** + * Get sequence of points using getPoint( t ) + * getPoints(divisions?: number): T[]; + */ + getPoints(divisions?: number): Vector[]; + + /** + * Get sequence of equi-spaced points using getPointAt( u ) + * getSpacedPoints(divisions?: number): T[]; + */ + getSpacedPoints(divisions?: number): Vector[]; + + /** + * Get total curve arc length + */ + getLength(): number; + + /** + * Get list of cumulative segment lengths + */ + getLengths(divisions?: number): number[]; + + /** + * Update the cumlative segment distance cache + */ + updateArcLengths(): void; + + /** + * Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance + */ + getUtoTmapping(u: number, distance: number): number; + + /** + * Returns a unit vector tangent at t. If the subclassed curve do not implement its tangent derivation, 2 points a small delta apart will be used to find its gradient which seems to give a reasonable approximation + * getTangent(t: number): T; + */ + getTangent(t: number): Vector; + + /** + * Returns tangent at equidistance point u on the curve + * getTangentAt(u: number): T; + */ + getTangentAt(u: number): Vector; + + static Utils: { + tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; + tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; + tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; + interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; + }; + + static create(constructorFunc: Function, getPointFunc: Function): Function; + } + + export interface BoundingBox { + minX: number; + minY: number; + maxX: number; + maxY: number; + centroid: Vector; + } + + export class CurvePath extends Curve { + constructor(); + + curves: Curve[]; + bends: Path[]; + autoClose: boolean; + + getWrapPoints(oldPts: Vector2[], path: Path): Vector2[]; + createPointsGeometry(divisions: number): Geometry; + addWrapPath(bendpath: Path): void; + createGeometry(points: Vector2[]): Geometry; + add(curve: Curve): void; + getTransformedSpacedPoints(segments: number, bends?: Path[]): Vector2[]; + createSpacedPointsGeometry(divisions: number): Geometry; + closePath(): void; + getBoundingBox(): BoundingBox; + getCurveLengths(): number; + getTransformedPoints(segments: number, bends?: Path): Vector2[]; + checkConnection(): boolean; + } + + export class Gyroscope extends Object3D { + constructor(); + + scaleWorld: Vector3; + translationWorld: Vector3; + rotationWorld: Quaternion; + translationObject: Vector3; + scaleObject: Vector3; + rotationObject: Quaternion; + + updateMatrixWorld(force?: boolean): void; + } + + export enum PathActions { + MOVE_TO, + LINE_TO, + QUADRATIC_CURVE_TO, // Bezier quadratic curve + BEZIER_CURVE_TO, // Bezier cubic curve + CSPLINE_THRU, // Catmull-rom spline + ARC, // Circle + ELLIPSE, + } + + /** + * a 2d path representation, comprising of points, lines, and cubes, similar to the html5 2d canvas api. It extends CurvePath. + */ + export class Path extends CurvePath { + constructor(points?: Vector2); + + actions: PathActions[]; + + fromPoints(vectors: Vector2[]): void; + moveTo(x: number, y: number): void; + lineTo(x: number, y: number): void; + quadraticCurveTo(aCPx: number, aCPy: number, aX: number, aY: number): void; + bezierCurveTo(aCP1x: number, aCP1y: number, aCP2x: number, aCP2y: number, aX: number, aY: number): void; + splineThru(pts: Vector2[]): void; + arc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + absarc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + toShapes(): Shape[]; + } + + /** + * Defines a 2d shape plane using paths. + */ + export class Shape implements Path { + constructor(points?: Vector2[]); + + holes: Path[]; + + makeGeometry(options?: any): ShapeGeometry; + extractAllPoints(divisions: number): { + shape: Vector2[]; + holes: Vector2[][]; + }; + extrude(options?: any): ExtrudeGeometry; + extractPoints(divisions: number): Vector2[]; + extractAllSpacedPoints(divisions: Vector2): { + shape: Vector2[]; + holes: Vector2[][]; + }; + getPointsHoles(divisions: number): Vector2[][]; + getSpacedPointsHoles(divisions: number): Vector2[][]; + + getCurveLengths(): number; + // trick for TypeScript 0.9.5 compile passed + // from Path + actions: PathActions[]; + fromPoints(vectors: Vector2[]): void; + moveTo(x: number, y: number): void; + lineTo(x: number, y: number): void; + quadraticCurveTo(aCPx: number, aCPy: number, aX: number, aY: number): void; + bezierCurveTo(aCP1x: number, aCP1y: number, aCP2x: number, aCP2y: number, aX: number, aY: number): void; + splineThru(pts: Vector2[]): void; + arc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + absarc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + toShapes(): Shape[]; + // from CurvePath + curves: Curve[]; + bends: Path[]; + autoClose: boolean; + add(curve: Curve): void; + checkConnection(): boolean; + closePath(): void; + getBoundingBox(): BoundingBox; + createPointsGeometry(divisions: number): Geometry; + createSpacedPointsGeometry(divisions: number): Geometry; + createGeometry(points: Vector2[]): Geometry; + addWrapPath(bendpath: Path): void; + getTransformedPoints(segments: number, bends?: Path): Vector2[]; + getTransformedSpacedPoints(segments: number, bends?: Path[]): Vector2[]; + getWrapPoints(oldPts: Vector2[], path: Path): Vector2[]; + getPoint(t: number): Vector; + getPointAt(u: number): Vector; + getPoints(divisions?: number): Vector[]; + getSpacedPoints(divisions?: number): Vector[]; + getLength(): number; + getLengths(divisions?: number): number[]; + needsUpdate: boolean; + updateArcLengths(): void; + getUtoTmapping(u: number, distance: number): number; + getNormalVector(t: number): Vector; + getTangent(t: number): Vector; + getTangentAt(u: number): Vector; + } + + + + // Extras / Geomerties ///////////////////////////////////////////////////////////////////// + + export class CircleGeometry extends Geometry { + constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); + } + + export class ConvexGeometry extends Geometry { + constructor(vertices: Vector3[]); + } + + /** + * CubeGeometry is the quadrilateral primitive geometry class. It is typically used for creating a cube or irregular quadrilateral of the dimensions provided within the (optional) 'width', 'height', & 'depth' constructor arguments. + */ + export class BoxGeometry extends Geometry { + /** + * @param width — Width of the sides on the X axis. + * @param height — Height of the sides on the Y axis. + * @param depth — Depth of the sides on the Z axis. + * @param widthSegments — Number of segmented faces along the width of the sides. + * @param heightSegments — Number of segmented faces along the height of the sides. + * @param depthSegments — Number of segmented faces along the depth of the sides. + */ + constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number); + } + + export class CubeGeometry extends BoxGeometry { + } + + export class CylinderGeometry extends Geometry { + /** + * @param radiusTop — Radius of the cylinder at the top. + * @param radiusBottom — Radius of the cylinder at the bottom. + * @param height — Height of the cylinder. + * @param radiusSegments — Number of segmented faces around the circumference of the cylinder. + * @param heightSegments — Number of rows of faces along the height of the cylinder. + * @param openEnded - A Boolean indicating whether or not to cap the ends of the cylinder. + */ + constructor(radiusTop?: number, radiusBottom?: number, height?: number, radiusSegments?: number, heightSegments?: number, openEnded?: boolean); + } + + export class ExtrudeGeometry extends Geometry { + constructor(shape?: Shape, options?: any); + constructor(shapes?: Shape[], options?: any); + + addShapeList(shapes: Shape[], options?: any): void; + addShape(shape: Shape, options?: any): void; + } + + export class IcosahedronGeometry extends PolyhedronGeometry { + constructor(radius: number, detail: number); + } + + export class LatheGeometry extends Geometry { + constructor(points: Vector3[], steps?: number, angle?: number); + } + + export class OctahedronGeometry extends PolyhedronGeometry { + constructor(radius: number, detail: number); + } + + export class ParametricGeometry extends Geometry { + constructor(func: (u: number, v: number) => Vector3, slices: number, stacks: number, useTris?: boolean); + } + + export class PlaneGeometry extends Geometry { + constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); + } + + export class PolyhedronGeometry extends Geometry { + constructor(vertices: Vector3[], faces: Face[], radius?: number, detail?: number); + } + + export class RingGeometry extends Geometry { + constructor(innerRadius?: number, outerRadius?: number, thetaSegments?: number, phiSegments?: number, thetaStart?: number, thetaLength?: number); + } + export class ShapeGeometry extends Geometry { + constructor(shape: Shape, options?: any); + constructor(shapes: Shape[], options?: any); + + shapebb: BoundingBox; + addShapeList(shapes: Shape[], options: any): ShapeGeometry; + addShape(shape: Shape, options?: any): void; + } + + /** + * A class for generating sphere geometries + */ + export class SphereGeometry extends Geometry { + /** + * The geometry is created by sweeping and calculating vertexes around the Y axis (horizontal sweep) and the Z axis (vertical sweep). Thus, incomplete spheres (akin to 'sphere slices') can be created through the use of different values of phiStart, phiLength, thetaStart and thetaLength, in order to define the points in which we start (or end) calculating those vertices. + * + * @param radius — sphere radius. Default is 50. + * @param segmentsWidth — number of horizontal segments. Minimum value is 3, and the default is 8. + * @param segmentsHeight — number of vertical segments. Minimum value is 2, and the default is 6. + * @param phiStart — specify horizontal starting angle. Default is 0. + * @param phiLength — specify horizontal sweep angle size. Default is Math.PI * 2. + * @param thetaStart — specify vertical starting angle. Default is 0. + * @param thetaLength — specify vertical sweep angle size. Default is Math.PI. + */ + constructor(radius: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number); + } + + export class TetrahedronGeometry extends PolyhedronGeometry { + constructor(radius?: number, detail?: number); + } + + export interface TextGeometryParameters { + size?: number; // size of the text + height?: number; // thickness to extrude text + curveSegments?: number; // number of points on the curves + font?: string; // font name + weight?: string; // font weight (normal, bold) + style?: string; // font style (normal, italics) + bevelEnabled?: boolean; // turn on bevel + bevelThickness?: number; // how deep into text bevel goes + bevelSize?: number; // how far from text outline is bevel + } + + export class TextGeometry extends ExtrudeGeometry { + constructor(text: string, TextGeometryParameters?: TextGeometryParameters); + } + + export class TorusGeometry extends Geometry { + constructor(radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, arc?: number); + } + + export class TorusKnotGeometry extends Geometry { + constructor(radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, p?: number, q?: number, heightScale?: number); + } + + export class TubeGeometry extends Geometry { + constructor(path: Path, segments?: number, radius?: number, radiusSegments?: number, closed?: boolean); + + path: Path; + segments: number; + radius: number; + radiusSegments: number; + closed: boolean; + tangents: Vector3[]; + normals: Vector3[]; + binormals: Vector3[]; + + FrenetFrames(path: Path, segments: number, closed: boolean): void; + } + + // Extras / Helpers ///////////////////////////////////////////////////////////////////// + + export class ArrowHelper extends Object3D { + constructor(dir: Vector3, origin?: Vector3, length?: number, hex?: number, headLength?: number, headWidth?: number); + + line: Line; + cone: Mesh; + + setColor(hex: number): void; + setLength(length: number): void; + setDirection(dir: Vector3): void; + } + + export class AxisHelper extends Line { + constructor(size: number); + } + + export class BoundingBoxHelper extends Mesh { + constructor(object: Object3D, hex: number); + + object: Object3D; + box: Box3; + + update(): void; + } + export class CameraHelper extends Line { + constructor(camera: Camera); + + pointMap: { [id: string]: number[]; }; + camera: Camera; + + update(): void; + } + + export class DirectionalLightHelper extends Object3D { + constructor(light: Light, sphereSize: number, arrowLength: number); + + lightSphere: Mesh; + light: Light; + targetLine: Line; + + update(): void; + } + + export class GridHelper extends Line { + constructor(size: number, step: number); + + setColors(colorCenterLine: number, colorGrid: number): void; + } + export class HemisphereLightHelper extends Object3D { + constructor(light: Light, sphereSize: number, arrowLength: number, domeSize: number); + + lightSphere: Mesh; + light: Light; + + update(): void; + } + + export class PointLightHelper extends Object3D { + constructor(light: Light, sphereSize: number); + + lightSphere: Mesh; + light: Light; + + update(): void; + } + + export class SpotLightHelper extends Object3D { + constructor(light: Light, sphereSize: number, arrowLength: number); + + lightSphere: Mesh; + light: Light; + lightCone: Mesh; + + update(): void; + } + + // Extras / Objects ///////////////////////////////////////////////////////////////////// + + export class ImmediateRenderObject extends Object3D { + constructor(); + + render(renderCallback:Function): void; + } + + export interface LensFlareProperty { + texture: Texture; // Texture + size: number; // size in pixels (-1 = use texture.width) + distance: number; // distance (0-1) from light source (0=at light source) + x: number; + y: number; + z: number; // screen position (-1 => 1) z = 0 is ontop z = 1 is back + scale: number; // scale + rotation: number; // rotation + opacity: number; // opacity + color: Color; // color + blending: Blending; + } + + export class LensFlare extends Object3D { + constructor(texture?: Texture, size?: number, distance?: number, blending?: Blending, color?: Color); + + lensFlares: LensFlareProperty[]; + positionScreen: Vector3; + customUpdateCallback: (object: LensFlare) => void; + + add(obj: Object3D): void; + add(texture: Texture, size?: number, distance?: number, blending?: Blending, color?: Color): void; + + updateLensFlares(): void; + } + + export interface MorphBlendMeshAnimation { + startFrame: number; + endFrame: number; + length: number; + fps: number; + duration: number; + lastFrame: number; + currentFrame: number; + active: boolean; + time: number; + direction: number; + weight: number; + directionBackwards: boolean; + mirroredLoop: boolean; + } + + export class MorphBlendMesh extends Mesh { + constructor(geometry: Geometry, material: Material); + + animationsMap: { [name: string]: MorphBlendMeshAnimation; }; + animationsList: MorphBlendMeshAnimation[]; + + setAnimationWeight(name: string, weight: number): void; + setAnimationFPS(name: string, fps: number): void; + createAnimation(name: string, start: number, end: number, fps: number): void; + playAnimation(name: string): void; + update(delta: number): void; + autoCreateAnimations(fps: number): void; + setAnimationDuration(name: string, duration: number): void; + setAnimationDirectionForward(name: string): void; + getAnimationDuration(name: string): number; + getAnimationTime(name: string): number; + setAnimationDirectionBackward(name: string): void; + setAnimationTime(name: string, time: number): void; + stopAnimation(name: string): void; + } + + // Extras / Renderers / Plugins ///////////////////////////////////////////////////////////////////// + + export class DepthPassPlugin implements RendererPlugin { + constructor(); + + enabled: boolean; + renderTarget: RenderTarget; + + init(renderer: Renderer): void; + update(scene: Scene, camera: Camera): void; + render(scene: Scene, camera: Camera): void; + } + + export class LensFlarePlugin implements RendererPlugin { + constructor(); + + init(renderer: Renderer): void; + render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; + } + + export class ShadowMapPlugin implements RendererPlugin { + constructor(); + + init(renderer: Renderer): void; + + update(scene: Scene, camera: Camera): void; + render(scene: Scene, camera: Camera): void; + } + + export class SpritePlugin implements RendererPlugin { + constructor(); + + init(renderer: Renderer): void; + render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; + } + + // Extras / Shaders ///////////////////////////////////////////////////////////////////// + + export var ShaderFlares: { + 'lensFlareVertexTexture': { + vertexShader: string; + fragmentShader: string; + }; + 'lensFlare': { + vertexShader: string; + fragmentShader: string; + }; + }; +} diff --git a/threejs/three.d.ts.tscparams b/threejs/three.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/threejs/three.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/through/through.d.ts b/through/through.d.ts index 7d2adce5ee..8a617c4241 100644 --- a/through/through.d.ts +++ b/through/through.d.ts @@ -15,7 +15,7 @@ declare module "through" { }): through.ThroughStream; module through { - export interface ThroughStream extends Stream.ReadWriteStream { + export interface ThroughStream extends ReadWriteStream { autoDestroy: boolean; } } diff --git a/tsd.json b/tsd.json new file mode 100644 index 0000000000..60f508161b --- /dev/null +++ b/tsd.json @@ -0,0 +1,15 @@ +{ + "version": "v4", + "repo": "borisyankov/DefinitelyTyped", + "ref": "master", + "path": "_infrastructure/tests/typings", + "bundle": "_infrastructure/tests/typings/tsd.d.ts", + "installed": { + "bluebird/bluebird.d.ts": { + "commit": "bac5b4311465c7052467ec315d0cbb1c640a69d6" + }, + "node/node.d.ts": { + "commit": "bac5b4311465c7052467ec315d0cbb1c640a69d6" + } + } +} diff --git a/tv4/tv4-tests.ts b/tv4/tv4-tests.ts new file mode 100644 index 0000000000..2768d9f5fe --- /dev/null +++ b/tv4/tv4-tests.ts @@ -0,0 +1,43 @@ +/// + +var str:string; +var strArr:string[]; +var bool:boolean; +var num:number; +var obj:any; +var tv4:TV4; +var err:TV4Error; +var errs:TV4Error[]; +var single:TV4SingleResult; +var multi:TV4MultiResult; + +single = tv4.validateResult(obj, obj); +bool = single.valid; +strArr = single.missing; +err = single.error; + +num = err.code; +str = err.message; +str = err.dataPath; +str = err.schemaPath; + +multi = tv4.validateMultiple(obj, obj); +bool = multi.valid; +strArr = multi.missing; +errs = multi.errors; + +bool = tv4.addSchema(str, obj); +obj = tv4.getSchema(str); +obj = tv4.normSchema(str, str); +str = tv4.resolveUrl(str, str); + +tv4 = tv4.freshApi(); +tv4.dropSchemas(); +tv4.reset(); + +strArr = tv4.getMissingUris(/abc/); +strArr = tv4.getSchemaUris(/abc/); +obj = tv4.getSchemaMap()[str]; +num = tv4.errorCodes['bla']; + +num = tv4.errorCodes['MY_NAME']; diff --git a/tv4/tv4.d.ts b/tv4/tv4.d.ts new file mode 100644 index 0000000000..702d3c3bc6 --- /dev/null +++ b/tv4/tv4.d.ts @@ -0,0 +1,47 @@ +// Type definitions for Tiny Validator tv4 1.0.6 +// Project: https://github.com/geraintluff/tv4 +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface TV4ErrorCodes { + [key:string]:number; +} +interface TV4Error { + code:number; + message:string; + dataPath:string; + schemaPath:string; +} +interface TV4SchemaMap { + [uri:string]:any; +} +interface TV4BaseResult { + missing:string[]; + valid:boolean; +} +interface TV4SingleResult extends TV4BaseResult { + error:TV4Error; +} +interface TV4MultiResult extends TV4BaseResult { + errors:TV4Error[]; +} +interface TV4 { + validateResult(data:any, schema:any):TV4SingleResult; + validateMultiple(data:any, schema:any):TV4MultiResult; + + addSchema(uri:string, schema:any):boolean; + getSchema(uri:string):any; + normSchema(schema:any, baseUri:string):any; + resolveUrl(base:string, href:string):string; + freshApi():TV4; + dropSchemas():void; + reset():void; + + getMissingUris(exp?:RegExp):string[]; + getSchemaUris(exp?:RegExp):string[]; + getSchemaMap():TV4SchemaMap; + errorCodes:TV4ErrorCodes; +} +declare module "tv4" { +export = TV4; +} diff --git a/tween.js/tween.js.d.ts b/tween.js/tween.js.d.ts index df5826bd21..0caaed1477 100644 --- a/tween.js/tween.js.d.ts +++ b/tween.js/tween.js.d.ts @@ -1,6 +1,6 @@ // Type definitions for tween.js r12 // Project: https://github.com/sole/tween.js/ -// Definitions by: https://github.com/sunetos and https://github.com/jzarnikov +// Definitions by: sunetos , jzarnikov // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module TWEEN { diff --git a/tweenjs/tweenjs.d.ts b/tweenjs/tweenjs.d.ts index d7896d3491..a53dd8e209 100644 --- a/tweenjs/tweenjs.d.ts +++ b/tweenjs/tweenjs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for TweenJS 0.5.0 +// Type definitions for TweenJS 0.5.1 // Project: http://www.createjs.com/#!/TweenJS // Definitions by: Pedro Ferreira , Chris Smith // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -82,7 +82,7 @@ declare module createjs { static priority: any; //methods - static init(tween: Tween, prop: string, value: any): any; + static init(tween: Tween, prop: string, value: any): any; static step(tween: Tween, prop: string, startValue: any, injectProps: Object, endValue: any): void; static install(): void; static tween(tween: Tween, prop: string, value: any, startValues: Object, endValues: Object, ratio: number, wait: boolean, end: boolean): any; @@ -100,8 +100,8 @@ declare module createjs { // methods addLabel(label: string, position: number): void; addTween(...tween: Tween[]): void; - getCurrentLabel(): string; - getLabels(): Object[]; + getCurrentLabel(): string; + getLabels(): Object[]; gotoAndPlay(positionOrLabel: string): void; gotoAndPlay(positionOrLabel: number): void; gotoAndStop(positionOrLabel: string): void; @@ -148,6 +148,7 @@ declare module createjs { setPaused(value: boolean): Tween; setPosition(value: number, actionsMode: number): boolean; static tick(delta: number, paused: boolean): void; + tick(delta: number, paused: boolean): void; tick(delta: number): void; to(props: Object, duration?: number, ease?: (t: number) => number): Tween; wait(duration: number, passive?: boolean): Tween; diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index 8d4050c943..9ee948392c 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Twitter's typeahead.js 0.9.3 +// Type definitions for typeahead.js 0.9.3 // Project: http://twitter.github.io/typeahead.js/ // Definitions by: Ivaylo Gochkov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/underscore.string/underscore.string.d.ts b/underscore.string/underscore.string.d.ts index d016dc908d..db9ec042d4 100644 --- a/underscore.string/underscore.string.d.ts +++ b/underscore.string/underscore.string.d.ts @@ -562,5 +562,7 @@ interface UnderscoreStringStaticExports { toBoolean(str: string, trueValues?: any[], falseValues?: any[]): boolean; } - +declare module "underscore.string" { +export = UnderscoreStringStatic; +} // TODO interface UnderscoreString extends Underscore diff --git a/underscore/underscore-tests.ts b/underscore/underscore-tests.ts index ae5ab6f7ee..d3eb87f6aa 100644 --- a/underscore/underscore-tests.ts +++ b/underscore/underscore-tests.ts @@ -16,14 +16,14 @@ var list = [[0, 1], [2, 3], [4, 5]]; //var flat = _.reduceRight(list, (a, b) => a.concat(b), []); // https://typescript.codeplex.com/workitem/1960 var flat = _.reduceRight(list, (a, b) => a.concat(b), []); -var even = _.find([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); +var even = _.find([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); -var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); +var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); var listOfPlays = [{ title: "Cymbeline", author: "Shakespeare", year: 1611 }, { title: "The Tempest", author: "Shakespeare", year: 1611 }, { title: "Other", author: "Not Shakespeare", year: 2012 }]; _.where(listOfPlays, { author: "Shakespeare", year: 1611 }); -var odds = _.reject([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); +var odds = _.reject([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); //_.every([true, 1, null, 'yes'], _.identity); // https://typescript.codeplex.com/workitem/1960 _.every([true, 1, null, 'yes'], _.identity); @@ -38,7 +38,7 @@ _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }]; _.pluck(stooges, 'name'); -_.max(stooges, (stooge) => stooge.age); +_.max<{ name: string; age: number }>(stooges, (stooge) => stooge.age); _.max([1, 2, 3, 4, 5]); @@ -283,24 +283,30 @@ _(['test', 'test']).pick(['test2', 'test2']); //////////////// Chain Tests function chain_tests() { // https://typescript.codeplex.com/workitem/1960 - var list:number[] = _.chain([1, 2, 3, 4, 5, 6, 7, 8]) - .filter(n => n % 2 == 0) - .map(n => n * n) - .value(); + var numArray: number[] = _.chain([1, 2, 3, 4, 5, 6, 7, 8]) + .filter(num => num % 2 == 0) + .map(num => num * num) + .value(); - _([1, 2, 3, 4]) - .chain() - .filter((num: number) => { - return num % 2 == 0; - }).tap(alert) - .map((num: number) => { - return num * num; - }) - .value(); + var strArray: string[] = _([1, 2, 3, 4]) + .chain() + .filter(num => num % 2 == 0) + .tap(alert) + .map(num => "string" + num) + .value(); - _.chain([1, 2, 3, 200]) - .filter(function (num: number) { return num % 2 == 0; }) - .tap(alert) - .map(function (num: number) { return num * num }) - .value(); + var n : number = _.chain([1, 2, 3, 200]) + .filter(num => num % 2 == 0) + .tap(alert) + .map(num => num * num) + .max() + .value(); + + //If using alternate definition of map (~ line 2200), .value returns any + // because.map matches _Chain as opposed to _ChainOfArrays , which breaks typing on flatten + var hoverOverValueShouldBeNumberNotAny : number = _([1, 2, 3]).chain() + .map(num=> [num, num + 1]) + .flatten() + .find(num => num % 2 == 0) + .value(); } diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 4382f7bea7..10e4ccb23a 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -1,71 +1,70 @@ // Type definitions for Underscore 1.5.2 // Project: http://underscorejs.org/ -// Definitions by: -// Boris Yankov -// Josh Baldwin +// Definitions by: Boris Yankov +// Definitions by: Josh Baldwin // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module _ { - /** - * underscore.js _.throttle options. - **/ - interface ThrottleSettings { + /** + * underscore.js _.throttle options. + **/ + interface ThrottleSettings { - /** - * If you'd like to disable the leading-edge call, pass this as false. - **/ - leading?: boolean; + /** + * If you'd like to disable the leading-edge call, pass this as false. + **/ + leading?: boolean; - /** - * If you'd like to disable the execution on the trailing-edge, pass false. - **/ - trailing?: boolean; - } + /** + * If you'd like to disable the execution on the trailing-edge, pass false. + **/ + trailing?: boolean; + } - /** - * underscore.js template settings, set templateSettings or pass as an argument - * to 'template()' to overide defaults. - **/ - interface TemplateSettings { - /** - * Default value is '/<%([\s\S]+?)%>/g'. - **/ - evaluate?: RegExp; + /** + * underscore.js template settings, set templateSettings or pass as an argument + * to 'template()' to overide defaults. + **/ + interface TemplateSettings { + /** + * Default value is '/<%([\s\S]+?)%>/g'. + **/ + evaluate?: RegExp; - /** - * Default value is '/<%=([\s\S]+?)%>/g'. - **/ - interpolate?: RegExp; + /** + * Default value is '/<%=([\s\S]+?)%>/g'. + **/ + interpolate?: RegExp; - /** - * Default value is '/<%-([\s\S]+?)%>/g'. - **/ - escape?: RegExp; - } + /** + * Default value is '/<%-([\s\S]+?)%>/g'. + **/ + escape?: RegExp; + } - interface ListIterator { - (value: T, index: number, list: T[]): TResult; - } + interface ListIterator { + (value: T, index: number, list: T[]): TResult; + } - interface ObjectIterator { - (element: T, key: string, list: any): TResult; - } + interface ObjectIterator { + (element: T, key: string, list: any): TResult; + } - interface MemoIterator { - (prev: TResult, curr: T, index: number, list: T[]): TResult; - } + interface MemoIterator { + (prev: TResult, curr: T, index: number, list: T[]): TResult; + } - interface Collection { } + interface Collection { } - // Common interface between Arrays and jQuery objects - interface List extends Collection { - [index: number]: T; - length: number; - } + // Common interface between Arrays and jQuery objects + interface List extends Collection { + [index: number]: T; + length: number; + } - interface Dictionary extends Collection { - [index: string]: T; - } + interface Dictionary extends Collection { + [index: string]: T; + } } interface UnderscoreStatic { @@ -74,10 +73,10 @@ interface UnderscoreStatic { * as the first parameter can be invoked through this function. * @param key First argument to Underscore object functions. **/ - (value: Array): Underscore; - (value: T): Underscore; + (value: Array): Underscore; + (value: T): Underscore; - /* ************* + /* ************* * Collections * ************* */ @@ -101,7 +100,7 @@ interface UnderscoreStatic { * @param iterator Iterator function for each property on `obj`. * @param context 'this' object in `iterator`, optional. **/ - each( + each( object: _.Dictionary, iterator: _.ObjectIterator, context?: any): void; @@ -117,7 +116,7 @@ interface UnderscoreStatic { /** * @see _.each **/ - forEach( + forEach( object: _.Dictionary, iterator: _.ObjectIterator, context?: any): void; @@ -143,7 +142,7 @@ interface UnderscoreStatic { * @param context `this` object in `iterator`, optional. * @return The mapped object result. **/ - map( + map( object: _.Dictionary, iterator: _.ObjectIterator, context?: any): TResult[]; @@ -159,7 +158,7 @@ interface UnderscoreStatic { /** * @see _.map **/ - collect( + collect( object: _.Dictionary, iterator: _.ObjectIterator, context?: any): TResult[]; @@ -285,7 +284,7 @@ interface UnderscoreStatic { * @return The first element in `list` that has all `properties`. **/ findWhere( - list: _.List, + list: _.List, properties: U): T; /** @@ -299,7 +298,7 @@ interface UnderscoreStatic { **/ reject( list: _.Collection, - iterator: _.ListIterator, + iterator: _.ListIterator, context?: any): T[]; /** @@ -312,7 +311,7 @@ interface UnderscoreStatic { **/ every( list: _.Collection, - iterator?: _.ListIterator, + iterator?: _.ListIterator, context?: any): boolean; /** @@ -320,7 +319,7 @@ interface UnderscoreStatic { **/ all( list: _.Collection, - iterator?: _.ListIterator, + iterator?: _.ListIterator, context?: any): boolean; /** @@ -333,7 +332,7 @@ interface UnderscoreStatic { **/ any( list: _.Collection, - iterator?: _.ListIterator, + iterator?: _.ListIterator, context?: any): boolean; /** @@ -341,7 +340,7 @@ interface UnderscoreStatic { **/ some( list: _.Collection, - iterator?: _.ListIterator, + iterator?: _.ListIterator, context?: any): boolean; /** @@ -390,7 +389,7 @@ interface UnderscoreStatic { * @param list Finds the maximum value in this list. * @return Maximum value in `list`. **/ - max(list: _.List): number; + max(list: _.List): number; /** * Returns the maximum value in list. If iterator is passed, it will be used on each value to generate @@ -402,7 +401,7 @@ interface UnderscoreStatic { **/ max( list: _.Collection, - iterator?: _.ListIterator, + iterator?: _.ListIterator, context?: any): T; /** @@ -410,7 +409,7 @@ interface UnderscoreStatic { * @param list Finds the minimum value in this list. * @return Minimum value in `list`. **/ - min(list: _.List): number; + min(list: _.List): number; /** * Returns the minimum value in list. If iterator is passed, it will be used on each value to generate @@ -422,7 +421,7 @@ interface UnderscoreStatic { **/ min( list: _.Collection, - iterator?: _.ListIterator, + iterator?: _.ListIterator, context?: any): T; /** @@ -434,8 +433,8 @@ interface UnderscoreStatic { * @return A sorted copy of `list`. **/ sortBy( - list: _.List, - iterator?: _.ListIterator, + list: _.List, + iterator?: _.ListIterator, context?: any): T[]; /** @@ -443,7 +442,7 @@ interface UnderscoreStatic { * @param iterator Sort iterator for each element within `list`. **/ sortBy( - list: _.List, + list: _.List, iterator: string, context?: any): T[]; @@ -457,36 +456,36 @@ interface UnderscoreStatic { * @return An object with the group names as properties where each property contains the grouped elements from `list`. **/ groupBy( - list: _.List, - iterator?: _.ListIterator, - context?: any): _.Dictionary; + list: _.List, + iterator?: _.ListIterator, + context?: any): _.Dictionary; /** * @see _.groupBy * @param iterator Property on each object to group them by. **/ groupBy( - list: _.List, + list: _.List, iterator: string, - context?: any): _.Dictionary; + context?: any): _.Dictionary; /** * Given a `list`, and an `iterator` function that returns a key for each element in the list (or a property name), * returns an object with an index of each item. Just like _.groupBy, but for when you know your keys are unique. **/ indexBy( - list: _.List, - iterator: _.ListIterator, - context?: any): _.Dictionary; + list: _.List, + iterator: _.ListIterator, + context?: any): _.Dictionary; /** * @see _.indexBy * @param iterator Property on each object to index them by. **/ indexBy( - list: _.List, + list: _.List, iterator: string, - context?: any): _.Dictionary; + context?: any): _.Dictionary; /** * Sorts a list into groups and returns a count for the number of objects in each group. Similar @@ -499,8 +498,8 @@ interface UnderscoreStatic { **/ countBy( list: _.Collection, - iterator?: _.ListIterator, - context?: any): _.Dictionary; + iterator?: _.ListIterator, + context?: any): _.Dictionary; /** * @see _.countBy @@ -509,7 +508,7 @@ interface UnderscoreStatic { countBy( list: _.Collection, iterator: string, - context?: any): _.Dictionary; + context?: any): _.Dictionary; /** * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. @@ -554,38 +553,38 @@ interface UnderscoreStatic { * @param array Retrieves the first element of this array. * @return Returns the first element of `array`. **/ - first(array: _.List): T; + first(array: _.List): T; /** * @see _.first * @param n Return more than one element from `array`. **/ first( - array: _.List, + array: _.List, n: number): T[]; /** * @see _.first **/ - head(array: _.List): T; + head(array: _.List): T; /** * @see _.first **/ head( - array: _.List, + array: _.List, n: number): T[]; /** * @see _.first **/ - take(array: _.List): T; + take(array: _.List): T; /** * @see _.first **/ take( - array: _.List, + array: _.List, n: number): T[]; /** @@ -596,7 +595,7 @@ interface UnderscoreStatic { * @return Returns everything but the last `n` elements of `array`. **/ initial( - array: _.List, + array: _.List, n?: number): T[]; /** @@ -604,14 +603,14 @@ interface UnderscoreStatic { * @param array Retrieves the last element of this array. * @return Returns the last element of `array`. **/ - last(array: _.List): T; + last(array: _.List): T; /** * @see _.last * @param n Return more than one element from `array`. **/ last( - array: _.List, + array: _.List, n: number): T[]; /** @@ -622,21 +621,21 @@ interface UnderscoreStatic { * @return Returns the elements of `array` from `index` to the end of `array`. **/ rest( - array: _.List, + array: _.List, n?: number): T[]; /** * @see _.rest **/ tail( - array: _.List, + array: _.List, n?: number): T[]; /** * @see _.rest **/ drop( - array: _.List, + array: _.List, n?: number): T[]; /** @@ -645,7 +644,7 @@ interface UnderscoreStatic { * @param array Array to compact. * @return Copy of `array` without false values. **/ - compact(array: _.List): T[]; + compact(array: _.List): T[]; /** * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will @@ -655,7 +654,7 @@ interface UnderscoreStatic { * @return `array` flattened. **/ flatten( - array: _.List, + array: _.List, shallow?: boolean): any[]; /** @@ -665,7 +664,7 @@ interface UnderscoreStatic { * @return Copy of `array` without `values`. **/ without( - array: _.List, + array: _.List, ...values: T[]): T[]; /** @@ -674,7 +673,7 @@ interface UnderscoreStatic { * @param arrays Array of arrays to compute the union of. * @return The union of elements within `arrays`. **/ - union(...arrays: _.List[]): T[]; + union(...arrays: _.List[]): T[]; /** * Computes the list of values that are the intersection of all the arrays. Each value in the result @@ -682,7 +681,7 @@ interface UnderscoreStatic { * @param arrays Array of arrays to compute the intersection of. * @return The intersection of elements within `arrays`. **/ - intersection(...arrays: _.List[]): T[]; + intersection(...arrays: _.List[]): T[]; /** * Similar to without, but returns the values from array that are not present in the other arrays. @@ -691,8 +690,8 @@ interface UnderscoreStatic { * @return Copy of `array` with only `others` values. **/ difference( - array: _.List, - ...others: _.List[]): T[]; + array: _.List, + ...others: _.List[]): T[]; /** * Produces a duplicate-free version of the array, using === to test object equality. If you know in @@ -705,34 +704,34 @@ interface UnderscoreStatic { * @return Copy of `array` where all elements are unique. **/ uniq( - array: _.List, + array: _.List, isSorted?: boolean, - iterator?: _.ListIterator, + iterator?: _.ListIterator, context?: any): T[]; /** * @see _.uniq **/ uniq( - array: _.List, - iterator?: _.ListIterator, + array: _.List, + iterator?: _.ListIterator, context?: any): T[]; /** * @see _.uniq **/ unique( - array: _.List, - iterator?: _.ListIterator, + array: _.List, + iterator?: _.ListIterator, context?: any): T[]; /** * @see _.uniq **/ unique( - array: _.List, + array: _.List, isSorted?: boolean, - iterator?: _.ListIterator, + iterator?: _.ListIterator, context?: any): T[]; @@ -758,8 +757,8 @@ interface UnderscoreStatic { * @return An object containing the `keys` as properties and `values` as the property values. **/ object( - keys: _.List, - values: _.List): TResult; + keys: _.List, + values: _.List): TResult; /** * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a @@ -773,7 +772,7 @@ interface UnderscoreStatic { * @see _.object **/ object( - list: _.List, + list: _.List, values?: any): TResult; /** @@ -787,7 +786,7 @@ interface UnderscoreStatic { * @return The index of `value` within `array`. **/ indexOf( - array: _.List, + array: _.List, value: T, isSorted?: boolean): number; @@ -795,7 +794,7 @@ interface UnderscoreStatic { * @see _indexof **/ indexOf( - array: _.List, + array: _.List, value: T, startFrom: number): number; @@ -808,7 +807,7 @@ interface UnderscoreStatic { * @return The index of the last occurance of `value` within `array`. **/ lastIndexOf( - array: _.List, + array: _.List, value: T, from?: number): number; @@ -822,7 +821,7 @@ interface UnderscoreStatic { * @return The index where `value` should be inserted into `list`. **/ sortedIndex( - list: _.List, + list: _.List, value: T, iterator?: (x: T) => TSort, context?: any): number; @@ -950,7 +949,7 @@ interface UnderscoreStatic { throttle( func: any, wait: number, - options?: _.ThrottleSettings): Function; + options?: _.ThrottleSettings): Function; /** * Creates and returns a new debounced version of the passed function that will postpone its execution @@ -1346,13 +1345,13 @@ interface UnderscoreStatic { * @param settings Settings to use while compiling. * @return Returns the compiled Underscore HTML template. **/ - template(templateString: string, data?: any, settings?: _.TemplateSettings): (...data: any[]) => string; + template(templateString: string, data?: any, settings?: _.TemplateSettings): (...data: any[]) => string; /** * By default, Underscore uses ERB-style template delimiters, change the * following template settings to use alternative delimiters. **/ - templateSettings: _.TemplateSettings; + templateSettings: _.TemplateSettings; /* ********** * Chaining * @@ -1364,7 +1363,8 @@ interface UnderscoreStatic { * @param obj Object to chain. * @return Wrapped `obj`. **/ - chain(obj: any): _Chain; + chain(obj: T[]): _Chain; + chain(obj: T): _Chain; /** * Extracts the value of a wrapped object. @@ -2194,13 +2194,29 @@ interface _Chain { * Wrapped type `any[]`. * @see _.map **/ - map(iterator: _.ListIterator, context?: any): _Chain; + map(iterator: (value: T, index: number, list: T[]) => TArray[], context?: any): _ChainOfArrays; + //Not sure why this won't work, might be a TypeScript error? + //map(iterator: _.ListIterator, context?: any): _ChainOfArrays; /** * Wrapped type `any[]`. * @see _.map **/ - map(iterator: _.ObjectIterator, context?: any): _Chain; + map(iterator: _.ListIterator, context?: any): _Chain; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map(iterator: (element: T, key: string, list: any) => TArray[], context?: any): _ChainOfArrays; + //Not sure why this won't work, might be a TypeScript error? + //map(iterator: _.ObjectIterator, context?: any): _ChainOfArrays; + + /** + * Wrapped type `any[]`. + * @see _.map + **/ + map(iterator: _.ObjectIterator, context?: any): _Chain; /** * @see _.map @@ -2243,7 +2259,7 @@ interface _Chain { * Wrapped type `any[]`. * @see _.find **/ - find(iterator: _.ListIterator, context?: any): _Chain; + find(iterator: _.ListIterator, context?: any): _ChainSingle; /** * @see _.find @@ -2271,7 +2287,7 @@ interface _Chain { * Wrapped type `any[]`. * @see _.findWhere **/ - findWhere(properties: U): _Chain; + findWhere(properties: U): _ChainSingle; /** * Wrapped type `any[]`. @@ -2323,43 +2339,43 @@ interface _Chain { * Wrapped type `any[]`. * @see _.pluck **/ - pluck(propertyName: string): _Chain; + pluck(propertyName: string): _Chain; /** * Wrapped type `number[]`. * @see _.max **/ - max(): _Chain; + max(): _ChainSingle; /** * Wrapped type `any[]`. * @see _.max **/ - max(iterator: _.ListIterator, context?: any): _Chain; + max(iterator: _.ListIterator, context?: any): _ChainSingle; /** * Wrapped type `any[]`. * @see _.max **/ - max(iterator?: _.ListIterator, context?: any): _Chain; + max(iterator?: _.ListIterator, context?: any): _ChainSingle; /** * Wrapped type `number[]`. * @see _.min **/ - min(): _Chain; + min(): _ChainSingle; /** * Wrapped type `any[]`. * @see _.min **/ - min(iterator: _.ListIterator, context?: any): _Chain; + min(iterator: _.ListIterator, context?: any): _ChainSingle; /** * Wrapped type `any[]`. * @see _.min **/ - min(iterator?: _.ListIterator, context?: any): _Chain; + min(iterator?: _.ListIterator, context?: any): _ChainSingle; /** * Wrapped type `any[]`. @@ -2518,7 +2534,7 @@ interface _Chain { * Wrapped type `any`. * @see _.flatten **/ - flatten(shallow?: boolean): _Chain; + flatten(shallow?: boolean): _Chain; /** * Wrapped type `any[]`. @@ -2947,7 +2963,13 @@ interface _Chain { * Wrapped type `any`. * @see _.value **/ - value(): TResult; + value(): T[]; +} +interface _ChainSingle { + value(): T; +} +interface _ChainOfArrays extends _Chain { + flatten(): _Chain; } declare var _: UnderscoreStatic; diff --git a/unity-webapi/unity-webapi.d.ts b/unity-webapi/unity-webapi.d.ts index 9170a26c19..3adf0c03ee 100644 --- a/unity-webapi/unity-webapi.d.ts +++ b/unity-webapi/unity-webapi.d.ts @@ -1,6 +1,6 @@ // Type definitions for Ubuntu Unity Web API 1.0 // Project: https://launchpad.net/libunity-webapps -// Definitions by: John Vrbanac | https://github.com/jmvrbanac +// Definitions by: John Vrbanac // Definitions: https://github.com/borisyankov/DefinitelyTyped interface External { diff --git a/universal-analytics/universal-analytics-test.ts b/universal-analytics/universal-analytics-test.ts new file mode 100644 index 0000000000..90b68d6a27 --- /dev/null +++ b/universal-analytics/universal-analytics-test.ts @@ -0,0 +1,87 @@ +/// + +var ui:UniversalAnalytics; + +var str:string; +var num:number; +var value:any; +var bool:boolean; +var params:Object; +var x:any; + +var client:UniversalAnalytics.Client = ui('UA-123-00'); +client = client.debug(); +client.send(); + +client = client.pageview(str); +client.pageview(str, (err:any) => {}); +client = client.pageview(params); +client.pageview(params, (err:any) => {}); +client = client.pageview(str, str); +client.pageview(str, str, (err:any) => {}); +client = client.pageview(str, str, str); +client.pageview(str, str, str, (err:any) => {}); + + +client = client.event(str, str); +client.event(str, str, (err:any) => {}); +client = client.event(str, str, str); +client.event(str, str, str, (err:any) => {}); +client = client.event(str, str, str, value); +client.event(str, str, str, value, (err:any) => {}); +client.event(str, str, str, value, params, (err:any) => {}); +client = client.event(params); +client.event(params, (err:any) => {}); + + +client = client.transaction(str); +client.transaction(str, (err:any) => {}); +client = client.transaction(str, num); +client.transaction(str, num, (err:any) => {}); +client = client.transaction(str, num, num); +client.transaction(str, num, num, (err:any) => {}); +client = client.transaction(str, num, num, num); +client.transaction(str, num, num, num, (err:any) => {}); +client = client.transaction(str, num, num, num, str); +client.transaction(str, num, num, num, str, (err:any) => {}); +client = client.transaction(params); +client.transaction(params, (err:any) => {}); + + +client = client.item(num); +client.item(num, (err:any) => {}); +client = client.item(num, num); +client.item(num, num, (err:any) => {}); +client = client.item(num, num, num); +client.item(num, num, num, (err:any) => {}); +client = client.item(num, num, num, str); +client.item(num, num, num, str, (err:any) => {}); +client = client.item(num, num, num, str, str); +client.item(num, num, num, str, str, (err:any) => {}); +client = client.item(num, num, num, str, str, params); +client.item(num, num, num, str, str, params, (err:any) => {}); +client = client.item(params); +client.item(params, (err:any) => {}); + + +client = client.exception(str); +client.exception(str, (err:any) => {}); +client = client.exception(str, bool); +client.exception(str, bool, (err:any) => {}); +client = client.exception(params); +client.exception(params, (err:any) => {}); + + +client = client.timing(str); +client.timing(str, (err:any) => {}); +client = client.timing(str, str); +client.timing(str, str, (err:any) => {}); +client = client.timing(str, str, num); +client.timing(str, str, num, (err:any) => {}); +client = client.timing(str, str, num, str); +client.timing(str, str, num, str, (err:any) => {}); +client = client.timing(params); +client.timing(params, (err:any) => {}); + + +x = client.middleware(str, {}); diff --git a/universal-analytics/universal-analytics.d.ts b/universal-analytics/universal-analytics.d.ts new file mode 100644 index 0000000000..7b08d85293 --- /dev/null +++ b/universal-analytics/universal-analytics.d.ts @@ -0,0 +1,94 @@ +// Type definitions for universal-analytics v0.3.2 +// Project: https://github.com/peaksandpies/universal-analytics +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface UniversalAnalytics { + (accountID:string, uuid?:string, opts?:Object):UniversalAnalytics.Client; +} + +declare module UniversalAnalytics { + + interface Client { + debug():UniversalAnalytics.Client; + + send():void; + + pageview(path:string):Client; + pageview(path:string, callback?:(err:any) => void):void; + pageview(params:Object):Client; + pageview(params:Object, callback?:(err:any) => void):void; + pageview(path:string, hostname:string):Client; + pageview(path:string, hostname:string, callback?:(err:any) => void):void; + pageview(path:string, title:string, hostname:string):Client; + pageview(path:string, title:string, hostname:string, callback?:(err:any) => void):void; + + + event(category:string, action:string):Client; + event(category:string, action:string, callback?:(err:any) => void):void; + event(category:string, action:string, label:string):Client; + event(category:string, action:string, label:string, callback?:(err:any) => void):void; + event(category:string, action:string, label:string, value:any):Client; + event(category:string, action:string, label:string, value:any, callback?:(err:any) => void):void; + event(category:string, action:string, label:string, value:any, params:Object, callback?:(err:any) => void):void; + event(params:Object):Client; + event(params:Object, callback:(err:any) => void):void; + + + transaction(id:string):Client; + transaction(id:string, callback:(err:any) => void):void; + transaction(id:string, revenue:number):Client; + transaction(id:string, revenue:number, callback:(err:any) => void):void; + transaction(id:string, revenue:number, shipping:number):Client; + transaction(id:string, revenue:number, shipping:number, callback:(err:any) => void):void; + transaction(id:string, revenue:number, shipping:number, taxping:number):Client; + transaction(id:string, revenue:number, shipping:number, taxping:number, callback:(err:any) => void):void; + transaction(id:string, revenue:number, shipping:number, taxping:number, affiliation:string):Client; + transaction(id:string, revenue:number, shipping:number, taxping:number, affiliation:string, callback:(err:any) => void):void; + transaction(params:Object):Client; + transaction(params:Object, callback:(err:any) => void):void; + + + item(price:number):Client; + item(price:number, callback:(err:any) => void):void; + item(price:number, quantity:number):Client; + item(price:number, quantity:number, callback:(err:any) => void):void; + item(price:number, quantity:number, sku:number):Client; + item(price:number, quantity:number, sku:number, callback:(err:any) => void):void; + item(price:number, quantity:number, sku:number, name:string):Client; + item(price:number, quantity:number, sku:number, name:string, callback:(err:any) => void):void; + item(price:number, quantity:number, sku:number, name:string, variation:string):Client; + item(price:number, quantity:number, sku:number, name:string, variation:string, callback:(err:any) => void):void; + item(price:number, quantity:number, sku:number, name:string, variation:string, params:Object):Client; + item(price:number, quantity:number, sku:number, name:string, variation:string, params:Object, callback:(err:any) => void):void; + item(params:Object):Client; + item(params:Object, callback:(err:any) => void):void; + + + exception(description:string):Client; + exception(description:string, callback:(err:any) => void):void; + exception(description:string, fatal:boolean):Client; + exception(description:string, fatal:boolean, callback:(err:any) => void):void; + exception(params:Object):Client; + exception(params:Object, callback:(err:any) => void):void; + + + timing(category:string):Client; + timing(category:string, callback:(err:any) => void):void; + timing(category:string, variable:string):Client; + timing(category:string, variable:string, callback:(err:any) => void):void; + timing(category:string, variable:string, time:number):Client; + timing(category:string, variable:string, time:number, callback:(err:any) => void):void; + timing(category:string, variable:string, time:number, label:string):Client; + timing(category:string, variable:string, time:number, label:string, callback:(err:any) => void):void; + timing(params:Object):Client; + timing(params:Object, callback:(err:any) => void):void; + + + middleware(accountID:string, options?:any):any; + } +} + +declare module 'universal-analytics' { +export = UniversalAnalytics; +} diff --git a/urijs/URI.d.ts b/urijs/URI.d.ts index 6d6dcb6124..21c7faf982 100644 --- a/urijs/URI.d.ts +++ b/urijs/URI.d.ts @@ -1,6 +1,8 @@ -// URI.js +// Type definitions for URI.js // Project: https://github.com/medialize/URI.js -// Definitions by: https://github.com/RodneyJT +// Definitions by: RodneyJT +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// interface URIOptions { @@ -181,4 +183,4 @@ declare class URI { interface JQuery { uri(): URI; -} \ No newline at end of file +} diff --git a/vega/vega-tests.ts b/vega/vega-tests.ts new file mode 100644 index 0000000000..2cbf9d7b9a --- /dev/null +++ b/vega/vega-tests.ts @@ -0,0 +1,2049 @@ +/// + +// examples from http://trifacta.github.io/vega/editor/ +var specs: Vega.Spec[] = [ + { + "name": "arc", + "width": 400, + "height": 400, + "data": [ + { + "name": "table", + "values": [12, 23, 47, 6, 52, 19], + "transform": [ + {"type": "pie", "value": "data"} + ] + } + ], + "scales": [ + { + "name": "r", + "type": "sqrt", + "domain": {"data": "table", "field": "data"}, + "range": [20, 100] + } + ], + "marks": [ + { + "type": "arc", + "from": {"data": "table"}, + "properties": { + "enter": { + "x": {"group": "width", "mult": 0.5}, + "y": {"group": "height", "mult": 0.5}, + "startAngle": {"field": "startAngle"}, + "endAngle": {"field": "endAngle"}, + "innerRadius": {"value": 20}, + "outerRadius": {"scale": "r"}, + "stroke": {"value": "#fff"} + }, + "update": { + "fill": {"value": "#ccc"} + }, + "hover": { + "fill": {"value": "pink"} + } + } + } + ] + }, + { + "width": 500, + "height": 200, + "padding": {"top": 10, "left": 30, "bottom": 30, "right": 10}, + "data": [ + { + "name": "table", + "values": [ + {"x": 1, "y": 28}, {"x": 2, "y": 55}, + {"x": 3, "y": 43}, {"x": 4, "y": 91}, + {"x": 5, "y": 81}, {"x": 6, "y": 53}, + {"x": 7, "y": 19}, {"x": 8, "y": 87}, + {"x": 9, "y": 52}, {"x": 10, "y": 48}, + {"x": 11, "y": 24}, {"x": 12, "y": 49}, + {"x": 13, "y": 87}, {"x": 14, "y": 66}, + {"x": 15, "y": 17}, {"x": 16, "y": 27}, + {"x": 17, "y": 68}, {"x": 18, "y": 16}, + {"x": 19, "y": 49}, {"x": 20, "y": 15} + ] + } + ], + "scales": [ + { + "name": "x", + "type": "linear", + "range": "width", + "zero": false, + "domain": {"data": "table", "field": "data.x"} + }, + { + "name": "y", + "type": "linear", + "range": "height", + "nice": true, + "domain": {"data": "table", "field": "data.y"} + } + ], + "axes": [ + {"type": "x", "scale": "x", "ticks": 20}, + {"type": "y", "scale": "y"} + ], + "marks": [ + { + "type": "area", + "from": {"data": "table"}, + "properties": { + "enter": { + "interpolate": {"value": "monotone"}, + "x": {"scale": "x", "field": "data.x"}, + "y": {"scale": "y", "field": "data.y"}, + "y2": {"scale": "y", "value": 0}, + "fill": {"value": "steelblue"} + }, + "update": { + "fillOpacity": {"value": 1} + }, + "hover": { + "fillOpacity": {"value": 0.5} + } + } + } + ] + }, + { + "width": 400, + "height": 200, + "padding": {"top": 10, "left": 30, "bottom": 30, "right": 10}, + "data": [ + { + "name": "table", + "values": [ + {"x": 1, "y": 28}, {"x": 2, "y": 55}, + {"x": 3, "y": 43}, {"x": 4, "y": 91}, + {"x": 5, "y": 81}, {"x": 6, "y": 53}, + {"x": 7, "y": 19}, {"x": 8, "y": 87}, + {"x": 9, "y": 52}, {"x": 10, "y": 48}, + {"x": 11, "y": 24}, {"x": 12, "y": 49}, + {"x": 13, "y": 87}, {"x": 14, "y": 66}, + {"x": 15, "y": 17}, {"x": 16, "y": 27}, + {"x": 17, "y": 68}, {"x": 18, "y": 16}, + {"x": 19, "y": 49}, {"x": 20, "y": 15} + ] + } + ], + "scales": [ + { + "name": "x", + "type": "ordinal", + "range": "width", + "domain": {"data": "table", "field": "data.x"} + }, + { + "name": "y", + "range": "height", + "nice": true, + "domain": {"data": "table", "field": "data.y"} + } + ], + "axes": [ + {"type": "x", "scale": "x"}, + {"type": "y", "scale": "y"} + ], + "marks": [ + { + "type": "rect", + "from": {"data": "table"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.x"}, + "width": {"scale": "x", "band": true, "offset": -1}, + "y": {"scale": "y", "field": "data.y"}, + "y2": {"scale": "y", "value": 0} + }, + "update": { + "fill": {"value": "steelblue"} + }, + "hover": { + "fill": {"value": "red"} + } + } + } + ] + }, + { + "width": 200, + "height": 720, + "data": [ + { + "name": "barley", + "url": "data/barley.json" + }, + { + "name": "variety", + "source": "barley", + "transform": [ + {"type": "facet", "keys": ["data.variety"]}, + {"type": "stats", "value": "data.yield", "median": true}, + {"type": "sort", "by": "-median"} + ] + }, + { + "name": "site", + "source": "barley", + "transform": [ + {"type": "facet", "keys": ["data.site"]}, + {"type": "stats", "value": "data.yield", "median": true}, + {"type": "sort", "by": "-median"} + ] + } + ], + "scales": [ + { + "name": "g", + "type": "ordinal", + "range": "height", + "padding": 0.15, + "domain": {"data": "site", "field": "key"} + }, + { + "name": "x", + "type": "linear", + "nice": true, + "range": "width", + "domain": {"data": "barley", "field": "data.yield"} + }, + { + "name": "c", + "type": "ordinal", + "range": "category10" + } + ], + "axes": [ + {"type": "x", "scale": "x", "offset": -12} + ], + "marks": [ + { + "type": "text", + "from": {"data": "site"}, + "properties": { + "enter": { + "x": {"group": "width", "mult": 0.5}, + "y": {"scale": "g", "field": "key", "offset": -2}, + "fontWeight": {"value": "bold"}, + "text": {"field": "key"}, + "align": {"value": "center"}, + "baseline": {"value": "bottom"}, + "fill": {"value": "#000"} + } + } + }, + { + "type": "group", + "from": {"data": "site"}, + "scales": [ + { + "name": "y", + "type": "ordinal", + "range": "height", + "points": true, + "padding": 1.2, + "domain": {"data": "variety", "field": "key"} + } + ], + "axes": [ + { + "type": "y", + "scale": "y", + "tickSize": 0, + "properties": {"axis": {"stroke": {"value": "transparent"}}} + } + ], + "properties": { + "enter": { + "x": {"value": 0.5}, + "y": {"scale": "g", "field": "key"}, + "height": {"scale": "g", "band": true}, + "width": {"group": "width"}, + "stroke": {"value": "#ccc"} + } + }, + "marks": [ + { + "type": "symbol", + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.yield"}, + "y": {"scale": "y", "field": "data.variety"}, + "size": {"value": 50}, + "stroke": {"scale": "c", "field": "data.year"}, + "strokeWidth": {"value": 2} + } + } + } + ] + } + ] + }, + { + "width": 960, + "height": 500, + "data": [ + { + "name": "unemp", + "url": "data/unemployment.tsv", + "format": {"type": "tsv", "parse": {"rate":"number"}} + }, + { + "name": "counties", + "url": "data/us-10m.json", + "format": {"type": "topojson", "feature": "counties"}, + "transform": [ + {"type": "geopath", "value": "data", "projection": "albersUsa"}, + { + "type": "zip", + "key": "data.id", + "with": "unemp", + "withKey": "data.id", + "as": "value", + "default": null + }, + {"type":"filter", "test":"d.path!=null && d.value!=null"} + ] + } + ], + "scales": [ + { + "name": "color", + "type": "quantize", + "domain": [0, 0.15], + "range": ["#f7fbff", "#deebf7", "#c6dbef", "#9ecae1", "#6baed6", + "#4292c6", "#2171b5", "#08519c", "#08306b"] + } + ], + "marks": [ + { + "type": "path", + "from": {"data": "counties"}, + "properties": { + "enter": { "path": {"field": "path"} }, + "update": { "fill": {"scale":"color", "field":"value.data.rate"} }, + "hover": { "fill": {"value": "red"} } + } + } + ] + }, + { + "width": 300, + "height": 240, + "data": [ + { + "name": "table", + "url": "data/groups.json" + } + ], + "scales": [ + { + "name": "cat", + "type": "ordinal", + "range": "height", + "padding": 0.2, + "domain": {"data": "table", "field": "data.category"} + }, + { + "name": "val", + "range": "width", + "round": true, + "nice": true, + "domain": {"data": "table", "field": "data.value"} + }, + { + "name": "color", + "type": "ordinal", + "range": "category20" + } + ], + "axes": [ + {"type": "y", "scale": "cat", "tickSize": 0, "tickPadding": 8}, + {"type": "x", "scale": "val"} + ], + "marks": [ + { + "type": "group", + "from": { + "data": "table", + "transform": [{"type":"facet", "keys":["data.category"]}] + }, + "properties": { + "enter": { + "y": {"scale": "cat", "field": "key"}, + "height": {"scale": "cat", "band": true} + } + }, + "scales": [ + { + "name": "pos", + "type": "ordinal", + "range": "height", + "domain": {"field": "data.position"} + } + ], + "marks": [ + { + "type": "rect", + "properties": { + "enter": { + "y": {"scale": "pos", "field": "data.position"}, + "height": {"scale": "pos", "band": true}, + "x": {"scale": "val", "field": "data.value"}, + "x2": {"scale": "val", "value": 0}, + "fill": {"scale": "color", "field": "data.position"} + } + } + }, + { + "type": "text", + "properties": { + "enter": { + "y": {"scale": "pos", "field": "data.position"}, + "dy": {"scale": "pos", "band": true, "mult": 0.5}, + "x": {"scale": "val", "field": "data.value", "offset": -4}, + "fill": {"value": "white"}, + "align": {"value": "right"}, + "baseline": {"value": "middle"}, + "text": {"field": "data.value"} + } + } + } + ] + } + ] + }, + { + "width": 400, + "height": 100, + "padding": {"top": 30, "left": 30, "bottom": 30, "right": 10}, + "data": [ + { + "name": "stats", + "values": [ + {"label": "Category A", "mean": 1, "lo": 0, "hi": 2}, + {"label": "Category B", "mean": 2, "lo": 1.5, "hi": 2.5}, + {"label": "Category C", "mean": 3, "lo": 1.7, "hi": 4.3}, + {"label": "Category D", "mean": 4, "lo": 3, "hi": 5}, + {"label": "Category E", "mean": 5, "lo": 4.1, "hi": 5.9} + ] + } + ], + "scales": [ + { + "name": "y", + "type": "ordinal", + "range": "height", + "domain": {"data": "stats", "field": "index"} + }, + { + "name": "x", + "range": [100, 400], + "nice": true, + "zero": true, + "domain": {"data": "stats", "field": "data.hi"} + } + ], + "axes": [ + {"type": "x", "scale": "x", "ticks": 6} + ], + "marks": [ + { + "type": "text", + "from": {"data": "stats"}, + "properties": { + "enter": { + "x": {"value": 0}, + "y": {"scale": "y", "field": "index"}, + "baseline": {"value": "middle"}, + "fill": {"value": "#000"}, + "text": {"field": "data.label"}, + "font": {"value": "Helvetica Neue"}, + "fontSize": {"value": 13} + } + } + }, + { + "type": "rect", + "from": {"data": "stats"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.lo"}, + "x2": {"scale": "x", "field": "data.hi"}, + "y": {"scale": "y", "field": "index", "offset": -1}, + "height": {"value": 1}, + "fill": {"value": "#888"} + } + } + }, + { + "type": "symbol", + "from": {"data": "stats"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.mean"}, + "y": {"scale": "y", "field": "index"}, + "size": {"value": 40}, + "fill": {"value": "#000"} + } + } + } + ] + }, + { + "name": "force", + "width": 500, + "height": 500, + "padding": {"top":0, "bottom":0, "left":0, "right":0}, + "data": [ + { + "name": "edges", + "url": "data/miserables.json", + "format": {"type": "json", "property": "links"}, + "transform": [ + {"type": "copy", "from": "data", "fields": ["source", "target"]} + ] + }, + { + "name": "nodes", + "url": "data/miserables.json", + "format": {"type": "json", "property": "nodes"}, + "transform": [ + { + "type": "force", + "links": "edges", + "linkDistance": 70, + "charge": -100, + "iterations": 1000 + } + ] + } + ], + "marks": [ + { + "type": "path", + "from": { + "data": "edges", + "transform": [ + {"type": "link", "shape": "line"} + ] + }, + "properties": { + "update": { + "path": {"field": "path"}, + "stroke": {"value": "#ccc"}, + "strokeWidth": {"value": 0.5} + } + } + }, + { + "type": "symbol", + "from": {"data": "nodes"}, + "properties": { + "enter": { + "fillOpacity": {"value": 0.3}, + "stroke": {"value": "steelblue"} + }, + "update": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "fill": {"value": "steelblue"} + }, + "hover": { + "fill": {"value": "#f00"} + } + } + } + ] + }, + { + "name": "image", + "width": 200, + "height": 200, + "padding": {"left":30, "top":10, "bottom":30, "right":10}, + "data": [ + { + "name": "data", + "values": [ + {"x":0.5, "y":0.5, "img":"data/ffox.png"}, + {"x":1.5, "y":1.5, "img":"data/gimp.png"}, + {"x":2.5, "y":2.5, "img":"data/7zip.png"} + ] + } + ], + "scales": [ + {"name": "x", "domain": [0, 3], "range": "width"}, + {"name": "y", "domain": [0, 3], "range": "height"} + ], + "axes": [ + {"type": "x", "scale": "x"}, + {"type": "y", "scale": "y"} + ], + "marks": [ + { + "type": "image", + "from": {"data": "data"}, + "properties": { + "enter": { + "url": {"field": "data.img"}, + "width": {"value": 50}, + "height": {"value": 50}, + "x": {"scale": "x", "field": "data.x"}, + "y": {"scale": "y", "field": "data.y"}, + "align": {"value": "center"}, + "baseline": {"value": "middle"} + }, + "update": { + "opacity": {"value": 1.0} + }, + "hover": { + "opacity": {"value": 0.5} + } + } + } + ] + }, + { + "width": 800, + "height": 500, + "padding": {"left": 15, "right": 65, "top": 10, "bottom": 20}, + "data": [ + { + "name": "jobs", + "url": "data/jobs.json" + }, + { + "name": "series", + "source": "jobs", + "transform": [ + {"type": "facet", "keys": ["data.job", "data.sex"]}, + {"type": "stats", "value": "data.perc"}, + {"type": "stack", "point": "data.year", "height": "data.perc", "order": "reverse"} + ] + }, + { + "name": "stats", + "source": "jobs", + "transform": [ + {"type": "facet", "keys": ["data.year"]}, + {"type": "stats", "value": "data.perc"} + ] + } + ], + "scales": [ + { + "name": "x", + "type": "linear", + "range": "width", + "zero": false, "round": true, + "domain": {"data": "jobs", "field": "data.year"} + }, + { + "name": "y", + "type": "linear", + "range": "height", "round": true, + "domain": {"data": "stats", "field": "sum"} + }, + { + "name": "color", + "type": "ordinal", + "domain": ["men", "women"], + "range": ["#33f", "#f33"] + }, + { + "name": "alpha", + "type": "linear", + "domain": {"data": "series", "field": "sum"}, + "range": [0.4, 0.8] + }, + { + "name": "font", + "type": "sqrt", + "range": [0,24], "round": true, + "domain": {"data": "stats", "field": "sum"} + }, + { + "name": "align", + "type": "quantize", + "range": ["left", "center", "right"], "zero":false, + "domain": [1730, 2130] + }, + { + "name": "offset", + "type": "quantize", + "range": [6, 0, -6], "zero":false, + "domain": [1730, 2130] + } + ], + "axes": [ + {"type": "x", "scale": "x", "format": "d", "ticks": 15, "tickSizeEnd": 0}, + { + "type": "y", "scale": "y", "format": "n", "orient": "right", + "grid": true, "layer": "back", "tickSize": 12, + "properties": { + "axis": {"stroke": {"value":"transparent"}}, + "grid": {"stroke": {"value": "#ccc"}}, + "ticks": {"stroke": {"value": "#ccc"}} + } + } + ], + "marks": [ + { + "type": "group", + "from": {"data": "series"}, + "marks": [ + { + "type": "area", + "properties": { + "update": { + "x": {"scale": "x", "field": "data.year"}, + "y": {"scale": "y", "field": "y"}, + "y2": {"scale": "y", "field": "y2"}, + "fill": {"scale": "color", "field": "data.sex"}, + "fillOpacity": {"scale": "alpha", "group": "sum"} + }, + "hover": { + "fillOpacity": {"value": 0.2} + } + } + } + ] + }, + { + "type": "group", + "from": {"data": "series"}, + "marks": [ + { + "type": "text", + "from": { + "transform": [ + {"type":"slice", "by":"max", "field":"data.perc"} + ] + }, + "interactive": false, + "properties": { + "update": { + "x": {"scale": "x", "field": "data.year"}, + "dx": {"scale": "offset", "field": "data.year"}, + "y": {"scale": "y", "field": "cy"}, + "fill": {"value": "#000"}, + "fillOpacity": {"scale": "font", "field": "data.perc", "mult": 0.15}, + "fontSize": {"scale": "font", "field": "data.perc", "offset": 5}, + "text": {"field": "data.job"}, + "align": {"scale": "align", "field": "data.year"}, + "baseline": {"value": "middle"} + } + } + } + ] + } + ] + }, + { + "name": "lifelines", + "width": 400, + "height": 100, + "data": [ + { + "name": "people", + "values": [ + {"label":"Washington", "born":-7506057600000, "died":-5366196000000, + "enter":-5701424400000, "leave":-5453884800000}, + {"label":"Adams", "born":-7389766800000, "died":-4528285200000, + "enter":-5453884800000, "leave":-5327740800000}, + {"label":"Jefferson", "born":-7154586000000, "died":-4528285200000, + "enter":-5327740800000, "leave":-5075280000000}, + {"label":"Madison", "born":-6904544400000, "died":-4213184400000, + "enter":-5075280000000, "leave":-4822819200000}, + {"label":"Monroe", "born":-6679904400000, "died":-4370518800000, + "enter":-4822819200000, "leave":-4570358400000} + ] + }, + { + "name": "events", + "format": {"type":"json", "parse":{"when":"date"}}, + "values": [ + {"name":"Decl. of Independence", "when":"July 4, 1776"}, + {"name":"U.S. Constitution", "when":"3/4/1789"}, + {"name":"Louisiana Purchase", "when":"April 30, 1803"}, + {"name":"Monroe Doctrine", "when":"Dec 2, 1823"} + ] + } + + ], + "scales": [ + { + "name": "y", + "type": "ordinal", + "range": "height", + "domain": {"data": "people", "field": "data.label"} + }, + { + "name": "x", + "type": "time", + "range": "width", + "round": true, + "nice": "year", + "domain": {"data": "people", "field": ["data.born", "data.died"]} + } + ], + "axes": [ + {"type": "x", "scale": "x"} + ], + "marks": [ + { + "type": "text", + "from": {"data": "events"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.when"}, + "y": {"value": -10}, + "angle": {"value": -25}, + "fill": {"value": "#000"}, + "text": {"field": "data.name"}, + "font": {"value": "Helvetica Neue"}, + "fontSize": {"value": 10} + } + } + }, + { + "type": "rect", + "from": {"data": "events"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.when"}, + "y": {"value": -8}, + "width": {"value": 1}, + "height": {"group": "height", "offset": 8}, + "fill": {"value": "#888"} + } + } + }, + { + "type": "text", + "from": {"data": "people"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.born"}, + "y": {"scale": "y", "field": "data.label", "offset": -3}, + "fill": {"value": "#000"}, + "text": {"field": "data.label"}, + "font": {"value": "Helvetica Neue"}, + "fontSize": {"value": 10} + } + } + }, + { + "type": "rect", + "from": {"data": "people"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.born"}, + "x2": {"scale": "x", "field": "data.died"}, + "y": {"scale": "y", "field": "data.label"}, + "height": {"value": 2}, + "fill": {"value": "#557"} + } + } + }, + { + "type": "rect", + "from": {"data": "people"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.enter"}, + "x2": {"scale": "x", "field": "data.leave"}, + "y": {"scale": "y", "field": "data.label", "offset":-1}, + "height": {"value": 4}, + "fill": {"value": "#e44"} + } + } + } + ] + }, + { + "width": 1920, + "height": 1000, + "viewport": [960, 500], + "data": [ + { + "name": "world", + "url": "data/world-110m.json", + "format": {"type": "topojson", "feature": "countries"} + } + ], + "marks": [ + { + "type": "path", + "from": { + "data": "world", + "transform": [{ + "type": "geopath", + "value": "data", + "projection": "winkel3", + "scale": 300, + "translate": [960, 500] + }] + }, + "properties": { + "enter": { + "stroke": {"value": "#fff"}, + "path": {"field": "path"} + }, + "update": {"fill": {"value": "#ccc"}}, + "hover": {"fill": {"value": "pink"}} + } + } + ] + }, + { + "width": 760, + "height": 260, + "data": [ + { + "name": "temp", + "url": "data/napoleon.json", + "format": {"type": "json", "property": "temp"}, + "transform": [ + {"type": "formula", "field": "lat", "expr": "55"}, + { + "type": "geo", + "lat": "lat", + "lon": "data.lon", + "center": [32.52, 53.3], + "scale": 3000 + } + ] + }, + { + "name": "army", + "url": "data/napoleon.json", + "format": {"type": "json", "property": "army"}, + "transform": [ + { + "type": "geo", + "lat": "data.lat", + "lon": "data.lon", + "center": [32.52, 53.3], + "scale": 3000 + } + ] + }, + { + "name": "cities", + "url": "data/napoleon.json", + "format": {"type": "json", "property": "cities"}, + "transform": [ + { + "type": "geo", + "lat": "data.lat", + "lon": "data.lon", + "center": [32.52, 53.3], + "scale": 3000 + } + ] + } + ], + "scales": [ + { + "name": "color", + "type": "ordinal", + "domain": {"data": "army", "field": "data.dir" }, + "range": ["brown", "black"] + }, + { + "name": "lw", + "type": "linear", "zero": false, + "domain": {"data": "army", "field": "data.size"}, + "range": [1, 50] + } + ], + "marks": [ + { + "type": "group", + "properties": { + "enter": { + "x": {"value": 0}, + "y": {"value": 200}, + "width": {"group": "width"}, + "height": {"value": 60} + } + }, + "scales": [ + { + "name": "y", + "type": "linear", "zero": false, "round": true, + "domain": {"data": "temp", "field": "data.temp"}, + "range": "height" + } + ], + "axes": [ + {"type": "y", "scale": "y", "ticks": 4, "orient": "right", + "grid": true, "layer": "back"} + ], + "marks": [ + { + "type": "rule", + "from": {"data": "temp"}, + "properties": { + "enter": { + "x": {"field": "x"}, + "y1": 0, + "y2": {"scale": "y", "field": "data.temp"}, + "stroke": {"value": "#ccc"} + } + } + }, + { + "type": "line", + "from": {"data": "temp"}, + "properties": { + "enter": { + "x": {"field": "x"}, + "y": {"scale": "y", "field": "data.temp"}, + "stroke": {"value": "#000"}, + "strokeWidth": {"value": 2} + } + } + }, + { + "type": "text", + "from": {"data": "temp"}, + "properties": { + "enter": { + "x": {"field": "x", "offset": -2}, + "y": {"scale": "y", "field": "data.temp", "offset": 6}, + "fill": {"value": "#000"}, + "text": {"field": "data.date"}, + "font": {"value": "Georgia"}, + "fontSize": {"value": 10}, + "align": {"value": "center"}, + "baseline": {"value": "top"} + } + } + } + ] + }, + { + "type": "group", + "from": { + "data": "army", + "transform": [ + {"type": "facet", "keys": ["data.group", "data.dir"]} + ] + }, + "marks": [ + { + "type": "group", + "from": { + "transform": [ + {"type": "window", "size": 2, "step": 1} + ] + }, + "marks": [ + { + "type": "line", + "properties": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "stroke": {"scale": "color", "field": "data.dir"}, + "strokeWidth": {"scale": "lw", "field": "data.size"}, + "strokeCap": {"value": "round"} + } + } + } + ] + } + ] + }, + { + "type": "symbol", + "from": {"data": "cities"}, + "properties": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "size": {"value": 25}, + "fill": {"value": "brown"}, + "stroke": {"value": "#000"} + } + } + }, + { + "type": "text", + "from": {"data": "cities"}, + "properties": { + "enter": { + "x": {"field": "x", "offset": 1}, + "y": {"field": "y", "offset": -4}, + "fill": {"value": "#fff"}, + "fillOpacity": {"value": 0.8}, + "text": {"field": "data.city"}, + "align": {"value": "center"}, + "baseline": {"value": "bottom"}, + "font": {"value": "Georgia"}, + "fontSize": {"value": 9}, + "fontStyle": {"value": "italic"} + } + } + }, + { + "type": "text", + "from": {"data": "cities"}, + "properties": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y", "offset": -5}, + "fill": {"value": "#000"}, + "text": {"field": "data.city"}, + "align": {"value": "center"}, + "baseline": {"value": "bottom"}, + "font": {"value": "Georgia"}, + "fontSize": {"value": 9}, + "fontStyle": {"value": "italic"} + } + } + } + ] + }, + { + "width": 700, + "height": 400, + "data": [ + { + "name": "cars", + "url": "data/cars.json" + }, + { + "name": "fields", + "values": ["cyl", "dsp", "lbs", "hp", "acc", "mpg", "year"] + } + ], + "scales": [ + { + "name": "ord", + "type": "ordinal", + "range": "width", "points": true, + "domain": {"data": "fields", "field": "data"} + }, + { + "name": "cyl", + "range": "height", "zero": false, "nice": true, + "domain": {"data": "cars", "field": "data.cyl"} + }, + { + "name": "dsp", + "range": "height", "zero": false, "nice": true, + "domain": {"data": "cars", "field": "data.dsp"} + }, + { + "name": "lbs", + "range": "height", "zero": false, "nice": true, + "domain": {"data": "cars", "field": "data.lbs"} + }, + { + "name": "hp", + "range": "height", "zero": false, "nice": true, + "domain": {"data": "cars", "field": "data.hp"} + }, + { + "name": "acc", + "range": "height", "zero": false, "nice": true, + "domain": {"data": "cars", "field": "data.acc"} + }, + { + "name": "mpg", + "range": "height", "zero": false, "nice": true, + "domain": {"data": "cars", "field": "data.mpg"} + }, + { + "name": "year", + "range": "height", "zero": false, "nice": true, + "domain": {"data": "cars", "field": "data.year"} + } + ], + "axes": [ + {"type":"y", "scale":"cyl", "offset":{"scale":"ord", "value":"cyl"}}, + {"type":"y", "scale":"dsp", "offset":{"scale":"ord", "value":"dsp"}}, + {"type":"y", "scale":"lbs", "offset":{"scale":"ord", "value":"lbs"}}, + {"type":"y", "scale":"hp", "offset":{"scale":"ord", "value":"hp"}}, + {"type":"y", "scale":"acc", "offset":{"scale":"ord", "value":"acc"}}, + {"type":"y", "scale":"mpg", "offset":{"scale":"ord", "value":"mpg"}}, + {"type":"y", "scale":"year", "offset":{"scale":"ord", "value":"year"}} + ], + "marks": [ + { + "type": "group", + "from": {"data": "cars"}, + "marks": [ + { + "type": "line", + "from": {"data": "fields"}, + "properties": { + "enter": { + "x": {"scale": "ord", "field": "data"}, + "y": {"scale": {"field": "data"}, "group": "data", "field": "data"}, + "stroke": {"value": "steelblue"}, + "strokeWidth": {"value": 1}, + "strokeOpacity": {"value": 0.3} + } + } + } + ] + }, + { + "type": "text", + "from": {"data": "fields"}, + "properties": { + "enter": { + "x": {"scale": "ord", "field": "data", "offset":-8}, + "y": {"group": "height", "offset": 6}, + "fontWeight": {"value": "bold"}, + "fill": {"value": "black"}, + "text": {"field": "data"}, + "align": {"value": "right"}, + "baseline": {"value": "top"} + } + } + } + ] + }, + { + "width": 700, + "height": 400, + "padding": {"top": 0, "left": 0, "bottom": 20, "right": 0}, + "data": [ + { + "name": "pop2000", + "url": "data/population.json", + "transform": [ + {"type": "filter", "test": "d.data.year == 2000"} + ] + } + ], + "scales": [ + { + "name": "g", + "domain": [0, 1], + "range": [340, 10] + }, + { + "name": "y", + "type": "ordinal", + "range": "height", + "reverse": true, + "domain": {"data": "pop2000", "field": "data.age"} + }, + { + "name": "c", + "type": "ordinal", + "domain": [1, 2], + "range": ["#1f77b4", "#e377c2"] + } + ], + "marks": [ + { + "type": "text", + "interactive": false, + "from": { + "data": "pop2000", + "transform": [{"type":"unique", "field":"data.age", "as":"age"}] + }, + "properties": { + "enter": { + "x": {"value": 325}, + "y": {"scale": "y", "field": "age", "offset": 11}, + "text": {"field": "age"}, + "baseline": {"value": "middle"}, + "align": {"value": "center"}, + "fill": {"value": "#000"} + } + } + }, + { + "type": "group", + "from": { + "data": "pop2000", + "transform": [ + {"type":"facet", "keys":["data.sex"]} + ] + }, + "properties": { + "update": { + "x": {"scale": "g", "field": "index"}, + "y": {"value": 0}, + "width": {"value": 300}, + "height": {"group": "height"} + } + }, + "scales": [ + { + "name": "x", + "type": "linear", + "range": "width", + "reverse": {"field": "index"}, + "nice": true, + "domain": {"data": "pop2000", "field": "data.people"} + } + ], + "axes": [ + {"type": "x", "scale": "x", "format": "s"} + ], + "marks": [ + { + "type": "rect", + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.people"}, + "x2": {"scale": "x", "value": 0}, + "y": {"scale": "y", "field": "data.age"}, + "height": {"scale": "y", "band": true, "offset": -1}, + "fillOpacity": {"value": 0.6}, + "fill": {"scale": "c", "field": "data.sex"} + } + } + } + ] + } + ] + }, + { + "width": 200, + "height": 200, + "data": [ + { + "name": "iris", + "url": "data/iris.json" + } + ], + "scales": [ + { + "name": "x", + "nice": true, + "range": "width", + "domain": {"data": "iris", "field": "data.sepalWidth"} + }, + { + "name": "y", + "nice": true, + "range": "height", + "domain": {"data": "iris", "field": "data.petalLength"} + }, + { + "name": "c", + "type": "ordinal", + "domain": {"data": "iris", "field": "data.species"}, + "range": ["#800", "#080", "#008"] + } + ], + "axes": [ + {"type": "x", "scale": "x", "offset": 5, "ticks": 5, "title": "Sepal Width"}, + {"type": "y", "scale": "y", "offset": 5, "ticks": 5, "title": "Petal Length"} + ], + "legends": [ + { + "fill": "c", + "title": "Species", + "offset": 0, + "properties": { + "symbols": { + "fillOpacity": {"value": 0.5}, + "stroke": {"value": "transparent"} + } + } + } + ], + "marks": [ + { + "type": "symbol", + "from": {"data": "iris"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.sepalWidth"}, + "y": {"scale": "y", "field": "data.petalLength"}, + "fill": {"scale": "c", "field": "data.species"}, + "fillOpacity": {"value": 0.5} + }, + "update": { + "size": {"value": 100}, + "stroke": {"value": "transparent"} + }, + "hover": { + "size": {"value": 300}, + "stroke": {"value": "white"} + } + } + } + ] + }, + { + "width": 600, + "height": 600, + "data": [ + { + "name": "iris", + "url": "data/iris.json" + }, + { + "name": "fields", + "values": ["petalLength", "petalWidth", "sepalWidth", "sepalLength"] + } + ], + "scales": [ + { + "name": "gx", + "type": "ordinal", + "range": "width", + "round": true, + "domain": {"data": "fields", "field": "data"} + }, + { + "name": "gy", + "type": "ordinal", + "range": "height", + "round": true, + "domain": {"data": "fields", "field": "data"} + }, + { + "name": "c", + "type": "ordinal", + "domain": {"data": "iris", "field": "data.species"}, + "range": ["#800", "#080", "#008"] + } + ], + "legends": [ + { + "fill": "c", + "title": "Species", + "offset": 10, + "properties": { + "symbols": { + "fillOpacity": {"value": 0.5}, + "stroke": {"value": "transparent"} + } + } + } + ], + "marks": [ + { + "type": "group", + "from": { + "data": "fields", + "transform": [{"type": "cross"}] + }, + "properties": { + "enter": { + "x": {"scale": "gx", "field": "a.data"}, + "y": {"scale": "gy", "field": "b.data"}, + "width": {"scale": "gx", "band": true, "offset":-35}, + "height": {"scale": "gy", "band": true, "offset":-35}, + "stroke": {"value": "#ddd"} + } + }, + "scales": [ + { + "name": "x", + "range": "width", + "zero": false, + "round": true, + "domain": {"data": "iris", "field": {"group": "a.data"}} + }, + { + "name": "y", + "range": "height", + "zero": false, + "round": true, + "domain": {"data": "iris", "field": {"group": "b.data"}} + } + ], + "axes": [ + {"type": "x", "scale": "x", "ticks": 5}, + {"type": "y", "scale": "y", "ticks": 5} + ], + "marks": [ + { + "type": "symbol", + "from": {"data": "iris"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": {"group": "a.data"}}, + "y": {"scale": "y", "field": {"group": "b.data"}}, + "fill": {"scale": "c", "field": "data.species"}, + "fillOpacity": {"value": 0.5} + }, + "update": { + "size": {"value": 36}, + "stroke": {"value": "transparent"} + }, + "hover": { + "size": {"value": 100}, + "stroke": {"value": "white"} + } + } + } + ] + } + ] + }, + { + "width": 500, + "height": 200, + "padding": {"top": 10, "left": 30, "bottom": 30, "right": 10}, + "data": [ + { + "name": "table", + "values": [ + {"x": 0, "y": 28, "c":0}, {"x": 0, "y": 55, "c":1}, + {"x": 1, "y": 43, "c":0}, {"x": 1, "y": 91, "c":1}, + {"x": 2, "y": 81, "c":0}, {"x": 2, "y": 53, "c":1}, + {"x": 3, "y": 19, "c":0}, {"x": 3, "y": 87, "c":1}, + {"x": 4, "y": 52, "c":0}, {"x": 4, "y": 48, "c":1}, + {"x": 5, "y": 24, "c":0}, {"x": 5, "y": 49, "c":1}, + {"x": 6, "y": 87, "c":0}, {"x": 6, "y": 66, "c":1}, + {"x": 7, "y": 17, "c":0}, {"x": 7, "y": 27, "c":1}, + {"x": 8, "y": 68, "c":0}, {"x": 8, "y": 16, "c":1}, + {"x": 9, "y": 49, "c":0}, {"x": 9, "y": 15, "c":1} + ] + }, + { + "name": "stats", + "source": "table", + "transform": [ + {"type": "facet", "keys": ["data.x"]}, + {"type": "stats", "value": "data.y"} + ] + } + ], + "scales": [ + { + "name": "x", + "type": "linear", + "range": "width", + "zero": false, + "domain": {"data": "table", "field": "data.x"} + }, + { + "name": "y", + "type": "linear", + "range": "height", + "nice": true, + "domain": {"data": "stats", "field": "sum"} + }, + { + "name": "color", + "type": "ordinal", + "range": "category10" + } + ], + "axes": [ + {"type": "x", "scale": "x"}, + {"type": "y", "scale": "y"} + ], + "marks": [ + { + "type": "group", + "from": { + "data": "table", + "transform": [ + {"type": "facet", "keys": ["data.c"]}, + {"type": "stack", "point": "data.x", "height": "data.y"} + ] + }, + "marks": [ + { + "type": "area", + "properties": { + "enter": { + "interpolate": {"value": "monotone"}, + "x": {"scale": "x", "field": "data.x"}, + "y": {"scale": "y", "field": "y"}, + "y2": {"scale": "y", "field": "y2"}, + "fill": {"scale": "color", "field": "data.c"} + }, + "update": { + "fillOpacity": {"value": 1} + }, + "hover": { + "fillOpacity": {"value": 0.5} + } + } + } + ] + } + ] + }, + { + "width": 500, + "height": 200, + "padding": {"top": 10, "left": 30, "bottom": 30, "right": 10}, + "data": [ + { + "name": "table", + "values": [ + {"x": 0, "y": 28, "c":0}, {"x": 0, "y": 55, "c":1}, + {"x": 1, "y": 43, "c":0}, {"x": 1, "y": 91, "c":1}, + {"x": 2, "y": 81, "c":0}, {"x": 2, "y": 53, "c":1}, + {"x": 3, "y": 19, "c":0}, {"x": 3, "y": 87, "c":1}, + {"x": 4, "y": 52, "c":0}, {"x": 4, "y": 48, "c":1}, + {"x": 5, "y": 24, "c":0}, {"x": 5, "y": 49, "c":1}, + {"x": 6, "y": 87, "c":0}, {"x": 6, "y": 66, "c":1}, + {"x": 7, "y": 17, "c":0}, {"x": 7, "y": 27, "c":1}, + {"x": 8, "y": 68, "c":0}, {"x": 8, "y": 16, "c":1}, + {"x": 9, "y": 49, "c":0}, {"x": 9, "y": 15, "c":1} + ] + }, + { + "name": "stats", + "source": "table", + "transform": [ + {"type": "facet", "keys": ["data.x"]}, + {"type": "stats", "value": "data.y"} + ] + } + ], + "scales": [ + { + "name": "x", + "type": "ordinal", + "range": "width", + "domain": {"data": "table", "field": "data.x"} + }, + { + "name": "y", + "type": "linear", + "range": "height", + "nice": true, + "domain": {"data": "stats", "field": "sum"} + }, + { + "name": "color", + "type": "ordinal", + "range": "category10" + } + ], + "axes": [ + {"type": "x", "scale": "x"}, + {"type": "y", "scale": "y"} + ], + "marks": [ + { + "type": "group", + "from": { + "data": "table", + "transform": [ + {"type": "facet", "keys": ["data.c"]}, + {"type": "stack", "point": "data.x", "height": "data.y"} + ] + }, + "marks": [ + { + "type": "rect", + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.x"}, + "width": {"scale": "x", "band": true, "offset": -1}, + "y": {"scale": "y", "field": "y"}, + "y2": {"scale": "y", "field": "y2"}, + "fill": {"scale": "color", "field": "data.c"} + }, + "update": { + "fillOpacity": {"value": 1} + }, + "hover": { + "fillOpacity": {"value": 0.5} + } + } + } + ] + } + ] + }, + { + "width": 500, + "height": 200, + "data": [ + { + "name": "stocks", + "url": "data/stocks.csv", + "format": {"type": "csv", "parse": {"price":"number", "date":"date"}} + } + ], + "scales": [ + { + "name": "x", + "type": "time", + "range": "width", + "domain": {"data": "stocks", "field": "data.date"} + }, + { + "name": "y", + "type": "linear", + "range": "height", + "nice": true, + "domain": {"data": "stocks", "field": "data.price"} + }, + { + "name": "color", "type": "ordinal", "range": "category10" + } + ], + "axes": [ + {"type": "x", "scale": "x", "tickSizeEnd": 0}, + {"type": "y", "scale": "y"} + ], + "marks": [ + { + "type": "group", + "from": { + "data": "stocks", + "transform": [{"type": "facet", "keys": ["data.symbol"]}] + }, + "marks": [ + { + "type": "line", + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.date"}, + "y": {"scale": "y", "field": "data.price"}, + "stroke": {"scale": "color", "field": "data.symbol"}, + "strokeWidth": {"value": 2} + } + } + }, + { + "type": "text", + "from": { + "transform": [{"type": "filter", "test": "index==data.length-1"}] + }, + "properties": { + "enter": { + "x": {"scale": "x", "field": "data.date", "offset": 2}, + "y": {"scale": "y", "field": "data.price"}, + "fill": {"scale": "color", "field": "data.symbol"}, + "text": {"field": "data.symbol"}, + "baseline": {"value": "middle"} + } + } + } + ] + } + ] + }, + { + "name": "treemap", + "width": 960, + "height": 500, + "padding": 2.5, + "data": [ + { + "name": "tree", + "url": "data/flare.json", + "format": {"type": "treejson"}, + "transform": [ + {"type": "treemap", "value": "data.size"} + ] + } + ], + "scales": [ + { + "name": "color", + "type": "ordinal", + "range": [ + "#3182bd", "#6baed6", "#9ecae1", "#c6dbef", "#e6550d", + "#fd8d3c", "#fdae6b", "#fdd0a2", "#31a354", "#74c476", + "#a1d99b", "#c7e9c0", "#756bb1", "#9e9ac8", "#bcbddc", + "#dadaeb", "#636363", "#969696", "#bdbdbd", "#d9d9d9" + ] + }, + { + "name": "size", + "type": "ordinal", + "domain": [0, 1, 2, 3], + "range": [256, 28, 20, 14] + }, + { + "name": "opacity", + "type": "ordinal", + "domain": [0, 1, 2, 3], + "range": [0.15, 0.5, 0.8, 1.0] + } + ], + "marks": [ + { + "type": "rect", + "from": { + "data": "tree", + "transform": [{"type":"filter", "test":"d.values"}] + }, + "interactive": false, + "properties": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "width": {"field": "width"}, + "height": {"field": "height"}, + "fill": {"scale": "color", "field": "data.name"} + } + } + }, + { + "type": "rect", + "from": { + "data": "tree", + "transform": [{"type":"filter", "test":"!d.values"}] + }, + "properties": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "width": {"field": "width"}, + "height": {"field": "height"}, + "stroke": {"value": "#fff"} + }, + "update": { + "fill": {"value": "rgba(0,0,0,0)"} + }, + "hover": { + "fill": {"value": "red"} + } + } + }, + { + "type": "text", + "from": { + "data": "tree", + "transform": [{"type":"filter", "test":"d.values"}] + }, + "interactive": false, + "properties": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "dx": {"field": "width", "mult": 0.5}, + "dy": {"field": "height", "mult": 0.5}, + "font": {"value": "Helvetica Neue"}, + "fontSize": {"scale": "size", "field": "depth"}, + "align": {"value": "center"}, + "baseline": {"value": "middle"}, + "fill": {"value": "#000"}, + "fillOpacity": {"scale": "opacity", "field": "depth"}, + "text": {"field": "data.name"} + } + } + } + ] + }, + { + "width": 250, + "height": 200, + "data": [ + { + "name": "weather", + "url": "data/weather.json" + } + ], + "scales": [ + { + "name": "x", + "type": "ordinal", + "range": "width", + "padding": 0.1, "round": true, + "domain": {"data": "weather", "field": "index"} + }, + { + "name": "y", + "range": "height", + "nice": true, "zero": false, "round": true, + "domain": { + "data": "weather", + "field": ["data.record.low", "data.record.high"] + } + } + ], + "axes": [ + { "type": "y", "scale": "y", "ticks": 3, "tickSize": 0, + "orient": "right", "grid": true, + "properties": { + "grid": {"stroke": {"value": "white"}, "strokeWidth": {"value": 2}}, + "axis": {"stroke": {"value": "transparent"}} + } + } + ], + "marks": [ + { + "type": "text", + "from": {"data": "weather"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "index"}, + "dx": {"scale": "x", "band": true, "mult": 0.5}, + "y": {"value": 0}, + "fill": {"value": "#000"}, + "text": {"field": "data.day"}, + "align": {"value": "center"}, + "baseline": {"value": "bottom"} + } + } + }, + { + "type": "rect", + "from": {"data": "weather"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "index"}, + "width": {"scale": "x", "band": true, "offset": -1}, + "y": {"scale": "y", "field": "data.record.low"}, + "y2": {"scale": "y", "field": "data.record.high"}, + "fill": {"value": "#ccc"} + } + } + }, + { + "type": "rect", + "from": {"data": "weather"}, + "properties": { + "enter": { + "x": {"scale": "x", "field": "index"}, + "width": {"scale": "x", "band": true, "offset": -1}, + "y": {"scale": "y", "field": "data.normal.low"}, + "y2": {"scale": "y", "field": "data.normal.high"}, + "fill": {"value": "#999"} + } + } + }, + { + "type": "rect", + "from": { + "data": "weather", + "transform": [{"type":"filter", "test":"d.data.actual"}] + }, + "properties": { + "enter": { + "x": {"scale": "x", "field": "index", "offset": 4}, + "width": {"scale": "x", "band": true, "offset": -8}, + "y": {"scale": "y", "field": "data.actual.low"}, + "y2": {"scale": "y", "field": "data.actual.high"}, + "fill": {"value": "#000"} + } + } + }, + { + "type": "rect", + "from": { + "data": "weather", + "transform": [{"type":"filter", "test":"d.data.forecast"}] + }, + "properties": { + "enter": { + "x": {"scale": "x", "field": "index", "offset": 9}, + "width": {"scale": "x", "band": true, "offset": -18}, + "y": {"scale": "y", "field": "data.forecast.low.low"}, + "y2": {"scale": "y", "field": "data.forecast.high.high"}, + "fill": {"value": "#000"} + } + } + }, + { + "type": "rect", + "from": { + "data": "weather", + "transform": [{"type":"filter", "test":"d.data.forecast"}] + }, + "properties": { + "enter": { + "x": {"scale": "x", "field": "index", "offset": 4}, + "width": {"scale": "x", "band": true, "offset": -8}, + "y": {"scale": "y", "field": "data.forecast.low.low"}, + "y2": {"scale": "y", "field": "data.forecast.low.high"}, + "fill": {"value": "#000"} + } + } + }, + { + "type": "rect", + "from": { + "data": "weather", + "transform": [{"type":"filter", "test":"d.data.forecast"}] + }, + "properties": { + "enter": { + "x": {"scale": "x", "field": "index", "offset": 4}, + "width": {"scale": "x", "band": true, "offset": -8}, + "y": {"scale": "y", "field": "data.forecast.high.low"}, + "y2": {"scale": "y", "field": "data.forecast.high.high"}, + "fill": {"value": "#000"} + } + } + } + ] + }, + { + "name": "wordcloud", + "width": 400, + "height": 400, + "padding": {"top":0, "bottom":0, "left":0, "right":0}, + "data": [ + { + "name": "table", + "values": [ + {"text": "poem", "value": 80}, + {"text": "peom", "value": 44}, + {"text": "moep", "value": 40}, + {"text": "meop", "value": 36}, + {"text": "emop", "value": 32}, + {"text": "epom", "value": 28}, + {"text": "opem", "value": 24}, + {"text": "omep", "value": 20}, + {"text": "mope", "value": 56}, + {"text": "mepo", "value": 12}, + {"text": "pemo", "value": 10}, + {"text": "pome", "value": 10} + ], + "transform": [ + { + "type": "wordcloud", + "text": "data.text", + "font": "Helvetica Neue", + "fontSize": "data.value", + "rotate": {"random": [-60,-30,0,30,60]} + } + ] + } + ], + "marks": [ + { + "type": "text", + "from": {"data": "table"}, + "properties": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "angle": {"field": "angle"}, + "align": {"value": "center"}, + "baseline": {"value": "alphabetic"}, + "font": {"field": "font"}, + "fontSize": {"field": "fontSize"}, + "text": {"field": "data.text"} + }, + "update": { + "fill": {"value": "steelblue"} + }, + "hover": { + "fill": {"value": "#f00"} + } + } + } + ] + } +]; + +specs.forEach(spec => { + vg.parse.spec(spec, chart => { + chart({el:"#vis"}).update(); + }); +}); \ No newline at end of file diff --git a/vega/vega.d.ts b/vega/vega.d.ts new file mode 100644 index 0000000000..29ed1ba15c --- /dev/null +++ b/vega/vega.d.ts @@ -0,0 +1,336 @@ +// Type definitions for Vega +// Project: http://trifacta.github.io/vega/ +// Definitions by: Tom Crockett +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Vega { + export interface VG { + parse: Parse; + } + + export interface Parse { + spec(url: string, callback: (chart: (args: ViewArgs) => View) => void): void; + spec(spec: Spec, callback: (chart: (args: ViewArgs) => View) => void): void; + data(dataSet: Vega.Data[], callback: () => void): void; + // TODO all the other stuff + } + + export interface ViewArgs { + // TODO docs + el: any; + data?: any; + hover?: boolean; + renderer?: string; + } + + export interface View { + // TODO docs + width(): number; + width(w: number): View; + + height(): number; + height(h: number): View; + + padding(): Padding; + padding(p: Padding): View; + + viewport(): number[]; + viewport(v: number[]): View; + + renderer(r: string): View; + + data(): any; + data(d: any): View; + + initialize(i: any): View; + + render(r?: any[]): View; + + update(options?: UpdateOptions): View; + } + + export interface Padding { + // TODO docs + top: number; + right: number; + bottom: number; + left: number; + } + + export interface UpdateOptions { + // TODO docs + props?: string; + items?: any; + duration?: number; + ease?: string; + } + + export interface Spec { + /** + * A unique name for the visualization specification. + */ + name?: string; + /** + * The total width, in pixels, of the data rectangle. Default is 500 if + * undefined. + */ + width?: number; + /** + * The total height, in pixels, of the data rectangle. Default is 500 if + * undefined. + */ + height?: number; + /** + * The width and height of the on-screen viewport, in pixels. If necessary, + * clipping and scrolling will be applied. + */ + viewport?: number[]; + /** + * [Number | Object | String] + * The internal padding, in pixels, from the edge of the visualization + * canvas to the data rectangle. If an object is provided, it must include + * {top, left, right, bottom} properties. Two string values are also + * acceptable: "auto" (the default) and "strict". Auto-padding computes the + * padding dynamically based on the contents of the visualization. All + * marks, including axes and legends, are used to compute the necessary + * padding. "Strict" auto-padding attempts to adjust the padding such that + * the overall width and height of the visualization is unchanged. This mode + * can cause the visualization's width and height parameters to be adjusted + * such that the total size, including padding, remains constant. Note that + * in some cases strict padding is not possible; for example, if the axis + * labels are much larger than the data rectangle. + */ + padding?: any; + /** + * Definitions of data to visualize. + */ + data: Data[]; + /** + * Scale transform definitions. + */ + scales?: Scale[]; + /** + * Axis definitions. + */ + axes?: Axis[]; + /** + * Legend definitions. + */ + legends?: Legend[]; + /** + * Graphical mark definitions. + */ + marks: Mark[]; + } + + export interface Data { + /** + * A unique name for the data set. + */ + name: string; + /** + * An object that specifies the format for the data file, if loaded from a + * URL. + */ + format?: Data.Format; + /** + * The actual data set to use. The values property allows data to be inlined + * directly within the specification itself. + */ + values?: any; + /** + * The name of another data set to use as the source for this data set. The + * source property is particularly useful in combination with a transform + * pipeline to derive new data. + */ + source?: string; + /** + * A URL from which to load the data set. Use the format property to ensure + * the loaded data is correctly parsed. If the format property is not specified, + * the data is assumed to be in a row-oriented JSON format. + */ + url?: string; + /** + * An array of transforms to perform on the data. Transform operators will be + * run on the default data, as provided by late-binding or as specified by the + * source, values, or url properties. + */ + transform?: Data.Transform[]; + } + + export module Data { + export interface Format { + /** + * The currently supported format types are json (JavaScript Object + * Notation), csv (comma-separated values), tsv (tab-separated values), + * topojson, and treejson. + */ + type?: string; + // TODO: fields for specific formats + } + + export interface Transform { + // TODO + } + } + + export interface Scale { + // TODO docs + + // -- Common scale properties + name?: string; + type?: string; + domain?: any; + domainMin?: any; + domainMax?: any; + range?: any; + rangeMin?: any; + rangeMax?: any; + reverse?: boolean; + round?: boolean; + + // -- Ordinal scale properties + points?: boolean; + padding?: number; + sort?: boolean; + + // -- Time/Quantitative scale properties + clamp?: boolean; + nice?: any; // boolean for quantitative scales, string for time scales + + // -- Quantitative scale properties + exponent?: number; + zero?: boolean; + } + + export interface Axis { + // TODO docs + type: string; + scale: string; + orient?: string; + title?: string; + titleOffset?: number; + format?: string; + ticks?: number; + values?: any[]; + subdivide?: number; + tickPadding?: number; + tickSize?: number; + tickSizeMajor?: number; + tickSizeMinor?: number; + tickSizeEnd?: number; + offset?: any; + layer?: string; + grid?: boolean; + properties?: Axis.Properties + } + + export module Axis { + export interface Properties { + majorTicks?: Mark.PropertySet; + minorTicks?: Mark.PropertySet; + grid?: Mark.PropertySet; + labels?: Mark.PropertySet; + title?: Mark.PropertySet; + axis?: Mark.PropertySet; + } + } + + export interface Legend { + // TODO + } + + export interface Mark { + // TODO docs + type: string; + name?: string; + description?: string; + from?: Mark.From; + properties?: Mark.PropertySets; + key?: string; + delay?: Mark.ValueRef; + } + + export module Mark { + export interface From { + // TODO docs + data?: string; + transform?: Data.Transform[]; + } + + export interface PropertySets { + // TODO docs + enter?: PropertySet; + exit?: PropertySet; + update?: PropertySet; + hover?: PropertySet; + } + + export interface PropertySet { + // TODO docs + + // -- Shared visual properties + x?: ValueRef; + x2?: ValueRef; + width?: ValueRef; + y?: ValueRef; + y2?: ValueRef; + height?: ValueRef; + opacity?: ValueRef; + fill?: ValueRef; + fillOpacity?: ValueRef; + stroke?: ValueRef; + strokeWidth?: ValueRef; + strokeOpacity?: ValueRef; + strokeDash?: ValueRef; + strokeDashOffset?: ValueRef; + + // -- symbol + size?: ValueRef; + shape?: ValueRef; + + // -- path + path?: ValueRef; + + // -- arc + innerRadius?: ValueRef; + outerRadius?: ValueRef; + startAngle?: ValueRef; + endAngle?: ValueRef; + + // -- area / line + interpolate?: ValueRef; + tension?: ValueRef; + + // -- image / text + align?: ValueRef; + baseline?: ValueRef; + + // -- image + url?: ValueRef; + + // -- text + text?: ValueRef; + dx?: ValueRef; + dy?: ValueRef; + angle?: ValueRef; + font?: ValueRef; + fontSize?: ValueRef; + fontWeight?: ValueRef; + fontStyle?: ValueRef; + } + + export interface ValueRef { + // TODO docs + value?: any; + field?: any; + group?: any; + scale?: any; + mult?: number; + offset?: number; + band?: boolean; + } + } +} + +declare var vg: Vega.VG; \ No newline at end of file diff --git a/videojs/videojs.d.ts b/videojs/videojs.d.ts index 07f080acc2..1c53eefaf9 100644 --- a/videojs/videojs.d.ts +++ b/videojs/videojs.d.ts @@ -1,9 +1,10 @@ // Type definitions for Video.js -// The Video.js API allows you to interact with the video through Javascript, whether the browser is playing the video through HTML5 video, Flash, or any other supported playback technologies. // Project: https://github.com/zencoder/video-js // Definitions by: Vincent Bortone // Definitions: https://github.com/borisyankov/DefinitelyTyped +// The Video.js API allows you to interact with the video through Javascript, whether the browser is playing the video through HTML5 video, Flash, or any other supported playback technologies. + interface VideoJSOptions { techOrder?: string[]; html5?: Object; diff --git a/webaudioapi/waa-20120802.d.ts b/webaudioapi/waa-20120802.d.ts index 489cd4efb2..64dc658764 100644 --- a/webaudioapi/waa-20120802.d.ts +++ b/webaudioapi/waa-20120802.d.ts @@ -1,8 +1,11 @@ -// Type definitions for the Web Audio API, currently only implemented in WebKit browsers -// Conforms to the: http://www.w3.org/TR/2012/WD-webaudio-20120802/ specification +// Type definitions for Web Audio API +// Project: http://www.w3.org/TR/2012/WD-webaudio-20120802/ // Definitions by: Baruch Berger (https://github.com/bbss) // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Conforms to the: http://www.w3.org/TR/2012/WD-webaudio-20120802/ specification +// Currently only implemented in WebKit browsers + interface webkitAudioContext { destination: AudioDestinationNode; sampleRate: number; diff --git a/webaudioapi/waa-nightly.d.ts b/webaudioapi/waa-nightly.d.ts index b6181e2444..79566f9396 100644 --- a/webaudioapi/waa-nightly.d.ts +++ b/webaudioapi/waa-nightly.d.ts @@ -1,8 +1,11 @@ -// Type definitions for the Web Audio API, currently only implemented in WebKit browsers (nightly builds) -// Conforms to the: https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html specification +// Type definitions for Web Audio API (nightly) +// Project: http://www.w3.org/TR/2012/WD-webaudio-20120802/ // Definitions by: Baruch Berger (https://github.com/bbss) // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Conforms to the: http://www.w3.org/TR/2012/WD-webaudio-20120802/ specification +// Currently only implemented in WebKit browsers (nightly builds) + interface webkitAudioContext { destination: AudioDestinationNode; @@ -247,4 +250,4 @@ interface MediaStreamAudioSourceNode extends AudioSourceNode { interface MediaStream { -} \ No newline at end of file +} diff --git a/webaudioapi/waa.d.ts b/webaudioapi/waa.d.ts index 6d85293549..cd53babc0c 100644 --- a/webaudioapi/waa.d.ts +++ b/webaudioapi/waa.d.ts @@ -1,6 +1,6 @@ -// Type definitions for the Web Audio API +// Type definitions for Web Audio API // Project: http://www.w3.org/TR/2012/WD-webaudio-20121213/ -// Definitions by: Baruch Berger (https://github.com/bbss), Kon (http://phyzkit.net/) +// Definitions by: Baruch Berger , Kon // Definitions: https://github.com/borisyankov/DefinitelyTyped /** diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index b1316091a0..ddf2200be3 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -1,4 +1,9 @@ -// Type definitions take from http://dev.w3.org/2011/webrtc/editor/getusermedia.html +// Type definitions for WebRTC +// Project: http://dev.w3.org/2011/webrtc/ +// Definitions by: Ken Smith +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html interface MediaStreamConstraints { audio: boolean; @@ -133,4 +138,4 @@ declare var webkitURL: { prototype: WebkitURL; new (): streamURL; createObjectURL(stream: MediaStream): string; -} \ No newline at end of file +} diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index e07e3a4173..d66ad6cf0f 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -1,10 +1,11 @@ -/// +// Type definitions for WebRTC +// Project: http://dev.w3.org/2011/webrtc/ +// Definitions by: Ken Smith +// Definitions: https://github.com/borisyankov/DefinitelyTyped -// These are TypeScript definitions to support static typing in TypeScript when interacting with WebRtc. // Definitions taken from http://dev.w3.org/2011/webrtc/editor/webrtc.html -// These are TypeScript definitions to support static typing in TypeScript when interacting with WebRtc. -// Definitions taken from http://dev.w3.org/2011/webrtc/editor/webrtc.html +/// interface RTCConfiguration { iceServers: RTCIceServer[]; diff --git a/when/when.d.ts b/when/when.d.ts index dbf4050a0f..859618852a 100644 --- a/when/when.d.ts +++ b/when/when.d.ts @@ -1,5 +1,6 @@ // Type definitions for When 2.4.0 // Project: https://github.com/cujojs/when +// Definitions by: Derek Cicerone // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module When { @@ -55,11 +56,25 @@ declare module When { } interface Promise { + catch(onRejected?: (reason: any) => Promise): Promise; + catch(onRejected?: (reason: any) => U): Promise; + ensure(onFulfilledOrRejected: Function): Promise; + inspect(): Snapshot; + + otherwise(onRejected?: (reason: any) => Promise): Promise; + otherwise(onRejected?: (reason: any) => U): Promise; + then(onFulfilled: (value: T) => Promise, onRejected?: (reason: any) => Promise, onProgress?: (update: any) => void): Promise; then(onFulfilled: (value: T) => Promise, onRejected?: (reason: any) => U, onProgress?: (update: any) => void): Promise; then(onFulfilled: (value: T) => U, onRejected?: (reason: any) => Promise, onProgress?: (update: any) => void): Promise; then(onFulfilled: (value: T) => U, onRejected?: (reason: any) => U, onProgress?: (update: any) => void): Promise; } + + interface Snapshot { + state: string; + value?: T; + reason?: any; + } } diff --git a/winjs/winjs.d.ts b/winjs/winjs.d.ts index 99a5e33c2b..cdc3d27fa5 100644 --- a/winjs/winjs.d.ts +++ b/winjs/winjs.d.ts @@ -1,3 +1,8 @@ +// Type definitions for WinJS +// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /* ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use @@ -15,321 +20,8583 @@ and limitations under the License. /// -declare module WinJS { - function strictProcessing(): void; - - export module Application { - export var onsettings: EventListener; - } - - module Binding { - function as(data: any): any; - function processAll(rootElement?: any, dataContext?: any, skipRoot?: boolean, bindingCache?: any): any; - function define(data: any): any; - function expandProperties(data: any): any; - function converter(method: any): any; - - export var optimizeBindingReferences: boolean; - export var mixin: any; - export var bind: any; - export var oneTime: any; - - export function initializer(customInit: any): any; - export var setAttribute: any; - - class List { - constructor(data?: T[], options?: { binding: boolean; proxy: boolean; }); - public push(item: T): number; - public indexOf(item: T, fromIndex?: number): number; - public splice(start: number, howMany?: number, ...items: T[]): T[]; - public createFiltered(predicate: (x: T) => boolean): List; - public createGrouped(keySelector: (x: T) => string, dataSelector: (x:T) => U, groupSorter?: (left:string, right:string) => number): List; - public createSorted(sorter: (left:T, right:T) => number): List; - public groups: List; - public dataSource: any; - public getAt(index: number): T; - public forEach(callback: (val: T, index: number, array: T[]) => void, thisArg?: any): void; - public every(callback: (val: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - public join(separator: string): string; - public map(callback: (val: T, index: number, array: T[]) => U, thisArg?: any): U[]; - public move(index: number, newIndex: number): void; - public pop(): T; - public reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue?: any): any; - public reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue?: any): any; - public reverse(): void; - public setAt(index: number, newValue: T): void; - public shift(): T; - public slice(begin: number, end: number): List; - public some(callback: (val: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - public sort(sortFunction: (left: T, right: T) => number): void; - public filter(callback: (val: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; - public unshift(value: T): number; - public length: number; - public notifyMutated(index: number): void; - } - class Template { - public element: HTMLElement; - public extractChild: boolean; - public processTimeout: number; - public debugBreakOnRender: boolean; - public disableOptimizedProcessing: boolean; - public isDeclarativeControlContainer: boolean; - public bindingInitializer: any; - - constructor(element: HTMLElement, options?: any); - public render: { - (dataContext: any, container?: HTMLElement): WinJS.Promise; - value(href: string, dataContext: any, container?: HTMLElement): WinJS.Promise; - }; - public renderItem(item: any, recycled?: HTMLElement): void; - } - - - } - module Namespace { - var define: any; - var defineWithParent: any; - } - module Class { - function define(constructor: any, instanceMembers: any): any; - function derive(baseClass: any, constructor: any, instanceMembers: any): any; - function mix(constructor: any, ...mixin: any[]): any; - } - function xhr(options: { type?: string; url?: string; user?: string; password?: string; headers?: any; data?: any; responseType?: string; }): WinJS.Promise; - module Application { - interface IOHelper { - exists(filename: string): boolean; - readText(fileName: string, def: string): WinJS.Promise; - readText(fileName: string): WinJS.Promise; - writeText(fileName: string, text: string): WinJS.Promise; - remove(fileName: string): WinJS.Promise; - } - var local: IOHelper; - var roaming: IOHelper; - var onactivated: EventListener; - var sessionState: any; - interface ApplicationActivationEvent extends Event { - detail: any; - setPromise(p: Promise): any; - } - function addEventListener(type: string, listener: EventListener, capture?: boolean): void; - var oncheckpoint: EventListener; - function start(): void; - function stop(): void; - } - class ErrorFromName { - constructor(name: string, message?: string); - } - class Promise implements Windows.Foundation.IPromise { - constructor(init: (c: any, e: any, p: any) => void); - then(success?: (value: T) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void): Windows.Foundation.IPromise; - then(success?: (value: T) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void): Windows.Foundation.IPromise; - then(success?: (value: T) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void): Windows.Foundation.IPromise; - then(success?: (value: T) => U, error?: (error: any) => U, progress?: (progress: any) => void): Windows.Foundation.IPromise; - done(success?: (value: T) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - - cancel(): void; - - static join(values: any[]): Promise; - static timeout(timeout: number): Promise; - static as(): Promise; - static as(obj: U): Promise; - static wrapError(obj: U): Promise; - } - module Navigation { - var history: any; - var canGoBack: boolean; - var canGoForward: boolean; - var location: string; - var state: any; - function addEventListener(type: string, listener: EventListener, capture: boolean): void; - function back(): void; - function forward(): void; - function navigate(location: any, initialState: any): WinJS.Promise; - function navigate(location: any): WinJS.Promise; - function removeEventListener(type: string, listener: EventListener, capture: boolean): void; - var onbeforenavigate: CustomEvent; - var onnavigated: CustomEvent; - var onnavigating: CustomEvent; - } - - export module Resources { - export var processAll: (element?: HTMLElement) => void; - export var getString: (id: string) => { value: string; empty?: boolean; lang?: string; }; - export var addEventListener: (id: string, handler: EventListener, useCapture?: boolean) => void; - } - - module Utilities { - function markSupportedForProcessing(obj: T): T; - function createEventProperties(...events: string[]): any; - - export function addClass(element: HTMLElement, className: string): void; - export function removeClass(element: HTMLElement, className: string): void; - - export function hasClass(element: HTMLElement, className: string): boolean; - - enum Key { - backspace, - tab, - enter, - shift, - ctrl, - alt, - pause, - capsLock, - escape, - space, - pageUp, - pageDown, - end, - home, - leftArrow, - upArrow, - rightArrow, - downArrow, - insert, - deleteKey, - num0, - num1, - num2, - num3, - num4, - num5, - num6, - num7, - num8, - num9, - a, - b, - c, - d, - e, - f, - g, - h, - i, - j, - k, - l, - m, - n, - o, - p, - q, - r, - s, - t, - u, - v, - w, - x, - y, - z, - leftWindows, - rightWindows, - numPad0, - numPad1, - numPad2, - numPad3, - numPad4, - numPad5, - numPad6, - numPad7, - numPad8, - numPad9, - multiply, - add, - subtract, - decimalPoint, - divide, - f1, - f2, - f3, - f4, - f5, - f6, - f7, - f8, - f9, - f10, - f11, - f12, - numLock, - scrollLock, - semicolon, - equal, - comma, - dash, - period, - forwardSlash, - graveAccent, - openBracket, - backSlash, - closeBracket, - singleQuote - } - } - module UI { - var process: any; - var processAll: any; - var ListLayout: any; - var GridLayout: any; - var Pages: any; - var setOptions: any; - - export var Animation: any; - - var DOMEventMixin: any; - - class Flyout { - constructor(element: HTMLElement, options: any); - element: Element; - } - - module Fragments { - var renderCopy: any; - } - - export class HtmlControl { - constructor(element: HTMLElement, options: { uri: string; }); - } - - interface IItem { - data: any; - } - - interface ISelection { - clear(): WinJS.Promise; - count(): number; - getItems(): WinJS.Promise; - } - - class ListView { - element: Element; - elementFromIndex(index: number): Element; - indexOfElement(element: Element): number; - selection: ISelection; - } - - class Menu { - constructor(element: HTMLElement, options: any); - element: Element; - } - - export class MenuCommand { - constructor(element: HTMLElement, options: any); - } - - export class SettingsFlyout { - static populateSettings(e: any): any; - static showSettings(id: string, path: any): any; - } - } - - export function xhr(options: { type: string; url: string; }): WinJS.Promise; // user: string; password: string; headers: any; data: any; responseType: string; -} - +/** + * Defines an Element object. +**/ interface Element { - winControl: any; // TODO: This should be control? -} + winControl: any; // TODO: This should be control? +}/** + * Provides application-level functionality, for example activation, storage, and application events. +**/ +declare module WinJS.Application { + //#region Objects + /** + * The local storage of the application. + **/ + var local: { + //#region Methods + + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): Promise; + + //#endregion Methods + + }; + + /** + * The roaming storage of the application. + **/ + var roaming: { + //#region Methods + + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): Promise; + + //#endregion Methods + + }; + + /** + * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. + **/ + var sessionState: any; + + /** + * The temp storage of the application. + **/ + var temp: { + //#region Methods + + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The text to write. + * @returns A Promise that completes with the number of bytes successfully written to the file. + **/ + writeText(fileName: string, text: string): Promise; + + //#endregion Methods + + }; + + //#endregion Objects + + //#region Methods + + /** + * Informs the application object that asynchronous work is being performed, and that this event handler should not be considered complete until the promise completes. This function can be set inside the handlers for all WinJS.Application events: onactivated oncheckpoint onerror onloaded onready onsettings onunload. + * @param promise The promise that should complete before processing is complete. + **/ + function setPromise(promise: Promise): void; + + //#endregion Methods + + //#region Functions + + /** + * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. + * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + function addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Queues a checkpoint event. + **/ + function checkpoint(): void; + + /** + * Queues an event to be processed by the WinJS.Application event queue. + * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. + **/ + function queueEvent(eventRecord: any): void; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: any): void; + + /** + * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). + **/ + function start(): void; + + /** + * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. + **/ + function stop(): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. + * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. + **/ + function onactivated(eventInfo: CustomEvent): void; + + /** + * Occurs when receiving PLM notification or when the checkpoint function is called. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function oncheckpoint(eventInfo: CustomEvent): void; + + /** + * Occurs when an unhandled error has been raised. + * @param eventInfo An object that contains information about the event. + **/ + function onerror(eventInfo: CustomEvent): void; + + /** + * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function onloaded(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is ready. This event occurs after the loaded event and the activated event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onready(eventInfo: CustomEvent): void; + + /** + * Occurs when the settings charm is invoked. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. + **/ + function onsettings(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is about to be unloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onunload(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functionality for data and template binding. +**/ +declare module WinJS.Binding { + //#region Properties + + /** + * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. + **/ + var optimizeBindingReferences: boolean; + + //#endregion Properties + + //#region Objects + + /** + * Allows you to add bindable properties dynamically. + **/ + var dynamicObservableMixin: { + //#region Methods + + /** + * Adds a property with change notification to this object, including a ECMAScript5 property definition. + * @param name The name of the property to add. + * @param value This object is returned. + **/ + addProperty(name: string, value: any): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Do not instantiate. A list returned by the createFiltered method. + **/ + class FilteredListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. A list of groups. + **/ + class GroupsListProjection extends ListBase { + //#region Methods + + /** + * Gets a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. + **/ + class GroupedSortedListProjection extends SortedListProjection { + //#region Properties + + /** + * Gets a List, which is a projection of the groups that were identified in this list. + **/ + groups: GroupsListProjection; + + //#endregion Properties + + } + + /** + * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. + **/ + class List extends ListBaseWithMutators { + //#region Constructors + + /** + * Creates a List object. + * @constructor + * @param list The array containing the elements to initalize the list. + * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. + **/ + constructor(list?: T[], options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Gets a key/data pair for the specified list index. + * @param index The index of value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the list item key specified. + * @param key The key of the value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Gets the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Moves the value at index to the specified position. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. + **/ + reverse(): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + /** + * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. + * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + **/ + sort(sortFunction: (left: T, right: T) => number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Represents a base class for lists. + **/ + class ListBase { + //#region Events + + /** + * An item in the list has changed its value. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * A new item has been inserted into the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * An item has been changed locations in the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * An item has been mutated. This event occurs as a result of calling the notifyMutated method. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmutated(eventInfo: CustomEvent): void; + + /** + * An item has been removed from the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * The list has been refreshed. Any references to items in the list may be incorrect. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. + **/ + onreload(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Returns a new list consisting of a combination of two arrays. + * @param item Additional items to add to the end of the list. + * @returns An array containing the concatenation of the list and any other supplied items. + **/ + concat(...item: T[]): T[]; + + /** + * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. + * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A filtered projection over the list. + **/ + createFiltered(predicate: (x: T) => boolean): FilteredListProjection; + + /** + * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. + * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. + * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). + * @returns A grouped projection over the list. + **/ + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + + /** + * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. + * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A sorted projection over the list. + **/ + createSorted(sorter: (left: T, right: T) => number): SortedListProjection; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Checks whether the specified callback function returns true for all elements in a list. + * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if the callback returns true for all elements in the list. + **/ + every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Returns the elements of a list that meet the condition specified in a callback function. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the elements that meet the condition specified in the callback function. + **/ + filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + + /** + * Calls the specified callback function for each element in a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + **/ + forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Gets the value at the specified index. + * @param index The index of the value to get. + * @returns The value at the specified index. + **/ + getAt(index: number): T; + + /** + * Gets the index of the first occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + * @returns The index of the first occurrence of a value in a list or -1 if not found. + **/ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns a string consisting of all the elements of a list separated by the specified separator string. + * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. + * @returns The elements of a list separated by the specified separator string. + **/ + join(separator: string): string; + + /** + * Gets the index of the last occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. + * @returns The index of the last occurrence of a value in a list, or -1 if not found. + **/ + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** + * Calls the specified callback function on each element of a list, and returns an array that contains the results. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. + * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the result of calling the callback function on each element in the list. + **/ + map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Forces the list to send a reload notification to any listeners. + **/ + notifyReload(): void; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. + * @returns The return value from the last call to the callback function. + **/ + reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. + * @returns The return value from the last call to callback function. + **/ + reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Extracts a section of a list and returns a new list. + * @param begin The index that specifies the beginning of the section. + * @param end The index that specifies the end of the section. + * @returns Returns a section of list. + **/ + slice(begin: number, end: number): T[]; + + /** + * Checks whether the specified callback function returns true for any element of a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if callback returns true for any element in the list. + **/ + some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + //#region Properties + + /** + * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. + **/ + dataSource: WinJS.UI.IListDataSource; + + /** + * Indicates that the object is compatibile with declarative processing. + **/ + static supportedForProcessing: boolean; + + //#endregion Properties + } + + /** + * Represents a base class for normal list modifying operations. + **/ + class ListBaseWithMutators extends ListBase { + //#region Methods + + /** + * Removes the last element from a list and returns it. + * @returns The last element from the list. + **/ + pop(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the end of the list. + * @returns The new length of the list. + **/ + push(value: T): number; + + /** + * Removes the first element from a list and returns it. + * @returns The first element from the list. + **/ + shift(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the start of the list. + * @returns The new length of the list. + **/ + unshift(value: T): number; + + //#endregion Methods + } + + /** + * Represents a base class for list projections. + **/ + class ListProjection extends ListBaseWithMutators { + //#region Methods + + /** + * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) + **/ + dispose(): void; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Moves the value at index to position newIndex. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + } + + /** + * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. + **/ + var mixin: { + //#region Methods + + /** + * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . + * @param name The name of the property to add. + * @param value The value of the property. + * @returns This object is returned. + **/ + addProperty(name: string, value: any): any; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Provides functions that can make an object observable. + **/ + var observableMixin: { + //#region Methods + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + }; + + /** + * Do not instantiate. Returned by the createSorted method. + **/ + class SortedListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value to be replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Provides a reusable declarative binding element. + **/ + class Template { + //#region Constructors + + /** + * Creates a template that provides a reusable declarative binding element. + * @constructor + * @param element The DOM element to convert to a template. + * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. + **/ + constructor(element: HTMLElement, options?: string); + + //#endregion Constructors + + //#region Methods + + render: { + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + (dataContext: any, container?: HTMLElement): Promise; + + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + value(href: string, dataContext: any, container?: HTMLElement): Promise; + }; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default binding initializer for the template. + **/ + bindingInitializer: any; + + /** + * Gets or sets a value that specifies whether a debug break is inserted into the first rendering of each template. This property only has an effect when the app is in debug mode. + **/ + debugBreakOnRender: boolean; + + /** + * This property is deprecated and might not be available in future versions of the WinJS. Gets or sets a value that specifies whether optimized template processing has been disabled. + **/ + disableOptimizedProcessing: boolean; + + /** + * Gets the DOM element that is used as the template. + **/ + element: HTMLElement; + + /** + * Gets a value that specifies whether templates should be instantiated without the creation of an additional child element. + **/ + extractChild: boolean; + + /** + * Determines whether the Template contains declarative controls that must be processed separately. This property is always true. The controls that belong to a Template object's children are instantiated when a Template instance is rendered. + **/ + isDeclarativeControlContainer: boolean; + + //#endregion Properties + + } + + //#endregion Objects + + //#region Functions + + /** + * Adds a CSS class from the specified path of the source object to a destination object. + * @param source The source object that has the class to copy. + * @param sourceProperties The path on the source object to the source class. + * @param dest The destination object. + **/ + function addClassOneTime(source: any, sourceProperties: any[], dest: HTMLElement): void; + + /** + * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. + * @param data The object to observe. + * @returns The observable object. + **/ + function as(data: U): U; + + /** + * Binds to one or more properties on the observable object or or on child values of that object. + * @param observable The object to bind to. + * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. + * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. + **/ + function bind(observable: any, bindingDescriptor: any): any; + + /** + * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. + * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. + * @returns The binding initializer. + **/ + function converter(convert: Function): Function; + + /** + * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Creates a new constructor function that supports observability with the specified set of properties. + * @param data The object to use as the pattern for defining the set of properties. + * @returns A constructor function with 1 optional argument that is the initial state of the properties. + **/ + function define(data: any): Function; + + /** + * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. + * @param shape The specification for the bindable object. + * @returns An object with a set of properties all of which are wired for binding. + **/ + function expandProperties(shape: any): any; + + /** + * Marks a custom initializer function as being compatible with declarative data binding. + * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. + * @returns The input customInitializer. + **/ + function initializer(customInitializer: Function): Function; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + function notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Sets the destination property to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. + * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. + * @param dataContext The object that contains the values to which the DOM element should be bound. + * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. + * @param bindingCache The cached binding data. + * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. + * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. + **/ + function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; + + /** + * Creates a one-way binding between the source object and an attribute on the destination element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + * @returns An object with a cancel() method that is used to coalesce bindings. + **/ + function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; + + /** + * Sets an attribute on the destination element to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + **/ + function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; + + /** + * Returns the original (non-observable) object is returned if the specified object is an observable proxy, + * @param data The object for which to retrieve the original value. + * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. + **/ + function unwrap(data: any): any; + + //#endregion Functions + + //#region Interfaces + + interface IKeyDataPair { + key: string; + data: T; + } + + //#endregion Interfaces + +} +/** + * Provides helper functions for defining Classes. +**/ +declare module WinJS.Class { + //#region Functions + + /** + * Defines a class using the given constructor and the specified instance members. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods made available on the type. + * @param staticMembers The set of static fields, properties, and methods made available on the type. + * @returns The newly-defined type. + **/ + function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. + * @param baseClass The type to inherit from. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. + * @param staticMembers The set of static fields, properties, and methods to be made available on the type. + * @returns The newly-defined type. + **/ + function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. + * @param constructor A constructor function that will be used to instantiate this class. + * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. + * @returns The newly defined class. + **/ + function mix(constructor: Function, ...mixin: any[]): any; + + //#endregion Functions + +} +/** + * The WinJS namespace provides special Windows Library for JavaScript functionality, including Promise and xhr. +**/ +declare module WinJS { + //#region Properties + + /** + * Can be set to show the results of a validation process. + **/ + var validation: boolean; + + //#endregion Properties + + //#region Objects + + /** + * An error object. + **/ + class ErrorFromName { + //#region Constructors + + /** + * Creates an Error object with the specified name and message properties. + * @constructor + * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. + * @param message The message for this error. The message is meant to be consumed by humans and should be localized. + **/ + constructor(name: string, message?: string); + + //#endregion Constructors + + } + + /** + * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + **/ + class Promise implements Windows.Foundation.IPromise { + //#region Constructors + + /** + * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + * @constructor + * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. + * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. + **/ + constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when there is an error in processing a promise. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener for the promise. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Returns a promise that is fulfilled when one of the input promises has been fulfilled. + * @param value An array that contains Promise objects or objects whose property values include Promise objects. + * @returns A promise that on fulfillment yields the value of the input (complete or error). + **/ + static any(value: Promise[]): Promise; + + /** + * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. + * @param value The value to be treated as a Promise. + * @returns The promise. + **/ + static as(value: U): Promise; + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Raises an event of the specified type and properties. + * @param type The type (name) of the event. + * @param details The set of additional properties to be attached to the event object. + * @returns true if preventDefault was called on the event; otherwise, false. + **/ + dispatchEvent(type: string, details: any): boolean; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + + /** + * Determines whether a value fulfills the promise contract. + * @param value A value that may be a promise. + * @returns true if the object conforms to the promise contract (has a then function), otherwise false. + **/ + static is(value: any): boolean; + + /** + * Creates a Promise that is fulfilled when all the values are fulfilled. + * @param values An object whose members contain values, some of which may be promises. + * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. + **/ + static join(values: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param capture Specifies whether or not to initiate capture. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Windows.Foundation.IPromise, onError?: (error: any) => Windows.Foundation.IPromise, onProgress?: (progress: any) => void): Windows.Foundation.IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Windows.Foundation.IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Windows.Foundation.IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => Windows.Foundation.IPromise, onProgress?: (progress: any) => void): Windows.Foundation.IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Windows.Foundation.IPromise; + + /** + * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. + * @param values A set of values (which could be either an array or an object) of which some or all are promises.. + * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. + * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. + * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. + * @returns A Promise that is the result of calling join on the values parameter. + **/ + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + + /** + * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. + * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. + * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. + * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. + **/ + static timeout(timeout: number, promise?: Promise): Promise; + + /** + * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. + * @param value Some non-promise value to be wrapped in a promise. + * @returns A promise that is successfully fulfilled with the specified value. + **/ + static wrap(value: U): Promise; + + /** + * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. + * @param error A non-promise error value to be wrapped in a promise. + * @returns A promise that is in an error state with the specified value. + **/ + static wrapError(error: U): Promise; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. + * @param message The message to log. + * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). + * @param type The type of message (error, warning, info, etc.). + **/ + function log(message: string, tags: string, type: string): void; + + /** + * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. + **/ + function strictProcessing(): void; + + /** + * Wraps calls to XMLHttpRequest in a promise. + * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. + * @returns A promise that returns the XMLHttpRequest object when it completes. + **/ + function xhr(options: IXHROptions): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IXHROptions { + type?: string; + url: string; + user?: string; + password?: string; + headers?: any; + data: any; + responseType?: string; + } + + //#endregion Interfaces +} +/** + * Provides helper functions for defining namespaces. For more information, see Organizing your code with WinJS.Namespace. +**/ +declare module WinJS.Namespace { + //#region Functions + + /** + * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. + * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function define(name?: string, members?: any): any; + + /** + * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. + * @param parentNamespace The parent namespace. + * @param name The name of the new namespace. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; + + //#endregion Functions + +} +/** + * Provides functionality for dealing with basic navigation, including the navigation stack. +**/ +declare module WinJS.Navigation { + //#region Properties + + /** + * Determines whether it is possible to navigate backwards. + **/ + var canGoBack: boolean; + + /** + * Determines if it is possible to navigate forwards. + **/ + var canGoForward: boolean; + + /** + * Gets or sets the navigation history. + **/ + var history: any; + + /** + * Gets or sets the current location. + **/ + var location: string; + + /** + * Gets or sets a user-defined object that represents the state associated with the current location. + **/ + var state: any; + + //#endregion Properties + + //#region Functions + + /** + * Adds an event listener to the control. + * @param eventType The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + function addEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Navigates backwards. + * @param distance The number of entries to go back into the history. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function back(distance?: number): Promise; + + /** + * Navigates forwards. + * @param distance The number of entries to go forward. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function forward(distance?: number): Promise; + + /** + * Navigates to a location. + * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. + * @param initialState A user-defined object that represents the navigation state that may be accessed through state. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). + **/ + function navigate(location: any, initialState?: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs before navigation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onbeforenavigate(eventInfo: CustomEvent): void; + + /** + * Occurs after navigation has taken place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigated(eventInfo: CustomEvent): void; + + /** + * Occurs when navigation is taking place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigating(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functions for accessing resources and localizing content. +**/ +declare module WinJS.Resources { + //#region Functions + + /** + * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. + * @param type The name of the event to handle. + * @param listener The listener (event handler function) to associate with the event. + * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. + **/ + function addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The name of the event to raise. + * @param details The set of additional properties to attach to the event object. + **/ + function dispatchEvent(type: string, details: any): void; + + /** + * Retrieves the resource string that has the specified resource identifier. + * @param resourceId The resource ID of the string to retrieve. + * @returns An object that can contain these properties: value, empty, lang. + **/ + function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; + + /** + * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. + * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. + **/ + function processAll(rootElement?: HTMLElement): void; + + /** + * Removes an event listener that the addEventListener method registered. + * @param type The name of the event that the event listener is registered for. + * @param listener The listener (event handler function) to remove. + * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. + **/ + function oncontextchanged(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides access to the Windows animations. These functions provide developers with the ability to use animations in their custom controls that are consistent with animations used by Windows controls. +**/ +declare module WinJS.UI.Animation { + //#region Functions + + /** + * Creates an object that performs an animation that adds an item or items to a list. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that adds an item or items to a list of search results. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that collapses a list. + * @param hidden Element or elements hidden as a result of the collapse. + * @param affected Element or elements affected by the hidden items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list of search results. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that expands a list. + * @param revealed Element or elements revealed by the expansion. + * @param affected Element or elements affected by the newly revealed items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs a peek animation. + * @param element Element or elements involved in the peek. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createPeekAnimation(element: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that moves an item or items. + * @param element Element or elements involved in the reposition. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. + **/ + function createRepositionAnimation(element: any): IAnimationMethodResponse; + + /** + * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. + * @param incoming Element or elements being faded in. + * @param outgoing Element or elements being replaced. + * @returns An object that completes when the animation has finished. + **/ + function crossFade(incoming: any, outgoing: any): Promise; + + /** + * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. + * @param target Element or elements that the dragged object would cause to be moved if it were dropped. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenEnter(target: any, offset: any): Promise; + + /** + * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. + * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenLeave(target: any): Promise; + + /** + * Performs an animation when the user finishes dragging an object. + * @param dragSource Element or elements that were dragged. + * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + + /** + * Performs an animation when the user begins to drag an object. + * @param dragSource Element or elements being dragged. + * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceStart(dragSource: any, affected?: any): Promise; + + /** + * Performs an animation that displays one or more elements on a page. + * @param incoming Element or elements that compose the incoming content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function enterContent(incoming: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. + * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. + * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function enterPage(element: any, offset: any): Promise; + + /** + * Performs an animation that hides one or more elements on a page. + * @param outgoing Element or elements that compose the outgoing content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitContent(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that dismisses the current page when transitioning between pages in an app. + * @param outgoing Element or elements that compose the outgoing page. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitPage(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that fades an item or set of items into view. + * @param shown Element or elements being faded in. + * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. + **/ + function fadeIn(shown: any): Promise; + + /** + * Performs an animation that fades an item or set of items out of view. + * @param hidden Element or elements being faded out. + * @returns An object that completes when the animation is finished. + **/ + function fadeOut(hidden: any): Promise; + + /** + * Performs an animation that hides edge-based user interface (UI). + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function hideEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that hides a panel. + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function hidePanel(element: any, offset: any): Promise; + + /** + * Performs an animation that removes pop-up user interface (UI). + * @param element Element or elements that are being hidden. + * @returns An object that completes when the animation is finished. + **/ + function hidePopup(element: any): Promise; + + /** + * Performs an animation when a pointer is pressed on an object. + * @param element Element or elements on which the pointer is pressed. + * @returns An object that completes when the animation is finished. + **/ + function pointerDown(element: any): Promise; + + /** + * Performs an animation when a pointer is released. + * @param element Element or elements that the pointer was pressed on. + * @returns An object that completes when the animation is finished. + **/ + function pointerUp(element: any): Promise; + + /** + * Performs an animation that slides a narrow, edge-based user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function showEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that slides a large panel user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPanel(element: any, offset: any): Promise; + + /** + * Performs an animation that displays a pop-up user interface (UI). + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPopup(element: any, offset: any): Promise; + + /** + * Performs a deselection animation in response to a swipe interaction. + * @param deselected Element or elements that become unselected. + * @param selection Element or elements that represent the selection, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeDeselect(deselected: any, selection: any): Promise; + + /** + * Performs an animation that reveals an item or items in response to a swipe interaction. + * @param target Element or elements being revealed. + * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function swipeReveal(target: any, offset: any): Promise; + + /** + * Performs a selection animation in response to a swipe interaction. + * @param selected Element or elements being selected. + * @param selection Element or elements that show that something is selected, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeSelect(selected: any, selection: any): Promise; + + /** + * Performs an animation that updates a badge. + * @param incoming Element or elements that comprise the new badge. + * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function updateBadge(incoming: any, offset: any): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IAnimationMethodResponse { + execute(): Promise; + } + + //#endregion Interfaces + +} +/** + * Provides controls and objects that manipulate data. +**/ +declare module WinJS.UI { + //#region Enumerations + + /** + * Specifies an icon that appears in an AppBarCommand object. + **/ + enum AppBarIcon { + previous, + next, + play, + pause, + edit, + save, + clear, + delete, + remove, + add, + cancel, + accept, + more, + redo, + undo, + home, + up, + forward, + right, + back, + left, + favorite, + camera, + settings, + video, + sync, + download, + mail, + find, + help, + upload, + emoji, + twopage, + leavechat, + mailforward, + clock, + send, + crop, + rotatecamera, + people, + closepane, + openpane, + world, + flag, + previewlink, + globe, + trim, + attachcamera, + zoomin, + bookmarks, + document, + protecteddocument, + page, + bullets, + comment, + mail2, + contactinfo, + hangup, + viewall, + mappin, + phone, + videochat, + switch, + contact, + rename, + pin, + musicinfo, + go, + keyboard, + dockleft, + dockright, + dockbottom, + remote, + refresh, + rotate, + shuffle, + list, + shop, + selectall, + orientation, + import, + importall, + browsephotos, + webcam, + pictures, + savelocal, + caption, + stop, + showresults, + volume, + repair, + message, + page2, + calendarday, + calendarweek, + calendar, + characters, + mailreplyall, + read, + link, + accounts, + showbcc, + hidebcc, + cut, + attach, + paste, + filter, + copy, + emoji2, + important, + mailreply, + slideshow, + sort, + manage, + allapps, + disconnectdrive, + mapdrive, + newwindow, + openwith, + contactpresence, + priority, + uploadskydrive, + gototoday, + font, + fontcolor, + contact2, + folder, + audio, + placeholder, + view, + setlockscreen, + settile, + cc, + stopslideshow, + permissions, + highlight, + disableupdates, + unfavorite, + unpin, + openlocal, + mute, + italic, + underline, + bold, + movetofolder, + likedislike, + dislike, + like, + alignright, + aligncenter, + alignleft, + zoom, + zoomout, + openfile, + otheruser, + admin, + street, + map, + clearselection, + fontdecrease, + fontincrease, + fontsize, + cellphone, + reshare, + tag, + repeatone, + repeatall, + outlinestar, + solidstar, + calculator, + directions, + target, + library, + phonebook, + memo, + microphone, + postupdate, + backtowindow, + fullscreen, + newfolder, + calendarreply, + unsyncfolder, + reporthacked, + syncfolder, + blockcontact, + switchapps, + addfriend, + touchpointer, + gotostart, + zerobars, + onebar, + twobars, + threebars, + fourbars, + scan, + preview + } + + /** + * Indicates whether the IListDataAdapter was able to provide a count. + **/ + enum CountResult { + /** + * Indicates no count is available. + **/ + unknown + } + + /** + * Indicates that the IListDataAdapter was unable to provide a count. + **/ + enum CountError { + /** + * An attempt to count items timed out. + **/ + noResponse + } + + /** + * Describes the status of an IListDataSource. + **/ + enum DataSourceStatus { + /** + * The IListDataSource is ready. + **/ + ready, + /** + * The IListDataSource is still loading. + **/ + waiting, + /** + * The IListDataSource failed to load. + **/ + failure + } + + /** + * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. + **/ + enum EditError { + /** + * The edit operation timed out. + **/ + noResponse, + /** + * The data source cannot be written to. + **/ + notPermitted, + /** + * The item has changed. + **/ + noLongerMeaningful + } + + /** + * Specifies the type of error encountered when retrieving items from an IListDataAdapter. + **/ + enum FetchError { + /** + * The fetch operation timed out. + **/ + noResponse, + /** + * The specified item could not be located. + **/ + doesNotExist + } + + /** + * Specifies how group headers in a ListView respond to the tap interaction. + **/ + enum GroupHeaderTapBehavior { + /** + * The group is invoked. + **/ + invoke, + /** + * Nothing happens. + **/ + none + } + + /** + * Specifies the position of group headers relative to their items in a ListView. + **/ + enum HeaderPosition { + /** + * Group headers appear to the left of items. + **/ + left, + /** + * Group headers appear above items. + **/ + top + } + + /** + * Specifies that type of animation for which a contentanimating event was raised. + **/ + enum ListViewAnimationType { + /** + * The animation plays when the ListView is first displayed. + **/ + entrance, + /** + * The animation plays when the ListView is changing its content. + **/ + contentTransition + } + + /** + * Describes the type of object in a ListView. + **/ + enum ObjectType { + /** + * The object is a group header in the list. + **/ + groupHeader, + /** + * The object is an item in the list. + **/ + item + } + + /** + * Specifies the orientation of a control. + **/ + enum Orientation { + /** + * A horizontal layout. + **/ + horizontal, + /** + * A vertical layout. + **/ + vertical + } + + /** + * Specifies the selection mode of a ListView. + **/ + enum SelectionMode { + /** + * Items cannot be selected. + **/ + none, + /** + * A single item may be selected. + **/ + single, + /** + * Multiple items may be selected. Clicking additional items adds them to the selection. + **/ + multi + } + + /** + * Specifies whether elements are selected when the user performs a swipe interaction. + **/ + enum SwipeBehavior { + /** + * The swipe interaction selects the elements touched by the swipe. + **/ + select, + /** + * The swipe interaction does not change which elements are selected. + **/ + none + } + + /** + * Specifies how items in a ListView respond to the tap interaction. + **/ + enum TapBehavior { + /** + * The item is selected and invoked. + **/ + directSelect, + /** + * The item is selected if was not already selected, and its deselected if it was already selected. + **/ + toggleSelect, + /** + * The item is invoked but not selected. + **/ + invokeOnly, + /** + * Nothing happens. + **/ + none + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Contains items that were requested from an IListDataAdapter and provides some information about those items. + **/ + interface IFetchResult { + //#region Properties + + /** + * Gets or sets the index of the requested item in the IListDataAdapter object's data source. + **/ + absoluteIndex: number; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. + **/ + atEnd: boolean; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. + **/ + atStart: boolean; + + /** + * Gets or sets the items returned by the fetch operation. + **/ + items: T[]; + + /** + * Gets or sets the location of the requested item within the items array. + **/ + offset: number; + + /** + * Gets or sets the number of items in the IListDataAdapter object's underlying data source. + **/ + totalCount: number; + + //#endregion Properties + + } + + /** + * Represents an item in a list. + **/ + interface IItem { + //#region Properties + + /** + * Gets or sets the item's data. + **/ + data: T; + + /** + * Gets the group key for the item. This property is only available for items that belong to a grouped data source. + **/ + groupKey: string; + + /** + * Gets the temporary ID of the item. + **/ + handle: string; + + /** + * Gets the item's index in the IListDataSource. + **/ + index: number; + + /** + * Gets or sets the key the identifies the item. + **/ + key: string; + + //#endregion Properties + + } + + /** + * Provides a mechanism for retrieving IItem objects asynchronously. + **/ + interface IItemPromise { + //#region Events + + /** + * Occurs when there is an error in processing. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; + + /** + * Stops change notification tracking for the IItem that fulfills this IItemPromise. + **/ + release(): void; + + /** + * Begins change notification tracking for the IItem that fulfills this IItemPromise. + **/ + retain(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the complete or error function. + **/ + then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the temporary ID of the IItem that fulfills this promise. + **/ + handle: string; + + /** + * Gets or sets the index of the IItem contained by this IItemPromise. + **/ + index: number; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. Represents a layout for the ListView. + **/ + interface ILayout { + //#region Methods + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the first visible item at the specified point. + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the last visible item at the specified point. + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A object that has these properties: animationPromise, newEndIndex. + **/ + endLayout(): any; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item. + * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. + **/ + getItemPosition(itemIndex: number): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The data source index of the current item. + * @param element The element for the current item. + * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. + * @returns A Promise that contains the index of the next item (This item becomes the current item). + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. + **/ + getScrollBarRange(): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param x The x-coordinate to test. + * @param y The y-coordinate to test. + **/ + hitTest(x: number, y: number): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were added. + **/ + itemsAdded(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + itemsMoved(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were removed. + **/ + itemsRemoved(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param groupIndex The index of the group in the group data source. + * @param element The element to render for the group header. + **/ + layoutHeader(groupIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item in the data source. + * @param element The element to render for the item. + **/ + layoutItem(itemIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element that represents a header in the data source. + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element An element that represents an item in the data source. + **/ + prepareItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element being released. + **/ + releaseItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + reset(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. + **/ + setSite(site: ILayoutSite): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The starting pixel of the area to which the items are rendered. + * @param endScrollPosition The last pixel of the area to which the items are rendered. + * @param count The upper bound of the number of items to render. + * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. + **/ + startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; + + //#endregion Methods + + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + horizontal: boolean; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView. + **/ + interface ILayout2 { + //#region Methods + + /** + * Called when the ListView finishes a drag operation. + **/ + dragLeave(): void; + + /** + * Called when the ListView initiates a drag operation. + * @param x The x-coordinate of the drag. + * @param y The y-coordinate of the drag. + * @param dragInfo An object that indicates whether the item is selected. + **/ + dragOver(x: number, y: number, dragInfo: number): void; + + /** + * Called when the ListView requests that the ILayout2 execute animations. + **/ + executeAnimations(): void; + + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * Gets the item at the specified hit-test coordinates. These coordinates are absolute coordinates (they are not relative to the layout's content area). + * @param x The x-coordinate to test for. + * @param y The y-coordinate to test for. + * @returns An object that describes the item at the hit test coordinates. It has these properties: type, index. + **/ + hitTest(x: number, y: number): any; + + /** + * Sets the rendering site and specifies whether the layout supports groups. This method is called by the ListView to initialize the layout. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * Retrieves the indexes of the items in the specified pixel range. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Performs a layout pass. + * @param tree A structure representing the layout tree that is returned from the ListView. + * @param changedRange An object that lists the index of the first item in the changed item range. This object has these properties: startIndex. + * @param modifiedItems An object that contains the old and new indexes of the items that have been modified in the tree. + * @param modifiedGroups An object that contains the old and new indexes of the group elements that have been modified in the tree. + * @returns A Promise that executes after layout is complete, or an object that contains two Promise objects: realizedRangeComplete, layoutComplete. + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): any; + + /** + * Called when the ListView requests that the ILayout2 set up animations. + **/ + setupAnimations(): void; + + /** + * Releases resources that were obtained during the call to initialize. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the orientation of the layout. + **/ + orientation: any; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayoutSite2 interface. Represents a rendering site for an ILayout. + **/ + interface ILayoutSite { + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + animationsDisabled: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + itemSurface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + rtl: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + scrollbarPos: number; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + surface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewport: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewportSize: any; + + //#endregion Properties + + } + + /** + * Represents a rendering site for an ILayout2. + **/ + interface ILayoutSite2 { + //#region Properties + + /** + * Gets the number of groups in the site. + **/ + groupCount: number; + + /** + * Gets the number of items in the site. + **/ + itemCount: Promise; + + /** + * Gets the pixel range of the realization area. + **/ + realizedRange: any; + + /** + * Gets the tree for use by an object that implements the ILayout2 interface. + **/ + tree: any; + + /** + * Gets the pixel range of visible items in the site. + **/ + visibleRange: any; + + //#endregion Properties + + } + + /** + * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. + **/ + interface IListBinding { + //#region Methods + + /** + * Retrieves the current item. + * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. + **/ + current(): IItemPromise>; + + /** + * Gets the first item from the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. + **/ + first(): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. + * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. + * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. + **/ + fromDescription(description: string): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. + * @param index A value greater than or equal to 0 that is the index of the item to retrieve. + * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. + **/ + fromIndex(index: number): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. + * @param key The key that identifies the item to retrieve. This value must be a non-empty string. + * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. + * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. + **/ + fromKey(key: string, hints?: any): IItemPromise>; + + /** + * Makes the specified IItem or IItemPromise the current item. + * @param item The IItem or IItemPromise that will become the current item. + * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. + **/ + jumpToItem(item: IItem): IItemPromise>; + + /** + * Retrieves the last item in the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. + **/ + last(): IItemPromise>; + + /** + * Retrieves the item after the current item and makes it the current item. + * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. + **/ + next(): IItemPromise>; + + /** + * Retrieves the item before the current item and makes it the current item. + * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. + **/ + previous(): IItemPromise>; + + /** + * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. + **/ + release(): void; + + /** + * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. + * @param item The IItem or IItemPromise that should stop receiving notifications. + **/ + releaseItem(item: IItem): void; + + //#endregion Methods + + } + + /** + * Accesses data for an IListDataSource. + **/ + interface IListDataAdapter { + //#region Methods + + /** + * Overwrites the data of the specified item. + * @param key The key of the item to overwrite. + * @param newData The new data for the item. + * @param indexHint The index of the item, if known. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + change(key: string, newData: T, indexHint: number): Promise; + + /** + * Gets the number of items in the IListDataAdapter object's data source. + * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. + **/ + getCount(): Promise; + + /** + * Inserts the specified data after the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. + * @param previousIndexHint The index of the item to insert the new data after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; + + /** + * Adds the specified key and data to the end of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts the specified data before the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. + * @param nextIndexHint The index of the item to insert the new data before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; + + /** + * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. + * @param description A description of the item to locate. + * @param countBefore The number of items before the matched item to retrieve. + * @param countAfter The number of items after the matched item to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromEnd(count: number): Promise>; + + /** + * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. + * @param index The index of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. + * @param key The key of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromStart(count: number): Promise>; + + /** + * Returns a string representation of the specified item that can be used for comparisons. + * @param item The item for which to generate a signature. + * @returns The signature representation of the specified item. + **/ + itemSignature(item: IItem): string; + + /** + * Moves the specified item to just after another item. + * @param key A key of the item to move. + * @param previousKey The key of another item. The item to move will be moved to just after this item. + * @param indexHint The index of the item to move, if known. + * @param previousIndexHint The index to move the item after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; + + /** + * Moves the specified item to just before another item. + * @param key A key of the item to move. + * @param nextKey The key of another item. The item to move will be moved to just before this item. + * @param indexHint The index of the item to move, if known. + * @param nextIndexHint The index to move the item before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; + + /** + * Moves the specified item to the end of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToEnd(key: string, indexHint: number): Promise>; + + /** + * Moves the specified item to the beginning of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToStart(key: string, indexHint: number): Promise>; + + /** + * Removes the specified item from the IListDataAdapter object's data source. + * @param key The key of the item to remove. + * @param data The new data for the item. + * @param indexHint The index of the item. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + remove(key: string, data: T, indexHint: number): Promise; + + /** + * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. + * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . + **/ + setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. + **/ + compareByIdentity: boolean; + + //#endregion Properties + + } + + /** + * Notifies clients when an IListDataAdapter object's data changes. + **/ + interface IListDataNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Raises a notification that an item in the IListDataAdapter object's data source has changed. + * @param item The item that changed. + **/ + changed(item: IItem): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Raises a notification that an item has been added to the IListDataAdapter object's data source. + * @param newItem The new item added to the IListDataAdapter object's data source. + * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. + * @param index The index of the new item. + **/ + inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Raises a notification that an item was moved within the IListDataAdapter object's data source. + * @param item The item that was moved. + * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. + * @param oldIndex The item's original index. + * @param newIndex The item's new index. + **/ + moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; + + /** + * Reloads data from the IListDataAdapter. + **/ + reload(): void; + + /** + * Raises a notification that an item was removed from the IListDataAdapter object's data source. + * @param key The key of the item that was removed. + * @param index The index of the item that was removed. + **/ + removed(key: string, index?: number): void; + + //#endregion Methods + + } + + /** + * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. + **/ + interface IListDataSource { + //#region Events + + /** + * Occurs when the status of the IListDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. + **/ + beginEdits(): void; + + /** + * Overwrites the data of the specified item. + * @param key The key for the item to replace. + * @param newData The new data for the item. + * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. + **/ + change(key: string, newData: T): Promise>; + + /** + * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. + * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. + * @returns The new IListBinding. + **/ + createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; + + /** + * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. + **/ + endEdits(): void; + + /** + * Retrieves the number of items in the data source. + * @returns A Promise that provides a Number that is the number of items in the data source. + **/ + getCount(): Promise; + + /** + * Inserts a new item after another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param previousKey The key for an item in the data source. The new item will be added after this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string): Promise>; + + /** + * Adds an item to the end of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds an item to the beginning of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts an item before another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param nextKey The key of an item in the data source. The new item will be inserted before this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string): Promise>; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Retrieves the item that has the specified description. + * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromDescription(description: any): Promise>; + + /** + * Retrieves the item at the specified index. + * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromIndex(index: number): Promise>; + + /** + * Retrieves the item with the specified key. + * @param key The key of the item to retrieve. It must be a non-empty string. + * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. + **/ + itemFromKey(key: string, description?: any): Promise>; + + /** + * Moves an item to just after another item. + * @param key The key that identifies the item to move. + * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: string): Promise>; + + /** + * Moves an item before another item. + * @param key The key that identifies the item to move. + * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: string): Promise>; + + /** + * Moves an item to the end of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToEnd(key: string): Promise>; + + /** + * Moves the specified item to the beginning of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToStart(key: string): Promise>; + + /** + * Removes the specified item from the data source. + * @param key The key that identifies the item to remove. + * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. + **/ + remove(key: string): Promise>; + + //#endregion Methods + + } + + /** + * Used by an IListBinding to provide change notifications when items in a IListDataSource change. + **/ + interface IListNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Indicates that an item changed. + * @param newItem The updated item. + * @param oldItem The original item. + **/ + changed(newItem: IItem, oldItem: IItem): void; + + /** + * Indicates that the number of items in the IListDataSource has changed. + * @param newCount The updated count. + * @param oldCount The original count. + **/ + countChanged(newCount: number, oldCount: number): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Indicates that the index of an item changed. + * @param handle The temporary ID of the item. + * @param newIndex The new index. + * @param oldIndex The original index. + **/ + indexChanged(handle: string, newIndex: number, oldIndex: number): void; + + /** + * Indicates that an item was added to the IListDataSource. + * @param itemPromise A promise for the new IItem. + * @param previousHandle The temporary ID of the item that precedes the new item. + * @param nextHandle The temporary ID of the item that follows the new item. + **/ + inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an IItemPromise was fulfilled and that the item is now available. + * @param item The fulfilled item. + **/ + itemAvailable(item: IItem): void; + + /** + * Indicates that an item was moved. + * @param item A promise for the IItem that was moved. + * @param previousHandle The temporary ID of the item that now precedes the moved item. + * @param nextHandle The temporary ID of the item that now follows the moved item. + **/ + moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an item was removed. + * @param handle The temporary ID of the item that was removed. + * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. + **/ + removed(handle: string, mirage: boolean): void; + + //#endregion Methods + + } + + /** + * Represents a selection of ListView items. + **/ + interface ISelection { + //#region Methods + + /** + * Adds one or more items to the selection. + * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + add(items: any): Promise; + + /** + * Clears the selection. + * @returns A Promise that is fulfilled when the clear operation completes. + **/ + clear(): Promise; + + /** + * Returns the number of items in the selection. + * @returns The number of items in the selection. + **/ + count(): number; + + /** + * Returns a list of the indexes for the items in the selection. + * @returns The list of indexes for the items in the selection as an array of Number objects. + **/ + getIndices(): number[]; + + /** + * Returns an array that contains the items in the selection. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + getItems(): Promise[]>; + + /** + * Gets an array of the index ranges for the selected items. + * @returns An array that contains an ISelectionRange object for each index range in the selection. + **/ + getRanges(): ISelectionRange[]; + + /** + * Returns a value that indicates whether the selection contains every item in the data source. + * @returns true if the selection contains every item in the data source; otherwise, false. + **/ + isEverything(): boolean; + + /** + * Removes the specified items from the selection. + * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + remove(items: any): Promise; + + /** + * Adds all the items in the ListView to the selection. + **/ + selectAll(): void; + + /** + * Clears the current selection and replaces it with the specified items. + * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + set(items: any): Promise; + + //#endregion Methods + + } + + /** + * Represents a range of indexes or keys in an ISelection. + **/ + interface ISelectionRange { + //#region Properties + + /** + * Gets or sets the index of the first item in the range. + **/ + firstIndex: number; + + /** + * Gets or sets the key of the first item in the range. + **/ + firstKey: any; + + /** + * Gets or sets the index of the last item in the range. + **/ + lastIndex: number; + + /** + * Gets or sets of the key of the last item in the range. + **/ + lastKey: any; + + //#endregion Properties + + } + + /** + * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. + **/ + interface IZoomableView { + //#region Methods + + /** + * Initiates semantic zoom on the custom control. + **/ + beginZoom(): void; + + /** + * Initializes the semantic zoom state for the custom control. + * @param isZoomedOut True if this is the zoomed out view; otherwise false. + * @param isCurrentView True if this is the current view; otherwise false. + * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. + * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. + **/ + configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; + + /** + * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. + * @param isCurrentView True if the control is the visible control; otherwise false. + **/ + endZoom(isCurrentView: boolean): void; + + /** + * Retrieves the current item of the zoomed in or zoomed out child of the custom control. + * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. + **/ + getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; + + /** + * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. + * @returns Identifies the panning axis of the child control. Implementation specific. + **/ + getPanAxis(): string; + + /** + * Manages pointer input for the custom control. + * @param pointerId The ID of the pointer. + **/ + handlePointer(pointerId: string): void; + + /** + * Positions the specified item within the viewport of the child control when panning or zooming begins. + * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. + * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. + **/ + positionItem(item: T, position: Utilities.IPosition): void; + + /** + * Selects the item closest to the specified screen coordinates. + * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. + * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. + **/ + setCurrentItem(x: number, y: number): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * Represents an application toolbar for displaying commands. + **/ + class AppBar { + //#region Constructors + + /** + * Creates a new AppBar object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBar. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this AppBar. Call this method when the AppBar is no longer needed. After calling this method, the AppBar becomes unusable. + **/ + dispose(): void; + + /** + * Returns the AppBarCommand object identified by id. + * @param id The element idenitifier (ID) of the command to be returned. + * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. + **/ + getCommandById(id: string): AppBarCommand; + + /** + * Hides the AppBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the AppBar. + * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the AppBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the AppBar. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the AppBar while hiding all other commands. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Sets the AppBarCommand objects that appear in the app bar. + **/ + commands: AppBarCommand; + + /** + * Gets or sets a value that indicates whether the AppBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the AppBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the layout of the app bar contents. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in an app bar. + **/ + class AppBarCommand { + //#region Constructors + + /** + * Creates a new AppBarCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBarCommand. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this AppBarCommand. Call this method when the AppBarCommand is no longer needed. After calling this method, the AppBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the AppBarCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBarCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing HOME or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + firstElementFocus: any; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the AppBarCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the icon of the AppBarCommand. + **/ + icon: string; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing END or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + lastElementFocus: any; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets the section of the app bar that the command is in. + **/ + section: string; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: string; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Provides backwards navigation in the form of a button. + **/ + class BackButton { + //#region Constructors + + /** + * Creates a new BackButton. + * @constructor + * @param element The DOM element hosts the new BackButton. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this BackButton. Call this method when the BackButton is no longer needed. After calling this method, the BackButton becomes unusable. + **/ + dispose(): void; + + /** + * Checks the current navigation history and updates the value of the control's disabled attribute. + **/ + refresh(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this BackButton. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView in which items are arranged in a grid and items can span multiple grid cells. + **/ + class CellSpanningLayout { + //#region Constructors + + /** + * Creates a new CellSpanningLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new CellSpanningLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: ILayoutSite2, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the position of group headers relative to their items. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * Gets or sets a function that enables cell-spanning and establishes base cell dimensions. + **/ + groupInfo: Function; + + /** + * Gets or sets a function that returns the width and height of an item, as well as whether it should appear in a new column. Setting this function improves performance because the ListView can allocate space for an item without having to measure it first. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This API supports the Windows Library for JavaScript infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets the orientation of the CellSpanningLayout. For a CellSpanningLayout, this property always returns Orientation.horizontal. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Allows users to pick a date value. + **/ + class DatePicker { + //#region Constructors + + /** + * Initializes a new instance of the DatePicker control. + * @constructor + * @param element The DOM element associated with the DatePicker control. + * @param options The set of options to be applied initially to the DatePicker control. The options are the following: calendar, current, datePattern, disabled, maxYear, minYear, monthPattern, yearPattern. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this DatePicker. Call this method when the DatePicker is no longer needed. After calling this method, the DatePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the calendar to use. + **/ + calendar: any; + + /** + * Gets or sets the current date of the DatePicker. You can use either a date string or a Date object to set this property. + **/ + current: Date; + + /** + * Gets or sets the display pattern for the date. The default date pattern is day.integer(2). You can change the date pattern by changing the number of integers displayed. + **/ + datePattern: string; + + /** + * Specifies whether the DatePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the DatePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the maximum Gregorian year available for picking. + **/ + maxYear: number; + + /** + * Gets or sets the minimum Gregorian year available for picking. + **/ + minYear: number; + + /** + * Gets or sets the display pattern for the month. The default month pattern is month.abbreviated. You can change the month pattern to the following values: month.full. The full name of the month. month.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. If you do specify the number of letters, the actual length of the month name that appears may vary. month.solo.full. A representation of the month that is suitable for stand-alone display. You can also use month.solo.abbreviated(n). month.integer(n). You can use integer with or without specifying the number of integers. + **/ + monthPattern: string; + + /** + * Gets or sets the display pattern for the year. The default year pattern is year.full. You can change the year pattern to the following values: year.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. + **/ + yearPattern: string; + + //#endregion Properties + + } + + /** + * Adds event-related methods to the control. + **/ + class DOMEventMixin { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture true to initiate capture; otherwise, false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type, adding the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true to initiate capture; otherwise, false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + setOptions(control: any, options: any): void; + + //#endregion Methods + + } + + /** + * Displays a collection, such as a set of photos, one item at a time. + **/ + class FlipView { + //#region Constructors + + /** + * Creates a new FlipView. + * @constructor + * @param element The DOM element that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the datasource count changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. + **/ + ondatasourcecountchanged(eventInfo: Event): void; + + /** + * Raised when the FlipView flips to a page and its renderer function completes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpagecompleted(eventInfo: CustomEvent): void; + + /** + * Raised when the FlipView flips to a page. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpageselected(eventInfo: CustomEvent): void; + + /** + * Occurs when an item becomes invisible or visible. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. + **/ + onpagevisibilitychanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Returns the number of items in the FlipView control's itemDataSource. + * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. + **/ + count(): Promise; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this FlipView. Call this method when the FlipView is no longer needed. After calling this method, the FlipView becomes unusable. + **/ + dispose(): void; + + /** + * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Navigates to the next page. + * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. + **/ + next(): boolean; + + /** + * Navigates to the previous item. + * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. + **/ + previous(): boolean; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event. + * @param eventHandler The event handler function to remove. + * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. + **/ + removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Sets custom animations for the FlipView to use when navigating between pages. + * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. + **/ + setCustomAnimations(animations: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the currently displayed page. + **/ + currentPage: number; + + /** + * Gets the HTML element that hosts this FlipView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the spacing between each item, in pixels. + **/ + itemSpacing: number; + + /** + * Gets or sets a Template or function that defines the HTML for each item's page. + **/ + itemTemplate: any; + + /** + * Gets or sets the orientation of the FlipView, horizontal or vertical. + **/ + orientation: string; + + //#endregion Properties + + } + + /** + * Displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. + **/ + class Flyout { + //#region Constructors + + /** + * Creates a new Flyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Flyout. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after a flyout is fully hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a flyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Hides the Flyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Flyout, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Flyout. + * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". + * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Flyout. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Flyout. + **/ + anchor: HTMLElement; + + /** + * Gets the DOM element that hosts the Flyout. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Flyout is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Flyout. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. + **/ + class GridLayout { + //#region Constructors + + /** + * Creates a new GridLayout object. + * @constructor + * @param options The set of properties and values to apply to the new GridLayout. + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the maximumRowsOrColumns property. + **/ + maxRows: number; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Creates a hub navigation pattern consisting of sections that can be navigated to. Each section is defined by a HubSection object. + **/ + class Hub { + //#region Constructors + + /** + * Creates a new Hub control. + * @constructor + * @param element The DOM element that will host the Hub control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the contentanimating event, add a property named "oncontentanimating" to the options object and set its value to the event handler. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the Hub is about to play entrance, content transition, insert, or remove animations. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.index, detail.section. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user clicks on an interactive header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.section. + **/ + onheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the Hub control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: loadingState. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Hub. Call this method when the Hub is no longer needed. After calling this method, the Hub becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the Hub control. + **/ + element: HTMLElement; + + /** + * Gets or sets the Template or templating function that creates the DOM elements for each HubSection header. Your HubSection object should provide strings for HubSection.header property. + **/ + headerTemplate: any; + + /** + * Gets or sets the index of the first HubSection at least partially in view. This property is useful for animating the visible content in the Hub. + **/ + indexOfFirstVisible: number; + + /** + * Gets or sets the index of last HubSection at least partially in view. Used for animating the visible content in the Hub. + **/ + indexOfLastVisible: number; + + /** + * Gets a value that indicates whether the hub is still loading or whether loading is complete. The value changes to complete after all the sections and content inside them has loaded. + **/ + loadingState: string; + + /** + * Gets or sets the orientation of sections within the Hub. + **/ + orientation: Orientation; + + /** + * Gets or sets the distance between the start of the Hub and the current viewable area. + **/ + scrollPosition: number; + + /** + * Gets or sets the index of the first visible HubSection. + **/ + sectionOnScreen: any; + + /** + * Gets or sets the List that contains the HubSection objects that belong to this Hub. + **/ + sections: WinJS.Binding.List; + + /** + * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: any; + + //#endregion Properties + + } + + /** + * Defines a section of a Hub. + **/ + class HubSection { + //#region Constructors + + /** + * Creates a new HubSection. + * @constructor + * @param element The DOM element hosts the new HubSection. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this HubSection. Call this method when the HubSection is no longer needed. After calling this method, the HubSection becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the HubSection control's content. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts this HubSection. + **/ + element: HTMLElement; + + /** + * Gets or sets the header for this HubSection. + **/ + header: string; + + /** + * Gets a value that specifies whether the header is static. + **/ + isHeaderStatic: boolean; + + //#endregion Properties + + } + + /** + * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. + **/ + class HtmlControl { + //#region Constructors + + /** + * Initializes a new instance of HtmlControl to define a new page control. + * @constructor + * @param element The element that hosts the HtmlControl. + * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + } + + /** + * Defines an item that can be pressed, swiped, and dragged. + **/ + class ItemContainer { + //#region Constructors + + /** + * Creates a new ItemContainer. + * @constructor + * @param element The DOM element hosts the new ItemContainer. For the ItemContainer to be accessible, this element must have its role attribute set to "list" or "listbox". If tapBehavior is set to none and selectionDisabled is true, then use the "list" role; otherwise, use the "listbox" role. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the item is invoked. (You can use the tapBehavior property to specify whether taps and clicks invoke the item.) + * @param eventInfo An object that contains information about the event. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Raised after the item is selected or deselected. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Raised just before the current selection changes. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ItemContainer. Call this method when the ItemContainer is no longer needed. After calling this method, the ItemContainer becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ItemContainer to update its layout. Call this function when the reading direction of the app changes after the control has been initialized. + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the item can be dragged. + **/ + draggable: boolean; + + /** + * Gets the element that hosts this ItemContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the item is selected. + **/ + selected: boolean; + + /** + * Gets or sets a value that specifies whether selection of this item is disabled. + **/ + selectionDisabled: boolean; + + /** + * Gets or sets how the ItemContainer reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets the orientation of swipe gestures. + **/ + swipeOrientation: any; + + /** + * Gets or sets how the ItemContainer reacts when the user taps or clicks an item. + **/ + tapBehavior: any; + + //#endregion Properties + + } + + /** + * This object supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + class Layout { + } + + /** + * Represents a layout for the ListView in which items are arranged in a vertical list. + **/ + class ListLayout { + //#region Constructors + + /** + * Creates a new ListLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + initialize(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel + * @param lastPixel + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Displays data items in a customizable list or grid. + **/ + class ListView { + //#region Constructors + + /** + * Creates a new ListView. + * @constructor + * @param element The DOM element that hosts the ListView control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ListView is about to play an entrance or contentTransition animation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user taps or clicks a group header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.groupHeaderIndex, detail.groupHeaderPromise. + **/ + ongroupheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the ListView is a drop target and the onitemdragenter has been disabled. This is raised every time the cursor is moved between a new pair of items. If you call preventDefault on this event, then the ListView does not move the items slightly above/below the cursor to provide visual feedback for a drop. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragbetween(eventInfo: CustomEvent): void; + + /** + * Raised when the user is dragging an item from the ListView and the datasource changes while the user is dragging. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragchanged(eventInfo: CustomEvent): void; + + /** + * Raised when an item is dropped onto the ListView as the result of a drag operation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.index, detail.insertAfterIndex. + **/ + onitemdragdrop(eventInfo: CustomEvent): void; + + /** + * Raised when the user drops an item dragged from a ListView. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragend(eventInfo: CustomEvent): void; + + /** + * Raised when an dragged item enters the bounds of the ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer. + **/ + onitemdragenter(eventInfo: CustomEvent): void; + + /** + * Raised when a draggable item leaves the bounds of a ListView control. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragleave(eventInfo: CustomEvent): void; + + /** + * Raised when the user begins to drag an item from a ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.dragInfo. + **/ + onitemdragstart(eventInfo: CustomEvent): void; + + /** + * Occurs when the user taps or clicks an item. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. + **/ + oniteminvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the focused item changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. + **/ + onkeyboardnavigating(eventInfo: CustomEvent): void; + + /** + * Occurs when the ListView control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + /** + * Occurs after the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Occurs just before the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Returns the DOM element that represents the item at the specified index. + * @param itemIndex The index of the item. + * @returns The DOM element that represents the item at the specified index. + **/ + elementFromIndex(itemIndex: number): HTMLElement; + + /** + * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. + * @param itemIndex The index of the item to scroll into view. + **/ + ensureVisible(itemIndex: number): void; + + /** + * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Returns the index of the item that the specified DOM element displays. + * @param element The DOM element that displays the item. + * @returns The index of the item displayed by element. + **/ + indexOfElement(element: HTMLElement): number; + + /** + * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. + **/ + loadMorePages(): void; + + /** + * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. + **/ + recalculateItemPosition(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Triggers the ListView disposal service manually. + **/ + triggerDispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. + **/ + automaticallyLoadPages: boolean; + + /** + * Gets or sets an object that indicates which item should have keyboard focus and the focus state of that item. + **/ + currentItem: { index: number; key: string; hasFocus: boolean; showFocus: boolean }; + + /** + * Gets the HTML element that hosts this ListView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that contains the groups for the items in the itemDataSource. + **/ + groupDataSource: IListDataSource; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks a group header. + **/ + groupHeaderTapBehavior: GroupHeaderTapBehavior; + + /** + * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. + **/ + groupHeaderTemplate: any; + + /** + * Gets or sets the first visible item. + **/ + indexOfFirstVisible: number; + + /** + * Gets the index of the last visible item in the ListView. + **/ + indexOfLastVisible: number; + + /** + * Gets or sets the data source that provides the ListView with items. + **/ + itemDataSource: IListDataSource; + + /** + * Go Gets or sets a value that specifies whether items can be dragged. When this is set to true the ListView provides built in behaviors related to item dragging. + **/ + itemsDraggable: boolean; + + /** + * Gets or sets whether the ListView control's items can be reordered within itself by dragging and dropping. + **/ + itemsReorderable: boolean; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. + **/ + itemTemplate: any; + + /** + * Gets or sets an object that controls the layout of the ListView. + **/ + layout: any; + + /** + * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. + **/ + loadingBehavior: string; + + /** + * Gets a value that indicates whether the ListView is still loading or whether loading is complete. + **/ + loadingState: string; + + /** + * Gets or sets the maximum number of realized items. + **/ + maxDeferredItemCleanup: number; + + /** + * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. + **/ + pagesToLoad: number; + + /** + * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. + **/ + pagesToLoadThreshold: number; + + /** + * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. + **/ + resetGroupHeader: (header: any, element: HTMLElement) => void; + + /** + * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. + **/ + resetItem: (item: T, element: HTMLElement) => void; + + /** + * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. + **/ + scrollPosition: number; + + /** + * Gets an ISelection that contains the range of currently selected items. + **/ + selection: ISelection; + + /** + * Gets or sets the selection mode of the ListView. + **/ + selectionMode: SelectionMode; + + /** + * Gets or sets how the ListView reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + /** + * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView; + + //#endregion Properties + + } + + /** + * Represents a menu flyout for displaying commands. + **/ + class Menu { + //#region Constructors + + /** + * Creates a new Menu object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Menu. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Menu. Call this method when the Menu is no longer needed. After calling this method, the Menu becomes unusable. + **/ + dispose(): void; + + /** + * Returns the MenuCommand object identified by id. + * @param id The element identifier (ID) of the command to be returned. + * @returns The command identified by id. + **/ + getCommandById(id: string): MenuCommand; + + /** + * Hides the Menu. + **/ + hide(): void; + + /** + * Hides the specified commands of the Menu. + * @param commands The commands to hide. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Menu, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Menu. + * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. + * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + /** + * Shows the specified commands of the Menu. + * @param commands The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the Menu while hiding all other commands. + * @param commands The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Menu. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Menu. + **/ + anchor: HTMLElement; + + /** + * Sets the MenuCommand objects that appear in the menu. + **/ + commands: MenuCommand; + + /** + * Gets the DOM element that hosts the Menu. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Menu is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Menu. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in a Menu object. + **/ + class MenuCommand { + //#region Constructors + + /** + * Creates a new MenuCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new MenuCommand. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Disposes this control. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the MenuCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the MenuCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the MenuCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets a value that indicates whether the MenuCommand is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Displays navigation commands in a toolbar that the user can show or hide. + **/ + class NavBar { + //#region Constructors + + /** + * Creates a new NavBar. + * @constructor + * @param element The DOM element that will host the new NavBar. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised after the NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + /** + * Occurs after the NavBar has finished processing its child elements. + * @param eventInfo An object that contains information about the event. + **/ + onchildrenprocessed(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBar. Call this method when the NavBar is no longer needed. After calling this method, the NavBar becomes unusable. + **/ + dispose(): void; + + /** + * Hides the NavBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the NavBar. + * @param commands The commands to hide. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Shows the NavBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the NavBar. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the NavBar while hiding all other commands. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + commands: AppBarCommand; + + /** + * Gets or sets a value that indicates whether the NavBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the HTML element that hosts this NavBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the NavBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the NavBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the NavBar is sticky (won't light dismiss). If not sticky, the NavBar dismisses normally when the user touches outside of the NavBar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a navigation command in a NavBarContainer. + **/ + class NavBarCommand { + //#region Constructors + + /** + * Creates a new NavBarCommand. + * @constructor + * @param element The DOM element hosts the new NavBarCommand. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this NavBarCommand. + **/ + element: HTMLElement; + + /** + * Gets or sets the command's icon. + **/ + icon: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Get or sets the location to navigate to when this command is invoked. + **/ + location: any; + + /** + * Gets or sets a value that specifies whether to show the split tab stop. + **/ + splitButton: boolean; + + /** + * Gets a value that indicates whether the splitButton is open. + **/ + splitOpened: boolean; + + /** + * Gets or sets a user-defined object that represents the state associated with the command's location. + **/ + state: any; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: any; + + //#endregion Properties + + } + + /** + * Contains a group of NavBarCommand objects in a NavBar. + **/ + class NavBarContainer { + //#region Constructors + + /** + * Creates a new NavBarContainer. + * @constructor + * @param element The DOM element hosts the new NavBarContainer. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when a child NavBarCommand object's click event fires. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.navbarcommand, detail.data. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Occurs when the split button of a child NavBarCommand is opened or closed. A split button is toggled when the user navigates to another page or opens another split button. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.opened, detail.index, detail.navbarcommand, detail.data. + **/ + onsplittoggle(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Forces the NavBarContainer to update its layout. Use this function when making the NavBarContainer visible again after you set its style.display property to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the current item. + **/ + currentIndex: number; + + /** + * Gets or sets a WinJS.Binding.List that generates NavBarCommand objects. + **/ + data: WinJS.Binding.List; + + /** + * Gets the HTML element that hosts this NavBarContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether NavBarCommand objects in this container use a fixed or dynamic width. + **/ + fixedSize: boolean; + + /** + * Gets or sets a value that specifies whether the NavBarContainer has a horizontal or vertical layout. + **/ + layout: Orientation; + + /** + * Gets or sets a value that specifies how many rows of navigation commands to display on a page. + **/ + maxRows: number; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the data source. Each item can contain multiple elements, but it must have a single root element. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Lets the user rate something by clicking an icon that represents a rating. The Rating control can display three types of ratings: an average rating, a tentative rating, and the user's rating. + **/ + class Rating { + //#region Constructors + + /** + * Creates a new Rating. + * @constructor + * @param element The DOM element hosts the new Rating. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user finishes interacting with the rating control without committing a tentative rating. + * @param eventInfo An object that contains information about the event. + **/ + oncancel(eventInfo: Event): void; + + /** + * Raised when the user commits a change to the userRating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onchange(eventInfo: CustomEvent): void; + + /** + * Raised when the user is choosing a new tentative Rating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onpreviewchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Rating. Call this method when the Rating is no longer needed. After calling this method, the Rating becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the average rating. + **/ + averageRating: number; + + /** + * Gets or sets whether the control is disabled. When the control is disabled, the user can't specify a new user rating or modify an existing rating. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the Rating. + **/ + element: HTMLElement; + + /** + * Gets or sets whether control lets the user clear the rating. + **/ + enableClear: boolean; + + /** + * Gets or sets the maximum possible rating value. + **/ + maxRating: number; + + /** + * Gets or sets a set of descriptions to show for rating values in the tooltip. + **/ + tooltipStrings: string[]; + + /** + * Gets or sets the user's rating. + **/ + userRating: number; + + //#endregion Properties + + } + + /** + * Generates HTML from a set of data. Use this control to generate lists of items. + **/ + class Repeater { + //#region Constructors + + /** + * Creates a new Repeater control. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanging(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserting(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoving(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoving(eventInfo: CustomEvent): void; + + /** + * Raised when the Repeater has finished loading a new set of data. This event is only fired on construction. This event is only raised when the Repeater is constructed or its data source or template changes. + * @param eventInfo An object that contains information about the event. + **/ + onitemsloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements. + **/ + onitemsreloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements, detail.setPromise. + **/ + onitemsreloading(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Repeater. Call this method when the Repeater is no longer needed. After calling this method, the Repeater becomes unusable. + **/ + dispose(): void; + + /** + * Returns the HTML element for the item at the specified index. + * @param index The index of the item. + * @returns The DOM element for the specified item. + **/ + elementFromIndex(index: number): HTMLElement; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the List that provides the Repeater with items to display. + **/ + data: WinJS.Binding.List; + + /** + * Gets the DOM element that hosts the Repeater. + **/ + element: HTMLElement; + + /** + * Gets the number of items in the Repeater control. + **/ + length: number; + + /** + * Gets or sets a WinJS.Binding.Template or custom rendering function that defines the HTML of each item within the Repeater. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Enables the user to perform search queries and select suggestions. + **/ + class SearchBox { + //#region Constructors + + /** + * Creates a new SearchBox. + * @constructor + * @param element The DOM element hosts the new SearchBox. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user or the app changes the queryText. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails. + **/ + onquerychanged(eventInfo: CustomEvent): void; + + /** + * Raised awhen the user clicks the search glyph or presses Enter. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails, detail.keyModifiers. + **/ + onquerysubmitted(eventInfo: CustomEvent): void; + + /** + * Raised when the app automatically redirects focus to the search box. This event can only be raised when the focusOnKeyboardInput property is set to true. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.propertyName. + **/ + onreceivingfocusonkeyboardinput(eventInfo: CustomEvent): void; + + /** + * Raised when the user selects a suggested option for the search. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tag, detail.keyModifiers, detail.storageFile. + **/ + onresultsuggestionschosen(eventInfo: CustomEvent): void; + + /** + * Raised when the system requests search suggestions from this app. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.linguisticDetails, detail.queryText, detail.searchSuggestionCollection. + **/ + onsuggestionsrequested(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SearchBox. Call this method when the SearchBox is no longer needed. After calling this method, the SearchBox becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Specifies whether suggestions based on local files are automatically displayed in the search pane, and defines the criteria that Windows uses to locate and filter these suggestions. + * @param settings The new settings for local content suggestions. + **/ + setLocalContentSuggestionSettings(settings: Windows.ApplicationModel.Search.LocalContentSuggestionSettings): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets whether the first suggestion is chosen when the user presses Enter. + **/ + chooseSuggestionOnEnter: boolean; + + /** + * Gets or sets a value that specifies whether the SearchBox is disabled. If the control is disabled, it won't receive focus. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the SearchBox. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the search box automatically receives focus when the user types into the app window. + **/ + focusOnKeyboardInput: boolean; + + /** + * Gets or sets the placeholder text for the SearchBox. This text is displayed if there is no other text in the input box. + **/ + placeholderText: string; + + /** + * Gets or sets the query text for the SearchBox. + **/ + queryText: string; + + /** + * Gets or sets the search history context. This context is used a secondary key (the app ID is the primary key) for storing search history. + **/ + searchHistoryContext: string; + + /** + * Gets or sets a value that specifies whether search history is disabled. + **/ + searchHistoryDisabled: boolean; + + //#endregion Properties + + } + + /** + * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. + **/ + class SemanticZoom { + //#region Constructors + + /** + * Creates a new SemanticZoom. + * @constructor + * @param element The DOM element that hosts the SemanticZoom. + * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the control zooms in or out. + * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. + **/ + onzoomchanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SemanticZoom. Call this method when the SemanticZoom is no longer needed. After calling this method, the SemanticZoom becomes unusable. + **/ + dispose(): void; + + /** + * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the SemanticZoom control. + **/ + element: HTMLElement; + + /** + * Gets or a sets a value that specifies whether to display the SemanticZoom zoom out button. + **/ + enableButton: boolean; + + /** + * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. + **/ + isDeclarativeControlContainer: boolean; + + /** + * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. + **/ + locked: boolean; + + /** + * Gets or sets a value that indicates whether the control is zoomed out. + **/ + zoomedOut: boolean; + + /** + * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. + **/ + zoomFactor: number; + + //#endregion Properties + + } + + /** + * Provides users with fast, in-context access to settings that affect the current Windows Store app. + **/ + class SettingsFlyout { + //#region Constructors + + /** + * Creates a new SettingsFlyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new SettingsFlyout. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after the SettingsFlyout is completely hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a SettingsFlyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SettingsFlyout. Call this method when the SettingsFlyout is no longer needed. After calling this method, the SettingsFlyout becomes unusable. + **/ + dispose(): void; + + /** + * Hides the SettingsFlyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Loads a fragment of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. + * @param e An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains the applicationcommands sub-property that you set to an array of settings commands. You then populate the SettingsFlyout with these commands by a call to populateSettings. + **/ + static populateSettings(e: CustomEvent): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the SettingsPane UI, if hidden. + **/ + show(): void; + + /** + * Shows the SettingsPane UI, if hidden, regardless of other state. + **/ + static show(): void; + + /** + * Show the Settings flyout using the Settings element identifier (ID) and the path of the page that contains the Settings element. + * @param id The ID of the Settings element. + * @param path The path of the page that contains the Settings element. + **/ + static showSettings(id: string, path: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element the SettingsFlyout is attached to. + **/ + element: HTMLElement; + + /** + * Gets whether the SettingsFlyout is hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the settings command Id for the SettingsFlyout control. + **/ + settingsCommandId: string; + + /** + * This property may be unavailable or altered in future versions. Use the CSS width property of the element that has the win-settingsflyout class instead. + **/ + width: string; + + //#endregion Properties + + } + + /** + * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. + **/ + class StorageDataSource { + //#region Constructors + + /** + * Creates a new StorageDataSource object. + * @constructor + * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. + * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . + **/ + constructor(query: Windows.Storage.Search.IStorageQueryResultBase, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Draws the thumbnail for the specified item to the specified img element. + * @param item The item to retrieve the thumbnail for. + * @param image The img element that will display the thumbnail. + * @returns A Promise that completes when the full-quality thumbnail is visible. + **/ + loadThumbnail(item: IItem, image: HTMLElement): Promise; + + //#endregion Methods + + } + + /** + * Prevents a DOM sub-tree from receiving tab navigations and focus. + **/ + class TabContainer { + //#region Constructors + + /** + * Creates a new TabContainer. + * @constructor + * @param element The DOM element that hosts the TabContainer control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this TabContainer. Call this method when the TabContainer is no longer needed. After calling this method, the TabContainer becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the child DOM element that receives tab focus. + **/ + childFocus: HTMLElement; + + /** + * Gets or sets the tab index of this container. + **/ + tabIndex: any; + + //#endregion Properties + + } + + /** + * Allows users to select time values. + **/ + class TimePicker { + //#region Constructors + + /** + * Initializes a new instance of a TimePicker control. + * @constructor + * @param element The DOM element associated with the TimePicker control. + * @param options The set of options to be applied initially to the TimePicker control. The options are the following: clock. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this TimePicker. Call this method when the TimePicker is no longer needed. After calling this method, the TimePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. + **/ + clock: string; + + /** + * Gets or sets the current time of the TimePicker. Note that the date value is always July 15, 2011. + **/ + current: Date; + + /** + * Specifies whether the TimePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the TimePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the display pattern for the hour. The default hour pattern is hour.integer(2). You can change the hour pattern by changing the number of integers displayed. + **/ + hourPattern: string; + + /** + * Gets or sets the minute increment. For example, 15 specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. + **/ + minuteIncrement: number; + + /** + * Gets or sets the display pattern for the minute. The default minute pattern is minute.integer(2). You can change the minute pattern by changing the number of integers displayed. + **/ + minutePattern: string; + + /** + * Gets or sets the display pattern for the period. The default period pattern is period.abbreviated(2). You can change the period pattern by changing the number of integers displayed. + **/ + periodPattern: string; + + //#endregion Properties + + } + + /** + * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). + **/ + class ToggleSwitch { + //#region Constructors + + /** + * Creates a new ToggleSwitch. + * @constructor + * @param element The DOM that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ToggleSwitch. Call this method when the ToggleSwitch is no longer needed. After calling this method, the ToggleSwitch becomes unusable. + **/ + dispose(): void; + + /** + * Handles the specified event. + * @param event The event. + **/ + handleEvent(event: any): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the control is on or off. + **/ + checked: boolean; + + /** + * Gets or sets a value that specifies whether the control is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the ToggleSwitch. + **/ + element: HTMLElement; + + /** + * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). + **/ + labelOff: string; + + /** + * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). + **/ + labelOn: string; + + /** + * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. + **/ + title: string; + + //#endregion Properties + + } + + /** + * Displays a tooltip that can contain images and formatting. + **/ + class Tooltip { + //#region Constructors + + /** + * Creates a new Tooltip. + * @constructor + * @param element The DOM element associated that hosts the Tooltip. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the opened event, add a property named "onopened" to the options object and set its value to the event handler. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised just before the Tooltip is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeclose(eventInfo: CustomEvent): void; + + /** + * Raised just before the Tooltip appears. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeopen(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is no longer displayed. + * @param eventInfo An object that contains information about the event. + **/ + onclosed(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is shown. + * @param eventInfo An object that contains information about the event. + **/ + onopened(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Hides the Tooltip. + **/ + close(): void; + + /** + * Releases resources held by this Tooltip. Call this method when the Tooltip is no longer needed. After calling this method, the Tooltip becomes unusable. + **/ + dispose(): void; + + /** + * Shows the Tooltip. + * @param type A value that specifies when to show the Tooltip. The default value is "mousedown". + **/ + open(type?: string): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the HTML element that is the content of the Tooltip. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the Tooltip control. + **/ + element: HTMLElement; + + /** + * Gets or appends additional CSS classes to apply to the element that hosts the Tooltip. + **/ + extraClass: string; + + /** + * Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains a lot of info and should be displayed for longer than a typical Tooltip. + **/ + infotip: boolean; + + /** + * Gets or sets the HTML content of the Tooltip. + **/ + innerHTML: string; + + /** + * Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. + **/ + class ViewBox { + //#region Constructors + + /** + * Initializes a new instance of the ViewBox control. + * @constructor + * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. + * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this ViewBox. Call this method when the ViewBox is no longer needed. After calling this method, the ViewBox becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that functions as the scaling box. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Serves as the base class for a custom IListDataSource. + **/ + class VirtualizedDataSource { + //#region Constructors + + /** + * Initializes the VirtualizedDataSource base class of a custom data source. + * @constructor + * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. + * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. + **/ + constructor(listDataAdapter: IListDataAdapter, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the status of the VirtualizedDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns a new IListDataSource that adds group information to the items of another IListDataSource. + * @param listDataSource The data source for the individual items to group. + * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. + * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. + * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. + * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + **/ + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + + /** + * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. + **/ + function disableAnimations(): void; + + /** + * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. + **/ + function enableAnimations(): void; + + /** + * Marks a event handler function as being compatible with declarative processing. + * @param handler The handler to be marked as compatible with declarative processing. + * @returns The handler, marked as compatible with declarative processing. + **/ + function eventHandler(handler: any): any; + + /** + * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise object that completes when the CSS animation is complete. + **/ + function executeAnimation(element: HTMLElement, animation: any): Promise; + + /** + * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise that completes when the transition is finished. + **/ + function executeTransition(element: HTMLElement, transition: any): Promise; + + /** + * Retrieves the items in the specified index range. + * @param dataSource The data source that contains the items to retrieve. + * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; + + /** + * Determines whether the Animations Library and ListView animations will be performed if called. + * @returns Returns true if animations will be performed; otherwise false. + **/ + function isAnimationEnabled(): boolean; + + /** + * Applies declarative control binding to all elements, starting at the specified root element. + * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. + * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. + * @returns A promise that is fulfilled when binding has been applied to all the controls. + **/ + function processAll(rootElement?: Element, skipRoot?: boolean): Promise; + + /** + * Applies declarative control binding to the specified element. + * @param element The element to bind. + * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. + **/ + function process(element: Element): Promise; + + /** + * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. + * @param selector The selector string. + * @param element The element to begin walking to the root of the document from. + * @returns The target element, if found. + **/ + function scopedSelect(selector: string, element: HTMLElement): HTMLElement; + + /** + * Given a DOM element and a control, attaches the control to the element. + * @param element Element to associate with the control. + * @param control The control to attach to the element. + **/ + function setControl(element: HTMLElement, control: any): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + function setOptions(control: any, options?: any): void; + + //#endregion Functions + +} +/** + * Provides functions to load HTML content programmatically. +**/ +declare module WinJS.UI.Fragments { + //#region Functions + + /** + * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. + * @param href The URI that contains the fragment to be copied. + * @returns A promise that is fulfilled when the fragment has been prepared for copying. + **/ + function cache(href: string): Promise; + + /** + * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. + * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. + **/ + function clearCache(href: string): void; + + /** + * Loads the contents of the specified URI into the specified element without copying it. + * @param href The URI that contains the fragment to copy. + * @param element Optional. The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. + **/ + function render(href: string, element: HTMLElement): Promise; + + /** + * Loads and copies the contents of the specified URI into the specified element. + * @param href The URI that contains the fragment to copy. + * @param target The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. + **/ + function renderCopy(href: string, target: HTMLElement): Promise; + + //#endregion Functions + +} +/** + * Provides methods for defining and displaying PageControl objects. +**/ +declare module WinJS.UI.Pages { + //#region Interfaces + + /** + * Provides members for a PageControl. You implement this interface when defining a new PageControl. + **/ + interface IPageControlMembers { + //#region Methods + + /** + * Called if any error occurs during the processing of the page. + * @param err The error that occurred. + * @returns Nothing if the error was handled, or an error promise if the error was not handled. + **/ + error?(err: any): Promise; + + /** + * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + init?(element: HTMLElement, options: any): Promise; + + /** + * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. + * @param uri The URI from which to create DOM objects. + * @returns A promise whose fulfilled value is the set of unparented DOM objects. + **/ + load?(uri: string): Promise; + + /** + * Initializes the control after the content of the control is set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options that are to be passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + processed?(element: HTMLElement, options: any): Promise; + + /** + * Called after all initialization and rendering is complete. At this time, the element is ready for use. + * @param element The DOM element that contains all the content for the page. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. + **/ + ready?(element: HTMLElement, options: any): Promise; + + /** + * Takes the elements returned by the load method and attaches them to the specified element. + * @param element The DOM element to which the loadResult elements are appended. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param loadResult A Promise that contains the elements returned from the load method. + **/ + render?(element: HTMLElement, options: any, loadResult: Promise): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. + **/ + class PageControl { + } + + //#endregion Objects + + //#region Functions + + /** + * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. + * @param uri The URI for the content that defines the page. + * @param members An object that defines the members that the control will have. + * @returns A constructor function that creates the PageControl. + **/ + function define(uri: string, members: IPageControlMembers): PageControl; + + /** + * Gets an already-defined page control for the specified URI, or creates a new one. + * @param uri The URI for the content that defines the page. + * @returns A constructor function that creates the page. + **/ + function get(uri: string): Function; + + /** + * Creates a PageControl from the specified URI and inserts it inside the specified element. + * @param uri The URI for the content that defines the page. + * @param element The DOM element to which the PageControl is appended. + * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. + * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + + //#endregion Functions + +} +/** + * Provides methods for detecting when the user tabs to or from DOM elements. +**/ +declare module WinJS.UI.TrackTabBehavior { + //#region Functions + + /** + * Sets the tab order for the specified element within its container. + * @param element The element to update. + * @param tabIndex The index value of the element within its container. + **/ + function attach(element: HTMLElement, tabIndex: number): void; + + /** + * Removes the tab order information from the specified element. + * @param element The element to remove tab information from. + **/ + function detatch(element: HTMLElement): void; + + //#endregion Functions + +} +/** + * Provides helper functions, for example, functions to add and remove CSS classes. +**/ +declare module WinJS.Utilities { + //#region Enumerations + + /** + * Defines a set of keyboard values. + **/ + enum Key { + /** + * The BACKSPACE key. + **/ + backspace, + /** + * The TAB key. + **/ + tab, + /** + * The ENTER key. + **/ + enter, + /** + * The SHIFT key. + **/ + shift, + /** + * The CTRL key. + **/ + ctrl, + /** + * The ALT key. + **/ + alt, + /** + * The PAUSE key. + **/ + pause, + /** + * The CAPS LOCK key. + **/ + capsLock, + /** + * The ESCAPE key. + **/ + escape, + /** + * The SPACE key. + **/ + space, + /** + * The PAGE UP key. + **/ + pageUp, + /** + * The PAGE DOWN key. + **/ + pageDown, + /** + * The END key. + **/ + end, + /** + * The HOME key. + **/ + home, + /** + * The LEFT ARROW key. + **/ + leftArrow, + /** + * The UP ARROW key. + **/ + upArrow, + /** + * The RIGHT ARROW key. + **/ + rightArrow, + /** + * The DOWN ARROW key. + **/ + downArrow, + /** + * The INSERT key. + **/ + insert, + /** + * The DELETE key. + **/ + deleteKey, + /** + * The 0 key. + **/ + num0, + /** + * The 1 key. + **/ + num1, + /** + * The 2 key. + **/ + num2, + /** + * The 3 key. + **/ + num3, + /** + * The 4 key. + **/ + num4, + /** + * The 5 key. + **/ + num5, + /** + * The 6 key. + **/ + num6, + /** + * The 7 key. + **/ + num7, + /** + * The 8 key. + **/ + num8, + /** + * The 9 key. + **/ + num9, + /** + * The a key. + **/ + a, + /** + * The b key. + **/ + b, + /** + * The c key. + **/ + c, + /** + * The d key. + **/ + d, + /** + * The e key. + **/ + e, + /** + * The f key. + **/ + f, + /** + * The g key. + **/ + g, + /** + * The h key. + **/ + h, + /** + * The i key. + **/ + i, + /** + * The j key. + **/ + j, + /** + * The k key. + **/ + k, + /** + * The l key. + **/ + l, + /** + * The m key. + **/ + m, + /** + * The n key. + **/ + n, + /** + * The o key. + **/ + o, + /** + * The p key. + **/ + p, + /** + * The q key. + **/ + q, + /** + * The r key. + **/ + r, + /** + * The s key. + **/ + s, + /** + * The t key. + **/ + t, + /** + * The u key. + **/ + u, + /** + * The v key. + **/ + v, + /** + * The w key. + **/ + w, + /** + * The x key. + **/ + x, + /** + * The y key. + **/ + y, + /** + * The z key. + **/ + z, + /** + * The left Windows key. + **/ + leftWindows, + /** + * The right Windows key. + **/ + rightWindows, + /** + * The menu key. + **/ + menu, + /** + * The 0 key on the numerical keypad. + **/ + numPad0, + /** + * The 1 key on the numerical keypad. + **/ + numPad1, + /** + * The 2 key on the numerical keypad. + **/ + numPad2, + /** + * The 3 key on the numerical keypad. + **/ + numPad3, + /** + * The 4 key on the numerical keypad. + **/ + numPad4, + /** + * The 5 key on the numerical keypad. + **/ + numPad5, + /** + * The 6 key on the numerical keypad. + **/ + numPad6, + /** + * The 7 key on the numerical keypad. + **/ + numPad7, + /** + * The 8 key on the numerical keypad. + **/ + numPad8, + /** + * The 9 key on the numerical keypad. + **/ + numPad9, + /** + * The multiplication key (*). + **/ + multiply, + /** + * The addition key (+). + **/ + add, + /** + * The subtraction key (-). + **/ + subtract, + /** + * The decimal point key (.) + **/ + decimalPoint, + /** + * The division key (/). + **/ + divide, + /** + * The F1 key. + **/ + F1, + /** + * The F2 key. + **/ + F2, + /** + * The F3 key. + **/ + F3, + /** + * The F4 key. + **/ + F4, + /** + * The F5 key. + **/ + F5, + /** + * The F6 key. + **/ + F6, + /** + * The F7 key. + **/ + F7, + /** + * The F8 key. + **/ + F8, + /** + * The F9 key. + **/ + F9, + /** + * The F10 key. + **/ + F10, + /** + * The F11 key. + **/ + F11, + /** + * The F12 key. + **/ + F12, + /** + * The NUMBER LOCK key. + **/ + numLock, + /** + * The SCROLL LOCK key. + **/ + scrollLock, + /** + * The browser BACK key. + **/ + browserBack, + /** + * The browser FORWARD key. + **/ + browserForward, + /** + * The semicolon key (;). + **/ + semicolon, + /** + * The equals key (=). + **/ + equal, + /** + * The comma key (,). + **/ + comma, + /** + * The dash key (-). + **/ + dash, + /** + * The period key (.). + **/ + period, + /** + * The forward slash key (/). + **/ + forwardSlash, + /** + * The grave accent key (`). + **/ + graveAccent, + /** + * The open bracket key ([). + **/ + openBracket, + /** + * The backslash key (\). + **/ + backSlash, + /** + * The close bracket key (]). + **/ + closeBracket, + /** + * The single quote key ('). + **/ + singleQuote + } + + //#endregion Enumerations + + //#region Objects + + /** + * A mixin that contains event-related functions. + **/ + var eventMixin: { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + }; + + /** + * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. + **/ + class QueryCollection { + //#region Constructors + + /** + * Initializes a new instance of a QueryCollection. + * @constructor + * @param items The items resulting from the query. + **/ + constructor(items: T[]); + + //#endregion Constructors + + //#region Methods + + /** + * Adds the specified class to all the elements in the collection. + * @param name The name of the class to add. + * @returns This QueryCollection object. + **/ + addClass(name: string): QueryCollection; + + /** + * Creates a QueryCollection that contains the children of the specified parent element. + * @param element The parent element. + * @returns The QueryCollection that contains the children of the element. + **/ + children(element: HTMLElement): QueryCollection; + + /** + * Clears the specified style property for all the elements in the collection. + * @param name The name of the style property to be cleared. + * @returns This QueryCollection object. + **/ + clearStyle(name: string): QueryCollection; + + /** + * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. + * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. + * @param options The options passed to the newly-created controls. + * @returns This QueryCollection object. + **/ + control(ctor: any, options?: any): QueryCollection; + + /** + * Performs an action on each item in the QueryCollection. + * @param callbackFn The action to perform on each item. + * @param thisArg The argument to bind to callbackFn. + * @returns The QueryCollection. + **/ + forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; + + /** + * Gets an item from the QueryCollection. + * @param index The index of the item to return. + * @returns A single item from the collection. + **/ + get(index: number): T; + + /** + * Gets an attribute value from the first element in the collection. + * @param name The name of the attribute. + * @returns The value of the attribute. + **/ + getAttribute(name: string): any; + + /** + * Determines whether the specified class exists on the first element of the collection. + * @param name The name of the class. + * @returns true if the element has the specified class; otherwise, false. + **/ + hasClass(name: string): boolean; + + /** + * Looks up an element by ID and wraps the result in a QueryCollection. + * @param id The ID of the element. + * @returns A QueryCollection that contains the element, if it is found. + **/ + id(id: string): QueryCollection; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T): void; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T[]): void; + + /** + * Registers the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function to be called when the event occurs. + * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. + **/ + listen(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. + * @param query The query selector string. + * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. + **/ + query(query: any): QueryCollection; + + /** + * Removes the specified class from all the elements in the collection. + * @param name The name of the class to be removed. + * @returns his QueryCollection object. + **/ + removeClass(name: string): QueryCollection; + + /** + * Unregisters the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function. + * @param capture true if capture == true; otherwise, false. + * @returns This QueryCollection object. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; + + /** + * Sets an attribute value on all the items in the collection. + * @param name The name of the attribute to be set. + * @param value The value of the attribute to be set. + * @returns This QueryCollection object. + **/ + setAttribute(name: string, value: any): QueryCollection; + + /** + * Sets the specified style property for all the elements in the collection. + * @param name The name of the style property. + * @param value The value for the property. + * @returns This QueryCollection object. + **/ + setStyle(name: string, value: any): QueryCollection; + + /** + * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. + * @param templateElement The DOM element to which the template control is attached. + * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. + * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. + * @returns The QueryCollection. + **/ + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + + /** + * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. + * @param name The name of the class to be toggled. + * @returns This QueryCollection object. + **/ + toggleClass(name: string): QueryCollection; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Adds the specified class to the specified element. + * @param e The element to which to add the class. + * @param name The name of the class to add. + * @returns The element. + **/ + function addClass(e: HTMLElement, name: string): HTMLElement; + + /** + * Gets a collection of elements that are the direct children of the specified element. + * @param element The parent element. + * @returns The collection of children of the element. + **/ + function children(element: HTMLElement): QueryCollection; + + /** + * Converts a CSS positioning string for the specified element to pixels. + * @param element The element. + * @param value The CSS positioning string. + * @returns The number of pixels. + **/ + function convertToPixels(element: HTMLElement, value: string): number; + + /** + * Creates an object that has one event for each name passed to the function. + * @param events A variable list of property names. + * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. + **/ + function createEventProperties(...events: string[]): any; + + /** + * Gets the data value associated with the specified element. + * @param element The element. + * @returns The value associated with the element. + **/ + function data(element: HTMLElement): any; + + /** + * Disposes all first-generation disposable elements that are descendents of the specified element. The specified element itself is not disposed. + * @param element The root element whose sub-tree is to be disposed. + **/ + function disposeSubTree(element: HTMLElement): void; + + /** + * Removes all the child nodes from the specified element. + * @param element The element. + * @returns The element. + **/ + function empty(element: HTMLElement): HTMLElement; + + /** + * Determines whether the specified event occurred within the specified element. + * @param element The element. + * @param event The event. + * @returns true if the event occurred within the element; otherwise, false. + **/ + function eventWithinElement(element: HTMLElement, event: Event): boolean; + + /** + * Adds tags and type to a logging message. + * @param message The message to be formatted. + * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. + * @param type The type of the message. + * @returns The formatted message. + **/ + function formatLog(message: string, tag: string, type: string): string; + + /** + * Gets the height of the content of the specified element. The content height does not include borders or padding. + * @param element The element. + * @returns The content height of the element. + **/ + function getContentHeight(element: HTMLElement): number; + + /** + * Gets the width of the content of the specified element. The content width does not include borders or padding. + * @param element The element. + * @returns The content width of the element. + **/ + function getContentWidth(element: HTMLElement): number; + + /** + * Gets the leaf-level type or namespace specified by the name parameter. + * @param name The name of the member. + * @param root The root to start in. Defaults to the global object. + * @returns The leaf-level type or namespace in the specified parent namespace. + **/ + function getMember(name: string, root?: any): any; + + /** + * Gets the position of the specified element. + * @param element The element. + * @returns An object that contains the left, top, width and height properties of the element. + **/ + function getPosition(element: HTMLElement): IPosition; + + /** + * Gets the left coordinate of the specified element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative left coordinate. + **/ + function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the top coordinate of the element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative top coordinate. + **/ + function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the height of the element, including its margins. + * @param element The element. + * @returns The height of the element including margins. + **/ + function getTotalHeight(element: HTMLElement): number; + + /** + * Gets the width of the element, including margins. + * @param element The element. + * @returns The width of the element including margins. + **/ + function getTotalWidth(element: HTMLElement): number; + + /** + * Determines whether the specified element has the specified class. + * @param e The element. + * @param name The name of the class. + * @returns true if the element has the class, otherwise false. + **/ + function hasClass(e: HTMLElement, name: string): boolean; + + /** + * Returns a collection with zero or one elements matching the specified id. + * @param id The ID of the element (or elements). + * @returns A collection of elements whose id matches the id parameter. + **/ + function id(id: string): QueryCollection; + + /** + * Calls insertAdjacentHTML on the specified element. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text The text to insert. + **/ + function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; + + /** + * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text Value to be provided to insertAdjacentHTML. + **/ + function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; + + /** + * Attaches the default dispose API wrapping the dispose implementation to the specified element. + * @param element The element to mark as disposable. + * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. + **/ + function markDisposable(element: HTMLElement, disposeImpl: Function): void; + + /** + * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. + * @param func The function to be marked as compatible with declarative processing. + * @returns The input function, marked as compatible with declarative processing. + **/ + function markSupportedForProcessing(func: U): U; + + /** + * Returns a QueryCollection with zero or one elements matching the specified selector query. + * @param query The CSS selector to use. See Selectors for more information. + * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. + * @returns A QueryCollection with zero or one elements matching the specified selector query. + **/ + function query(query: any, element: HTMLElement): QueryCollection; + + /** + * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. + * @param callback A function that executes after the DOMContentLoaded event has occurred. + * @param async If true, the callback should be executed asynchronously. + * @returns A promise that completes after the DOMContentLoaded event has occurred. + **/ + function ready(callback?: Function, async?: boolean): Promise; + + /** + * Removes the specified class from the specified element. + * @param e The element from which to remove the class. + * @param name The name of the class to remove. + * @returns The element. + **/ + function removeClass(e: HTMLElement, name: string): HTMLElement; + + /** + * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. + * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. + * @returns The input value. + **/ + function requireSupportedForProcessing(value: any): any; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTML(element: HTMLElement, text: string): void; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTML(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Configures a logger that writes messages containing the specified tags to the JavaScript console. + * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. + **/ + function startLog(options?: any): void; + + /** + * Removes the WinJS logger that had previously been set up. + **/ + function stopLog(): void; + + /** + * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. + * @param e The element on which to toggle the class. + * @param name The name of the class to toggle. + * @returns The element. + **/ + function toggleClass(e: HTMLElement, name: string): HTMLElement; + + //#endregion Functions + + //#region Interfaces + + interface IPosition { + left: number; + top: number; + width: number; + height: number; + } + + //#endregion Interfaces + +} +/** + * Provides functions and objects for scheduling and managing asynchronous tasks. +**/ +declare module WinJS.Utilities.Scheduler { + //#region Enumerations + + /** + * Represents a priority for a job managed by the Scheduler. + **/ + enum Priority { + /** + * A priority higher than the normal priority level. + **/ + aboveNormal, + /** + * A priority less than the normal priority level. + **/ + belowNormal, + /** + * A high priority. + **/ + high, + /** + * The idle priority for work items. + **/ + idle, + /** + * The highest priority. + **/ + max, + /** + * The lowest priority. + **/ + min, + /** + * The normal priority for work items. + **/ + normal + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Represents a work item that's executed by the Scheduler. + **/ + interface IJob { + //#region Methods + + /** + * Cancels the job. + **/ + cancel(): void; + + /** + * Pauses the job. + **/ + pause(): void; + + /** + * Resumes the job. + **/ + resume(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets a value that indicates whether the job has successfully completed. + **/ + completed: boolean; + + /** + * Gets the unique numeric identifier assigned to the job. + **/ + id: number; + + /** + * Gets or sets the name of the job. + **/ + name: string; + + /** + * Gets or sets the owner of the job. + **/ + owner: IOwnerToken; + + /** + * Gets or sets the priority of the job. + **/ + priority: Priority; + + //#endregion Properties + + } + + /** + * Provides a control mechanism that allows a job to cooperatively yield. This object is passed to your work function when you schedule it. + **/ + interface IJobInfo { + //#region Methods + + /** + * Uses a Promise to determine how long the scheduler should wait before rescheduling the job after it yields. + * @param promise Once the work item yields, the scheduler will wait for this Promise to complete before rescheduling the job. + **/ + setPromise(promise: Promise): void; + + /** + * Specifies the next unit of work to run once this job yields. + * @param work The next unit of work to run once this job yields. + **/ + setWork(work: Function): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the work item associated with this IJobInfo. + **/ + job: IJob; + + /** + * Gets a value that specifies whether the job should yield. + **/ + shouldYield: boolean; + + //#endregion Properties + + } + + /** + * Represents an object that owns jobs. You can use this object to cancel a set of jobs. + **/ + interface IOwnerToken { + //#region Methods + + /** + * Synchronously cancels the job that this token owns, including paused and blocked jobs. + **/ + cancelAll(): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Functions + + /** + * Creates and returns a new IOwnerToken which can be set to the owner property of one or more jobs. + * @returns A new IOwnerToken which can be set to the owner property of one or more jobs. + **/ + function createOwnerToken(): IOwnerToken; + + /** + * Runs the specified callback in a high priority context. + * @param callback The callback to run in a high priority callback. + * @returns The return value of the callback. + **/ + function execHigh(callback: () => U): U; + + /** + * Returns a string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + * @returns A string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + **/ + function retrieveState(): string; + + /** + * Runs jobs in the scheduler without timeslicing until all jobs at the specified priority and higher have executed. + * @param priority The priority to which the scheduler should drain. The default is -15. + * @param name An optional description of the drain request for diagnostics. + * @returns A Promise which completes when the drain has finished. Canceling this Promise cancels the drain request. This Promise will never enter an error state. + **/ + function requestDrain(priority?: Priority, name?: string): Promise; + + /** + * Schedules the specified function to execute asynchronously. + * @param work A function that represents the work item to be scheduled. When called the work item will receive as its first argument an object which allows the work item to ask the scheduler if it should yield cooperatively and if so allows the work item to either provide a function to be run as a continuation or a WinJS.Promise which will when complete provide a function to run as a continuation. Provide these fields for the object: shouldYield, setWork(work), setPromise(promise), job. + * @param priority The priority of the work item. If you don't specify a priority, it defaults to WinJS.Utilities.Scheduler.Priority.normal. + * @param thisArg A "this" instance to be bound to the work item. The default value is null. + * @param name A description of the work item for diagnostics. The default value is an empty string. + * @returns The job instance that represents this work item. + **/ + function schedule(work: (jobInfo: IJobInfo) => void, priority?: Priority, thisArg?: any, name?: string): IJob; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.aboveNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of aboveNormal priority. + **/ + function schedulePromiseAboveNormal(promiseValue?: Promise, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.belowNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of belowNormal priority. + **/ + function schedulePromiseBelowNormal(promiseValue?: Promise, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.high priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of high priority. + **/ + function schedulePromiseHigh(promiseValue?: Promise, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.Idle priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of idle priority. + **/ + function schedulePromiseIdle(promiseValue?: Promise, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.normal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of normal priority. + **/ + function schedulePromiseNormal(promiseValue?: Promise, jobName?: string): Promise; + + //#endregion Functions + +} diff --git a/winrt/winrt.d.ts b/winrt/winrt.d.ts index 881b64ed39..350b43153e 100644 --- a/winrt/winrt.d.ts +++ b/winrt/winrt.d.ts @@ -1,3 +1,8 @@ +// Type definitions for WinRT +// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx +// Definitions by: TypeScript samples +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /* ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use @@ -1768,16 +1773,31 @@ declare module Windows { } export interface IPackage { dependencies: Windows.Foundation.Collections.IVectorView; + description: string; + displayName: string; id: Windows.ApplicationModel.PackageId; installedLocation: Windows.Storage.StorageFolder; + isBundle: boolean; + isDevelopmentMode: boolean; isFramework: boolean; + isResourcePackage: boolean; + logo: Windows.Foundation.Uri; + publisherDisplayName: string; } export class Package implements Windows.ApplicationModel.IPackage { + static current: Windows.ApplicationModel.Package; + dependencies: Windows.Foundation.Collections.IVectorView; + description: string; + displayName: string; id: Windows.ApplicationModel.PackageId; installedLocation: Windows.Storage.StorageFolder; + isBundle: boolean; + isDevelopmentMode: boolean; isFramework: boolean; - static current: Windows.ApplicationModel.Package; + isResourcePackage: boolean; + logo: Windows.Foundation.Uri; + publisherDisplayName: string; } export interface IPackageStatics { current: Windows.ApplicationModel.Package; @@ -11519,13 +11539,78 @@ declare module Windows { snapped, fullScreenPortrait, } - export interface IApplicationViewStatics { - value: Windows.UI.ViewManagement.ApplicationViewState; - tryUnsnap(): boolean; - } + + /** + * Defines an instance of a window (app view) and the information that describes it. + **/ export class ApplicationView { + /** + * Gets the window (app view) for the current app. + **/ + static getForCurrentView(): ApplicationView; + + /** + * Attempts to unsnap a previously snapped app. This call will only succeed when the app is running in the foreground. + **/ + static tryUnsnap(): boolean; + + /** + * Gets the state of the current app view. + **/ static value: Windows.UI.ViewManagement.ApplicationViewState; - static tryUnsnap(): boolean; + + /** + * Indicates whether the app terminates when the last window is closed. + **/ + static terminateAppOnFinalViewClose: boolean; + + /** + * Gets the current orientation of the window (app view) with respect to the display. + **/ + orientation: ApplicationViewOrientation; + + /** + * Gets or sets the displayed title of the window. + **/ + title: string; + + /** + * Gets or sets whether screen capture is enabled for the window (app view). + **/ + isScreenCaptureEnabled: boolean; + + /** + * Gets whether the window (app view) is on the Windows lock screen. + **/ + isOnLockScreen: boolean; + + /** + * Gets whether the window(app view) is full screen or not. + **/ + isFullScreen: boolean; + + /** + * Gets the current ID of the window (app view) . + **/ + id: number; + + /** + * Gets whether the current window (app view) is adjacent to the right edge of the screen. + **/ + adjacentToRightDisplayEdge: boolean; + + /** + * Gets whether the current window (app view) is adjacent to the left edge of the screen. + **/ + adjacentToLeftDisplayEdge: number; + } + + /** + * Defines the set of display orientation modes for a window (app view). + **/ + export enum ApplicationViewOrientation { + landscape, + portrait } export interface IInputPaneVisibilityEventArgs { ensuredFocusedElementInView: boolean; @@ -14650,5 +14735,10 @@ declare module Windows.Foundation { done?(success?: (value: T) => any, error?: (error: any) => any, progress?: (progress: any) => void): void; cancel(): void; + + onerror?(eventInfo: CustomEvent): void; + addEventListener?(type: string, listener: Function, capture?: boolean): void; + dispatchEvent?(type: string, details: any): boolean; + removeEventListener?(eventType: string, listener: Function, capture?: boolean): void; } } diff --git a/xsockets/XSockets-tests.ts b/xsockets/XSockets-tests.ts new file mode 100644 index 0000000000..0b65bf9078 --- /dev/null +++ b/xsockets/XSockets-tests.ts @@ -0,0 +1,61 @@ +/// + +var conn = new XSockets.WebSocket('ws://localhost:4502/Generic'); + +conn.on(XSockets.Events.open,function (clientInfo) { + console.log('Open', clientInfo); +}); + +conn.on(XSockets.Events.onError, function (err) { + console.log('Error', err); +}); + +conn.on(XSockets.Events.close, function () { + console.log('Closed'); +}); + +conn.publish('foo', {text:'Hello Real-Time World'}); + +conn.on('foo', function(data) { + console.log('subscription to foo fired with data = ', data); +}); + +conn.unbind('foo'); + +conn.one('foo', function(data) { + console.log('subscription to foo fired with data = ', data); +}); + +conn.many('foo',4, function(data) { + console.log('subscription to foo fired with data = ', data); +}); + +conn.on('foo', function (data) { + console.log('subscription to foo fired with data = ', data); +}, function (confirmation) { + console.log('subscription confirmed',confirmation); + conn.publish('foo', { text: 'Hello Real-Time World' }); +}); + +conn.publish(XSockets.Events.storage.set, { + Key: "yourKey", + Value: { + Name: "John Doe", + Age: 40, + Likes: ["Beer", "Food", "Coffe"] + } +}); + +conn.publish(XSockets.Events.storage.remove, {Key: 'yourKey'}); + +conn.on(XSockets.Events.storage.getAll, function (data) { + data.forEach(function (item) { + console.log(item); + }); +}); + +conn.publish(XSockets.Events.storage.getAll, {}); + +conn.publish('set_MyProp',{value:'New Value'}); + +conn.on('get_MyProp',function(prop){console.log('Value Of MyProp',prop)}); \ No newline at end of file diff --git a/es6-promises/es6-promises-tests.ts.tscparams b/xsockets/XSockets-tests.ts.tscparams similarity index 100% rename from es6-promises/es6-promises-tests.ts.tscparams rename to xsockets/XSockets-tests.ts.tscparams diff --git a/xsockets/XSockets.d.ts b/xsockets/XSockets.d.ts new file mode 100644 index 0000000000..b09e577a89 --- /dev/null +++ b/xsockets/XSockets.d.ts @@ -0,0 +1,38 @@ +// Type definitions for XSockets.NET 3.0 +// Project: http://xsockets.net/ +// Definitions by: Jeffery Grajkowski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module XSockets { + export class WebSocket { + id: string; + constructor(url: string, subprotocol?: string, settings?: any); + on(event: string, handler: (data: any) => void, confirmation?: (arg: ConfirmationArgument) => void): void; + one(event: string, handler: (data: any) => void, confirmation?: (arg: ConfirmationArgument) => void): void; + many(event: string, times: number, handler: (data: any) => void, confirmation?: (arg: ConfirmationArgument) => void): void; + unbind(event: string): void; + publish(topic: string, data: any): void; + } + export interface ConfirmationArgument { + event: string; + } + export module Events { + export var close: string; + export var onBlob: string; + export var onError: string; + export module bindings { + export var completed: string; + } + export var open: string; + export module pubSub { + export var subscribe: string; + export var unsubscribe: string; + } + export module storage { + export var get: string; + export var getAll: string; + export var remove: string; + export var set: string; + } + } +} diff --git a/youtube/youtube.d.ts b/youtube/youtube.d.ts index b24b130dc2..efb4ba344b 100644 --- a/youtube/youtube.d.ts +++ b/youtube/youtube.d.ts @@ -1,7 +1,7 @@ // Type definitions for YouTube // Project: https://developers.google.com/youtube/ // Definitions by: Daz Wilkin -// Updated by: Ian Obermiller +// Definitions by: Ian Obermiller // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module YT { diff --git a/yui/yui.d.ts b/yui/yui.d.ts index acc448899b..4172cc123e 100644 --- a/yui/yui.d.ts +++ b/yui/yui.d.ts @@ -1,7 +1,7 @@ // Type definitions for yui 3.14.0 -// Project: https://github.com/yui/yui3/blob/release-3.14.0/src/yui/js -// Definitions by: -// Gia Bảo @ Sân Đình +// Project: https://github.com/yui/yui3 +// Definitions by: Gia Bảo @ Sân Đình +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/zepto/zepto.d.ts b/zepto/zepto.d.ts index 241b317cff..eb217e5b98 100644 --- a/zepto/zepto.d.ts +++ b/zepto/zepto.d.ts @@ -1,4 +1,9 @@ -/* +// Type definitions for Zepto 1.0-rc.1 +// Project: http://zeptojs.com/ +// Definitions by: Josh Baldwin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* zepto-1.0rc1.d.ts may be freely distributed under the MIT license. Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/zepto.d.ts diff --git a/zeroclipboard/zeroclipboard.d.ts b/zeroclipboard/zeroclipboard.d.ts index f950487004..847593df8d 100644 --- a/zeroclipboard/zeroclipboard.d.ts +++ b/zeroclipboard/zeroclipboard.d.ts @@ -1,7 +1,7 @@ // Type definitions for ZeroClipboard // Project: https://github.com/jonrohan/ZeroClipboard // Definitions by: Eric J. Smith -// Updated by: Blake Niemyjski +// Definitions by: Blake Niemyjski // Definitions: https://github.com/borisyankov/DefinitelyTyped declare class ZeroClipboard {