Merge remote-tracking branch 'remotes/upstream/master'

Conflicts:
	rx.js/rx.d.ts
This commit is contained in:
Igor Oleinikov
2014-03-07 15:34:40 +04:00
280 changed files with 51729 additions and 21975 deletions

11
.gitignore vendored
View File

@@ -29,8 +29,9 @@ Properties
!_infrastructure/tests/*/*.js
!_infrastructure/tests/*/*/*.js
!_infrastructure/tests/*/*/*/*.js
.idea
*.iml
node_modules
.idea
*.iml
*.js.map
node_modules

1
CONTRIBUTING.md Normal file
View File

@@ -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.

View File

@@ -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))

1
_infrastructure/tests/_ref.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference path="typings/tsd.d.ts" />

File diff suppressed because it is too large Load Diff

View File

@@ -1,598 +1,358 @@
/// <reference path='../../node/node.d.ts' />
/// <reference path='src/exec.ts' />
/// <reference path='src/io.ts' />
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 <string><any> (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);
}
}
}
/// <reference path="typings/tsd.d.ts" />
/// <reference path="src/exec.ts" />
/// <reference path="src/file.ts" />
/// <reference path="src/tsc.ts" />
/// <reference path="src/timer.ts" />
/// <reference path="src/util.ts" />
/// <reference path="src/index.ts" />
/// <reference path="src/changes.ts" />
/// <reference path="src/printer.ts" />
/// <reference path="src/reporter/reporter.ts" />
/// <reference path="src/suite/suite.ts" />
/// <reference path="src/suite/syntax.ts" />
/// <reference path="src/suite/testEval.ts" />
/// <reference path="src/suite/tscParams.ts" />
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<TestResult> {
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<TestResult> {
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<boolean> {
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<boolean> {
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();

View File

@@ -0,0 +1,36 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
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<string[]> {
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);
});
}
}
}

View File

@@ -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();
}
})();

View File

@@ -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<ExecResult> {
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 = <any>Function("return this;").call(null);
if(typeof global.ActiveXObject !== "undefined") {
return new WindowsScriptHostExec();
} else {
return new NodeExec();
}
}();

View File

@@ -0,0 +1,46 @@
/// <reference path="../_ref.d.ts" />
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 + ']';
}
}
}

View File

@@ -0,0 +1,208 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
/// <reference path="util.ts" />
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<void> {
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<void> {
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<void> {
return this.loadReferences(this.files).then(() => {
return this.getMissingReferences();
});
}
private getMissingReferences(): Promise<void> {
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<void> {
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<File> {
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<File[]> {
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<File>(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<File>(result).values().toArray());
});
}
}
}

View File

@@ -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;
})();

View File

@@ -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 <string>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 <boolean>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: <string[]>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
})();

View File

@@ -0,0 +1,281 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
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);
});
});
}
}
}

View File

@@ -0,0 +1,42 @@
/// <reference path="../../_ref.d.ts" />
/// <reference path="../printer.ts" />
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();
}
}
}
}

View File

@@ -0,0 +1,82 @@
/// <reference path="../../runner.ts" />
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<File[]>;
start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void): Promise<ITestSuite>;
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<File[]> {
throw new Error('please implement this method');
}
public start(targetFiles: File[], testCallback: (result: TestResult) => void): Promise<ITestSuite> {
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<TestResult> {
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
});
}
}
}

View File

@@ -0,0 +1,26 @@
/// <reference path="../../runner.ts" />
/// <reference path="../util.ts" />
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<File[]> {
return Promise.cast(files.filter((file) => {
return endDts.test(file.filePathWithName);
}));
}
}
}

View File

@@ -0,0 +1,26 @@
/// <reference path="../../runner.ts" />
/// <reference path="../util.ts" />
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<File[]> {
return Promise.cast(files.filter((file) => {
return endTestDts.test(file.filePathWithName);
}));
}
}
}

View File

@@ -0,0 +1,59 @@
/// <reference path='../../runner.ts' />
/// <reference path='../file.ts' />
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<File[]> {
return Promise.filter(files, (file) => {
return new Promise((resolve) => {
fs.exists(file.filePathWithName + '.tscparams', resolve);
});
});
}
public runTest(targetFile: File): Promise<TestResult> {
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 [];
}
}
}

View File

@@ -0,0 +1,50 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
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 = '<not-started>'
public start() {
this.time = 0;
this.startTime = this.now();
this.asString = '<started>';
}
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 (<string><any> (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'));
}
}
}

View File

@@ -0,0 +1,54 @@
/// <reference path='../_ref.d.ts' />
/// <reference path='../runner.ts' />
/// <reference path='exec.ts' />
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<ExecResult> {
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]);
});
}
}
}

View File

@@ -0,0 +1,40 @@
/// <reference path="../_ref.d.ts" />
module DT {
'use strict';
var fs = require('fs');
var Lazy: LazyJS.LazyStatic = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var referenceTagExp = /<reference[ \t]*path=["']?([\w\.\/_-]*)["']?[ \t]*\/>/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<boolean> {
return new Promise((resolve, reject) => {
fs.exists(target, (bool: boolean) => {
resolve(bool);
});
});
}
}

View File

@@ -0,0 +1,656 @@
// Type definitions for bluebird 1.0.0
// Project: https://github.com/petkaantonov/bluebird
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts
// By: Campredon <https://github.com/fdecampredon/>
// 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<void> (more overloads?)
declare class Promise<R> implements Promise.Thenable<R> {
/**
* 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<R>) => 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<U>(onFulfill: (value: R) => Promise.Thenable<U>, onReject: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => Promise.Thenable<U>, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => U, onReject: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill?: (value: R) => U, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* 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<U>(onReject?: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(onReject?: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(onReject?: (error: any) => U): Promise<U>;
caught<U>(onReject?: (error: any) => U): Promise<U>;
/**
* 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<U>(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise<U>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise<U>;
catch<U>(ErrorClass: Function, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(ErrorClass: Function, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(ErrorClass: Function, onReject: (error: any) => U): Promise<U>;
caught<U>(ErrorClass: Function, onReject: (error: any) => U): Promise<U>;
/**
* 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<U>(onReject: (reason: any) => Promise.Thenable<U>): Promise<U>;
error<U>(onReject: (reason: any) => U): Promise<U>;
/**
* 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<R>): Promise<R>;
finally(handler: (value: R) => R): Promise<R>;
finally(handler: (value: R) => void): Promise<void>;
lastly(handler: (value: R) => Promise.Thenable<R>): Promise<R>;
lastly(handler: (value: R) => R): Promise<R>;
/**
* 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<R>;
/**
* Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
*/
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* 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<R>;
/**
* 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<R>;
/**
* 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<R>;
/**
* 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<R>;
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<R>;
/**
* 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<U>(): Promise<U>;
/**
* 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<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* Create an uncancellable promise based on this promise.
*/
uncancellable(): Promise<R>;
/**
* 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<R>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName].call(obj, arg...);
* });
* </code>
*/
call(propertyName: string, ...args: any[]): Promise<any>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName];
* });
* </code>
*/
// TODO find way to fix get()
// get<U>(propertyName: string): Promise<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* return value;
* });
* </code>
*
* 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<U>(value: U): Promise<U>;
thenReturn<U>(value: U): Promise<U>;
return(): Promise<void>;
thenReturn(): Promise<void>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.return()`.
*
* Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
*/
throw(reason: Error): Promise<R>;
thenThrow(reason: Error): Promise<R>;
/**
* 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<U>(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U>(onFulfill: Function, onReject?: (reason: any) => U): Promise<U>;
/*
// TODO or something like this?
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => U): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise<U>;
*/
/**
* 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<U>(): Promise<U[]>;
/**
* 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<Object>;
/**
* 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<U>(): Promise<Promise.Inspection<U>[]>;
/**
* 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<U>(): Promise<U>;
/**
* 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<U>(count: number): Promise<U[]>;
/**
* 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<U>(): Promise<U>;
/**
* 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<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U>;
map<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => U): Promise<U>;
/**
* 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<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
reduce<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* 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<U>(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<U>;
filter<U>(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise<U>;
}
declare module Promise {
export interface Thenable<R> {
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected?: (error: any) => U): Thenable<U>;
then<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable<U>;
}
export interface Resolver<R> {
/**
* 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<R> {
/**
* 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<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
export function try<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
*/
export function attempt<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
export function attempt<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
/**
* 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<R>(value: Promise.Thenable<R>): Promise<R>;
export function resolve<R>(value: R): Promise<R>;
/**
* Create a promise that is rejected with the given `reason`.
*/
export function reject(reason: any): Promise<void>;
/**
* Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution).
*/
export function defer<R>(): Promise.Resolver<R>;
/**
* 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<R>(value: Promise.Thenable<R>): Promise<R>;
export function cast<R>(value: R): Promise<R>;
/**
* Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
*/
export function bind(thisArg: any): Promise<void>;
/**
* 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<R>(value: Promise.Thenable<R>, ms: number): Promise<R>;
export function delay<R>(value: R, ms: number): Promise<R>;
export function delay(ms: number): Promise<void>;
/**
* 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<R>(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<R>(generatorFunction: Function): Promise<R>;
/**
* 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<R>(values: Thenable<Thenable<R>[]>): Promise<R[]>;
// promise of array with values
export function all<R>(values: Thenable<R[]>): Promise<R[]>;
// array with promises of value
export function all<R>(values: Thenable<R>[]): Promise<R[]>;
// array with values
export function all<R>(values: R[]): Promise<R[]>;
/**
* 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<Object>): Promise<Object>;
// object
export function props(object: Object): Promise<Object>;
/**
* 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<R>(values: Thenable<Thenable<R>[]>): Promise<Promise.Inspection<R>[]>;
// promise of array with values
export function settle<R>(values: Thenable<R[]>): Promise<Promise.Inspection<R>[]>;
// array with promises of value
export function settle<R>(values: Thenable<R>[]): Promise<Promise.Inspection<R>[]>;
// array with values
export function settle<R>(values: R[]): Promise<Promise.Inspection<R>[]>;
/**
* 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<R>(values: Thenable<Thenable<R>[]>): Promise<R>;
// promise of array with values
export function any<R>(values: Thenable<R[]>): Promise<R>;
// array with promises of value
export function any<R>(values: Thenable<R>[]): Promise<R>;
// array with values
export function any<R>(values: R[]): Promise<R>;
/**
* 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<R>(values: Thenable<Thenable<R>[]>): Promise<R>;
// promise of array with values
export function race<R>(values: Thenable<R[]>): Promise<R>;
// array with promises of value
export function race<R>(values: Thenable<R>[]): Promise<R>;
// array with values
export function race<R>(values: R[]): Promise<R>;
/**
* 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<R>(values: Thenable<Thenable<R>[]>, count: number): Promise<R[]>;
// promise of array with values
export function some<R>(values: Thenable<R[]>, count: number): Promise<R[]>;
// array with promises of value
export function some<R>(values: Thenable<R>[], count: number): Promise<R[]>;
// array with values
export function some<R>(values: R[], count: number): Promise<R[]>;
/**
* 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<R>(...values: Thenable<R>[]): Promise<R[]>;
// variadic array with values
export function join<R>(...values: R[]): Promise<R[]>;
/**
* 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<R, U>(values: Thenable<Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => Thenable<U>): Promise<U[]>;
export function map<R, U>(values: Thenable<Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// promise of array with values
export function map<R, U>(values: Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => Thenable<U>): Promise<U[]>;
export function map<R, U>(values: Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// array with promises of value
export function map<R, U>(values: Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => Thenable<U>): Promise<U[]>;
export function map<R, U>(values: Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// array with values
export function map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => Thenable<U>): Promise<U[]>;
export function map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
/**
* 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<R, U>(values: Thenable<Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable<U>, initialValue?: U): Promise<U>;
export function reduce<R, U>(values: Thenable<Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// promise of array with values
export function reduce<R, U>(values: Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable<U>, initialValue?: U): Promise<U>;
export function reduce<R, U>(values: Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with promises of value
export function reduce<R, U>(values: Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable<U>, initialValue?: U): Promise<U>;
export function reduce<R, U>(values: Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with values
export function reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable<U>, initialValue?: U): Promise<U>;
export function reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* 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<R>(values: Thenable<Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => Thenable<boolean>): Promise<R[]>;
export function filter<R>(values: Thenable<Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// promise of array with values
export function filter<R>(values: Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => Thenable<boolean>): Promise<R[]>;
export function filter<R>(values: Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// array with promises of value
export function filter<R>(values: Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => Thenable<boolean>): Promise<R[]>;
export function filter<R>(values: Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// array with values
export function filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => Thenable<boolean>): Promise<R[]>;
export function filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
}
declare module 'bluebird' {
export = Promise;
}

View File

@@ -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 <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module LazyJS {
interface LazyStatic {
<T>(value: T[]):ArrayLikeSequence<T>;
(value: any[]):ArrayLikeSequence<any>;
<T>(value: Object):ObjectLikeSequence<T>;
(value: Object):ObjectLikeSequence<any>;
(value: string):StringLikeSequence;
strict():LazyStatic;
generate<T>(generatorFn: GeneratorCallback<T>, length?: number):GeneratedSequence<T>;
range(to: number):GeneratedSequence<number>;
range(from: number, to: number, step?: number):GeneratedSequence<number>;
repeat<T>(value: T, count?: number):GeneratedSequence<T>;
on<T>(eventType: string):Sequence<T>;
readFile(path: string):StringLikeSequence;
makeHttpRequest(path: string):StringLikeSequence;
}
interface ArrayLike<T> {
length:number;
[index:number]:T;
}
interface Callback {
():void;
}
interface ErrorCallback {
(error: any):void;
}
interface ValueCallback<T> {
(value: T):void;
}
interface GetKeyCallback<T> {
(value: T):string;
}
interface TestCallback<T> {
(value: T):boolean;
}
interface MapCallback<T, U> {
(value: T):U;
}
interface MapStringCallback {
(value: string):string;
}
interface NumberCallback<T> {
(value: T):number;
}
interface MemoCallback<T, U> {
(memo: U, value: T):U;
}
interface GeneratorCallback<T> {
(index: number):T;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface Iterator<T> {
new (sequence: Sequence<T>):Iterator<T>;
current():T;
moveNext():boolean;
}
interface GeneratedSequence<T> extends Sequence<T> {
new(generatorFn: GeneratorCallback<T>, length: number):GeneratedSequence<T>;
length():number;
}
interface AsyncSequence<T> extends SequenceBase<T> {
each(callback: ValueCallback<T>):AsyncHandle<T>;
}
interface AsyncHandle<T> {
cancel():void;
onComplete(callback: Callback):void;
onError(callback: ErrorCallback):void;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module Sequence {
function define(methodName: string[], overrides: Object): Function;
}
interface Sequence<T> extends SequenceBase<T> {
each(eachFn: ValueCallback<T>):Sequence<T>;
}
interface SequenceBase<T> extends SequenceBaser<T> {
first():any;
first(count: number):Sequence<T>;
indexOf(value: any, startIndex?: number):Sequence<T>;
last():any;
last(count: number):Sequence<T>;
lastIndexOf(value: any):Sequence<T>;
reverse():Sequence<T>;
}
interface SequenceBaser<T> {
// TODO improve define() (needs ugly overload)
async(interval: number):AsyncSequence<T>;
chunk(size: number):Sequence<T>;
compact():Sequence<T>;
concat(var_args: T[]):Sequence<T>;
consecutive(length: number):Sequence<T>;
contains(value: T):boolean;
countBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
countBy(propertyName: string): ObjectLikeSequence<T>;
dropWhile(predicateFn: TestCallback<T>): Sequence<T>;
every(predicateFn: TestCallback<T>): boolean;
filter(predicateFn: TestCallback<T>): Sequence<T>;
find(predicateFn: TestCallback<T>): Sequence<T>;
findWhere(properties: Object): Sequence<T>;
flatten(): Sequence<T>;
groupBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
initial(count?: number): Sequence<T>;
intersection(var_args: T[]): Sequence<T>;
invoke(methodName: string): Sequence<T>;
isEmpty(): boolean;
join(delimiter?: string): string;
map<U>(mapFn: MapCallback<T, U>): Sequence<U>;
max(valueFn?: NumberCallback<T>): T;
min(valueFn?: NumberCallback<T>): T;
pluck(propertyName: string): Sequence<T>;
reduce<U>(aggregatorFn: MemoCallback<T, U>, memo?: U): U;
reduceRight<U>(aggregatorFn: MemoCallback<T, U>, memo: U): U;
reject(predicateFn: TestCallback<T>): Sequence<T>;
rest(count?: number): Sequence<T>;
shuffle(): Sequence<T>;
some(predicateFn?: TestCallback<T>): boolean;
sortBy(sortFn: NumberCallback<T>): Sequence<T>;
sortedIndex(value: T): Sequence<T>;
sum(valueFn?: NumberCallback<T>): Sequence<T>;
takeWhile(predicateFn: TestCallback<T>): Sequence<T>;
union(var_args: T[]): Sequence<T>;
uniq(): Sequence<T>;
where(properties: Object): Sequence<T>;
without(var_args: T[]): Sequence<T>;
zip(var_args: T[]): Sequence<T>;
toArray(): T[];
toObject(): Object;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ArrayLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ArrayLikeSequence<T> extends Sequence<T> {
// define()X;
concat(): ArrayLikeSequence<T>;
first(count?: number): ArrayLikeSequence<T>;
get(index: number): T;
length(): number;
map<U>(mapFn: MapCallback<T, U>): ArrayLikeSequence<U>;
pop(): ArrayLikeSequence<T>;
rest(count?: number): ArrayLikeSequence<T>;
reverse(): ArrayLikeSequence<T>;
shift(): ArrayLikeSequence<T>;
slice(begin: number, end?: number): ArrayLikeSequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ObjectLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ObjectLikeSequence<T> extends Sequence<T> {
assign(other: Object): ObjectLikeSequence<T>;
// throws error
//async(): X;
defaults(defaults: Object): ObjectLikeSequence<T>;
functions(): Sequence<T>;
get(property: string): ObjectLikeSequence<T>;
invert(): ObjectLikeSequence<T>;
keys(): Sequence<string>;
omit(properties: string[]): ObjectLikeSequence<T>;
pairs(): Sequence<T>;
pick(properties: string[]): ObjectLikeSequence<T>;
toArray(): T[];
toObject(): Object;
values(): Sequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module StringLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface StringLikeSequence extends SequenceBaser<string> {
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;
}

File diff suppressed because it is too large Load Diff

View File

@@ -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;
}

View File

@@ -0,0 +1,4 @@
/// <reference path="node/node.d.ts" />
/// <reference path="bluebird/bluebird.d.ts" />
/// <reference path="lazy.js/lazy.js.d.ts" />
/// <reference path="optimist/optimist.d.ts" />

View File

@@ -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 <https://github.com/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);
}
}
}

View File

@@ -0,0 +1,242 @@
/// <reference path="angular-protractor.d.ts" />
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');
}

View File

@@ -0,0 +1,868 @@
// Type definitions for Angular Protractor 0.17.0
// Project: https://github.com/angular/protractor
// Definitions by: Bill Armstrong <https://github.com/BillArmstrong>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../selenium-webdriver/selenium-webdriver.d.ts" />
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.
* <p/>
* 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:
* <code><pre>
* var e1 = element.findElement(By.id('foo'));
* var e2 = element.findElement({id:'foo'});
* </pre></code>
* <p/>
* 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.<string>} 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.
* <p/>
* 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:
* <ul>
* <li>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).
* </li>
* <li>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:
* <code>
* 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");
* </code></li>
* <li>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).
* </li>
* </ul>
* <strong>Note:</strong> 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)).
* <p/>
* <em>Warning:</em> 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:
*
* <p>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
*
* <p>Finally, the following commonly mis-capitalized attribute/property names
* are evaluated as expected:
* <ul>
* <li>"class"
* <li>"readonly"
* </ul>
* @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.
*
* <p>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.<string>} 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.
* <p/>
* 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.<string>} 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.
* <p/>
* 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:
* <code><pre>
* var e1 = element.findElement(By.id('foo'));
* var e2 = element.findElement({id:'foo'});
* </pre></code>
* <p/>
* 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.<string>} 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.<name>(<args>)).
*
* @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:
* <span>{{status}}</span>
* var status = element(by.binding('{{status}}'));
*/
binding(bindingDescriptor: string): webdriver.Locator;
/**
* Usage:
* <select ng-model="user" ng-options="user.name for user in users"></select>
* element(by.select("user"));
*/
select(model: string): webdriver.Locator;
/**
* Usage:
* <select ng-model="user" ng-options="user.name for user in users"></select>
* element(by.selectedOption("user"));
*/
selectedOption(model: string): webdriver.Locator;
/**
* @DEPRECATED - use 'model' instead.
* Usage:
* <input ng-model="user" type="text"/>
* element(by.input('user'));
*/
input(model: string): webdriver.Locator;
/**
* Usage:
* <input ng-model="user" type="text"/>
* element(by.model('user'));
*/
model(model: string): webdriver.Locator;
/**
* Usage:
* <textarea ng-model="user"></textarea>
* element(by.textarea("user"));
*/
textarea(model: string): webdriver.Locator;
/**
* Usage:
* <div ng-repeat = "cat in pets">
* <span>{{cat.name}}</span>
* <span>{{cat.age}}</span>
* </div>
*
* // 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 <configuration.js>
*
* 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.
*
* <p>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:
* <code><pre>
* var e1 = driver.findElement(By.id('foo'));
* var e2 = driver.findElement({id:'foo'});
* </pre></code>
*
* <p>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.<string>|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;
}

View File

@@ -0,0 +1,29 @@
/// <reference path="angular-translate.d.ts" />
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);
};
});

View File

@@ -0,0 +1,64 @@
// Type definitions for Angular Translate (pascalprecht.translate module)
// Project: https://github.com/PascalPrecht/angular-translate
// Definitions by: Michel Salib <michelsalib@hotmail.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
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<void>;
storage(): IStorage;
storageKey(): string;
uses(): string;
uses(key: string): ng.IPromise<string>;
}
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;
}
}

View File

@@ -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" }
}
});
});
});

View File

@@ -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 {

View File

@@ -0,0 +1,83 @@
/// <reference path="angularfire.d.ts"/>
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, (<any>$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(_ => {
});
}
]);

41
angularfire/angularfire.d.ts vendored Normal file
View File

@@ -0,0 +1,41 @@
// Type definitions for AngularFire 0.6.0
// Project: http://angularfire.com
// Definitions by: Dénes Harmath <http://github.com/thSoft>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts"/>
/// <reference path="../firebase/firebase.d.ts"/>
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<any>;
}
interface AngularFireObject {
$priority: number;
}
interface AngularFireAuthService {
(firebase: Firebase): AngularFireAuth;
}
interface AngularFireAuth {
$getCurrentUser(): ng.IPromise<any>;
$login(provider: string, options?: Object): ng.IPromise<any>;
$logout(): void;
$createUser(email: string, password: string, noLogin?: boolean): ng.IPromise<any>;
$changePassword(email: string, oldPassword: string, newPassword: string): ng.IPromise<any>;
$removeUser(email: string, password: string): ng.IPromise<any>;
$sendPasswordResetEmail(email: string): ng.IPromise<any>;
}

View File

@@ -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';
}

21
angularjs/angular-animate.d.ts vendored Normal file
View File

@@ -0,0 +1,21 @@
// Type definitions for Angular JS 1.2+ (ngAnimate module)
// Project: http://angularjs.org
// Definitions by: Michel Salib <michelsalib@hotmail.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// 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;
}
}

View File

@@ -1,5 +1,6 @@
// Type definitions for Angular JS 1.2 (ngResource module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/daptiv/DefinitelyTyped
/// <reference path="angular.d.ts" />
@@ -18,19 +19,18 @@ declare module ng.resource {
// that deeply.
///////////////////////////////////////////////////////////////////////////
interface IResourceService {
<T extends IResource<T>, U extends IResourceClass<T>>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): U;
<T extends IResource<T>>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): IResourceClass<T>;
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): IResourceClass<IResource<any>>;
<T, U>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): U;
<T>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): IResourceClass<T>;
}
// 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<T extends IResource<T>> {
interface IResourceClass<T> {
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<T extends IResource<T>> {
interface IResource<T> {
$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<T>;
$resolved : boolean;
}
/** when creating a resource factory via IModule.factory */
interface IResourceServiceFactoryFunction<T extends IResource<T>> {
interface IResourceServiceFactoryFunction<T> {
($resource: ng.resource.IResourceService): IResourceClass<T>;
<U extends IResourceClass<T>>($resource: ng.resource.IResourceService): U;
}
@@ -121,3 +125,10 @@ declare module ng {
factory(name: string, resourceServiceFactoryFunction: ng.resource.IResourceServiceFactoryFunction<any>): IModule;
}
}
interface Array<T>
{
/** the promise of the original server interaction that created this collection. **/
$promise : ng.IPromise<Array<T>>;
$resolved : boolean;
}

View File

@@ -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
/// <reference path="../jquery/jquery.d.ts" />
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;

View File

@@ -1,7 +1,7 @@
/// <reference path="angular.d.ts" />
// 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

View File

@@ -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<any>[]): IPromise<any[]>;
all(promises: {[id: string]: IPromise<any>;}): IPromise<{[id: string]: any}>;
defer<T>(): IDeferred<T>;
reject(reason?: any): IPromise<void>;
when<T>(value: T): IPromise<T>;
@@ -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;

View File

@@ -1,5 +1,5 @@
// Type definitions for Microsoft.Windows.Azure.MobileService.Web-1.0.0
// Project: https://<your-azure-mobileservice-project>.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 <https://github.com/dmorosinotto/>
// 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;

View File

@@ -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 <https://github.com/eirikhm/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -165,4 +165,4 @@ declare module Backbone {
}
}
}

View File

@@ -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;
}

View File

@@ -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 <https://github.com/sumegizoltan>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -30,4 +30,4 @@ declare module BgiFrame {
getIframe(element: HTMLElement): HTMLElement;
prop(n: any): string;
}
}
}

View File

@@ -0,0 +1,25 @@
/// <reference path="bigscreen.d.ts"/>
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);

26
bigscreen/bigscreen.d.ts vendored Normal file
View File

@@ -0,0 +1,26 @@
// Type definitions for BigScreen 2.0.4
// Project: http://brad.is/coding/BigScreen/
// Definitions by: Douglas Eichelberger <https://github.com/dduugg/>
// 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;
}

View File

@@ -1,5 +1,7 @@
/// <reference path="bluebird.d.ts" />
// 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;
});

987
bluebird/bluebird.d.ts vendored
View File

@@ -3,496 +3,499 @@
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// 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:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName].call(obj, arg...);
* });
* </code>
*/
call(propertyName:string, ...args:any[]):Promise;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName];
* });
* </code>
*/
get(propertyName:string):Promise;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* return value;
* });
* </code>
*
* 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:
*
* <code>
* .then(function() {
* throw reason;
* });
* </code>
* 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:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName].call(obj, arg...);
* });
* </code>
*/
call(propertyName: string, ...args: any[]): Promise;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName];
* });
* </code>
*/
get(propertyName: string): Promise;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* return value;
* });
* </code>
*
* 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:
*
* <code>
* .then(function() {
* throw reason;
* });
* </code>
* 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;
}

View File

@@ -1,3 +1,8 @@
// Type definitions for bootstrap.paginator
// Project: https://github.com/lyonlai/bootstrap-paginator
// Definitions by: derikwhittaker <https://github.com/derikwhittaker/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface PaginatorOptions{
@@ -20,4 +25,4 @@ interface PaginatorOptions{
interface JQuery {
bootstrapPaginator(): JQuery;
bootstrapPaginator(options: PaginatorOptions): JQuery;
}
}

View File

@@ -1,4 +1,7 @@
// Type definitions for bootstrap.timepicker
// Project: https://github.com/jdewit/bootstrap-timepicker
// Definitions by: derikwhittaker <https://github.com/derikwhittaker/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
@@ -21,4 +24,4 @@ interface JQuery {
timepicker(methodName: string): JQuery;
timepicker(methodName: string, params: any): JQuery;
timepicker(options: TimeickerOptions): JQuery;
}
}

View File

@@ -107,3 +107,6 @@ interface JQuery {
affix(options?: AffixOptions): JQuery;
}
declare module "bootstrap" {
}

5
box2d/box2dweb.d.ts vendored
View File

@@ -1,3 +1,8 @@
// Type definitions for bootstrap.timepicker
// Project: http://code.google.com/p/box2dweb/
// Definitions by: jbaldwin <https://github.com/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.

View File

@@ -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 = <breeze.EntityType> 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, <Function> 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 = <breeze.EntityType> 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 = <breeze.EntityType> 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;

View File

@@ -1 +0,0 @@
""

20
breeze/breeze.d.ts vendored
View File

@@ -1,10 +1,8 @@
// Type definitions for Breeze 1.4
// Project: http://www.breezejs.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>,
// IdeaBlade <https://github.com/IdeaBlade/Breeze/>
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, IdeaBlade <https://github.com/IdeaBlade/Breeze/>
// 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<EntityByKeyResult>;
fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: boolean): Q.Promise<EntityByKeyResult>;
fetchEntityByKey(entityKey: EntityKey): Q.Promise<EntityByKeyResult>;
fetchEntityByKey(entityKey: EntityKey, checkLocalCacheFirst?: boolean): Q.Promise<EntityByKeyResult>;
fetchMetadata(callback?: (schema: any) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise<any>;
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<any>;
fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise<any>;
fetchMetadata(dataService: string, callback?: (data: any) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise<any>;
fetchMetadata(dataService: DataService, callback?: (data: any) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise<any>;
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;

View File

@@ -1 +0,0 @@
""

View File

@@ -6,28 +6,27 @@
/// <reference path="../node/node.d.ts" />
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 {

View File

@@ -5,7 +5,7 @@
/// <reference path="../node/node.d.ts" />
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;
}

4
chai/chai.d.ts vendored
View File

@@ -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 <https://github.com/jedhunsaker/>
// 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);

View File

@@ -1,3 +1,8 @@
// Type definitions for CodeMirror
// Project: https://github.com/marijnh/CodeMirror
// Definitions by: mihailik <https://github.com/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;

1
cometd/cometd.d.ts vendored
View File

@@ -1,5 +1,6 @@
// Type definitions for CometD 2.5.1
// Project: http://cometd.org
// Definitions by: Derek Cicerone <https://github.com/derekcicerone>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module CometD {

View File

@@ -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 <https://bitbucket.org/drk4>
// Definitions by: Pedro Ferreira <https://bitbucket.org/drk4>, Chris Smith <https://github.com/evilangelist>, Satoru Kimura <https://github.com/gyohk>
// 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;

View File

@@ -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 <https://github.com/giabao>
// Definitions by: Gia Bảo @ Sân Đình <https://github.com/giabao>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var CryptoJS: CryptoJS.CryptoJSStatic;
@@ -107,6 +106,8 @@ declare module CryptoJS{
interface Cipher extends ICipher<Object>{}
interface IStreamCipher<C> extends ICipher<C>{
drop?: number;
createEncryptor(key: WordArray, cfg?: C): IStreamCipher<C>
createDecryptor(key: WordArray, cfg?: C): IStreamCipher<C>
@@ -339,10 +340,7 @@ declare module CryptoJS{
interface PBKDF2 extends EvpKDF{} //PBKDF2 is same as EvpKDF
interface RC4Drop extends RC4, lib.ICipher<IRC4DropCfg>{}
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<CryptoJS.algo.IRC4DropCfg>
RC4Drop: CryptoJS.lib.ICipherHelper<Object>
MD5: CryptoJS.lib.HasherHelper
HmacMD5: CryptoJS.lib.IHasherHmacHelper

4
d3/d3.d.ts vendored
View File

@@ -1,6 +1,6 @@
// Type definitions for d3JS
// Project: http://d3js.org/
// Definitions by: TypeScript samples
// Definitions by: Boris Yankov <https://github.com/borisyankov>
// 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<any>;
forEach(func: (value: any) => void ): void;

View File

@@ -0,0 +1,5 @@
/// <reference path="domready.d.ts" />
domready(function () {
// dom is loaded!
})

6
domready/domready.d.ts vendored Normal file
View File

@@ -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;

32
dot/dot-tests.ts Normal file
View File

@@ -0,0 +1,32 @@
/// <reference path="dot.d.ts" />
var headertmpl = "<h1>{{=it.title}}</h1>";
var pagetmpl = "<h2>Here is the page using a header template< / h2 >\n"
+ "{{#def.header}}\n"
+ "{{=it.name}}";
var customizableheadertmpl = "{{#def.header}}"
+ "\n{{#def.mycustominjectionintoheader || ''} }";
var pagetmplwithcustomizableheader = "<h2>Here is the page with customized header template</h2>\n"
+ "{{##def.mycustominjectionintoheader:\n"
+ " <div>{{=it.title}} is not {{=it.name}}</div>\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);

50
dot/dot.d.ts vendored Normal file
View File

@@ -0,0 +1,50 @@
// Type definitions for doT v1.0.1
// Project: https://github.com/olado/doT
// Definitions by: ZombieHunter <https://github.com/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;
}

View File

@@ -1,5 +1,6 @@
// Type definitions for Dropzone 3.7.1
// Project: http://www.dropzonejs.com/
// Definitions by: Natan Vivo <https://github.com/nvivo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
@@ -74,4 +75,4 @@ declare class Dropzone {
interface JQuery {
dropzone(options: DropzoneOptions): Dropzone;
}
}

666
durandal/durandal.d.ts vendored
View File

@@ -1,3 +1,8 @@
// Type definitions for Durandal 2.0.1
// Project: http://durandaljs.com
// Definitions by: Evan Larsen <https://github.com/evanlarsen/>
// 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<T>(action?: (dfd: JQueryDeferred<T>) => void ): JQueryDeferred<T>;
/**
* 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<any>;
/**
* 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<any[]>;
/**
* 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<any[]>;
/**
* 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<any>;
/**
* 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<HTMLElement>} A promise of the view.
*/
export function createView(viewId: string): JQueryPromise<HTMLElement>;
/**
* 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<HTMLElement>;
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<HTMLElement>;
/**
* 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<HTMLElement>;
/**
* 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<HTMLElement>;
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<any>;
/**
* 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<T>(action?: (dfd: JQueryDeferred<T>) => void): JQueryDeferred<T>;
/**
* 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<any>;
/**
* 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<any[]>;
/**
* 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<any[]>;
/**
* 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<any>;
/**
* 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<HTMLElement>} A promise of the view.
*/
createView(viewId: string): JQueryPromise<HTMLElement>;
/**
* 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<HTMLElement>;
}
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<HTMLElement>;
/**
* 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<HTMLElement>;
/**
* 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<HTMLElement>;
}
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<boolean>;
nav:any;
nav: any;
}
interface DurandalRouteInstruction {
@@ -1656,4 +1678,4 @@ interface DurandalRootRouter extends DurandalRouterBase<DurandalRootRouter> {
* Installs the router's custom ko binding handler.
*/
install(): void;
}
}

View File

@@ -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);
}

121
easeljs/easeljs.d.ts vendored
View File

@@ -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 <https://bitbucket.org/drk4>, Chris Smith <https://github.com/evilangelist>
// 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<number> {
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<ColorMatrix>(...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<ColorMatrix>(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<ColorMatrix>(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<ColorMatrix>(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 {

47
easystarjs/easystarjs-tests.ts Executable file
View File

@@ -0,0 +1,47 @@
/// <reference path="easystarjs.d.ts"/>
// 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
*/

34
easystarjs/easystarjs.d.ts vendored Executable file
View File

@@ -0,0 +1,34 @@
// Type definitions for EasyStar.js 0.1.6
// Project: http://easystarjs.com/
// Definitions by: Magnus Gustafsson <https://github.com/borundin>
// 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;
}
}

15
ember/ember.d.ts vendored
View File

@@ -57,7 +57,7 @@ interface String {
w(): string[];
}
interface Array {
interface Array<T> {
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 { }

View File

@@ -5,10 +5,10 @@
interface Thenable<R> {
then<U>(onFulfill: (value: R) => Thenable<U>, onReject: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfill: (value: R) => Thenable<U>, onReject?: (error: any) => U): Thenable<U>;
then<U>(onFulfill: (value: R) => U, onReject: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfill?: (value: R) => U, onReject?: (error: any) => U): Thenable<U>;
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected?: (error: any) => U): Thenable<U>;
then<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable<U>;
}
@@ -130,4 +130,4 @@ declare module Promise {
* Make a Promise that fulfills when any item fulfills, and rejects if any item rejects.
*/
function race<R>(promises: Promise<R>[]): Promise<R>;
}
}

View File

@@ -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 <https://github.com/teppeis>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped

View File

@@ -1,3 +1,8 @@
// Type definitions for express-validator
// Project: https://github.com/ctavan/express-validator
// Definitions by: Nathan Ridley <https://github.com/axefrog/>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
declare module ExpressValidator {
export interface ValidationError {
msg: string;

10
express/express.d.ts vendored
View File

@@ -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<Router> {
@@ -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;

View File

@@ -1,6 +1,7 @@
// Type definitions for FabricJS
// Project: http://fabricjs.com/
// Definitions by: Oliver Klemencic <https://github.com/oklemencic/>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
/*
USAGE

View File

@@ -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 <http://phyzkit.net/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

View File

@@ -1 +0,0 @@
""

View File

@@ -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 <https://github.com/vbortone/>
// 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;

View File

@@ -1 +0,0 @@
""

6
flight/flight.d.ts vendored
View File

@@ -1,10 +1,10 @@
/// <reference path="../jquery/jquery.d.ts" />
// Type definitions for Flight 1.1.1
// Project: http://flightjs.github.com/flight/
// Definitions by: Jonathan Hedrén <https://github.com/jonathanhedren/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
declare module Flight {
export interface Base {
@@ -235,4 +235,4 @@ declare module Flight {
}
declare var DEBUG: Flight.DebugStatic;
declare var flight: Flight.FlightStatic;
declare var flight: Flight.FlightStatic;

View File

@@ -0,0 +1,15 @@
/// <reference path="ftdomdelegate.d.ts" />
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);

22
ftdomdelegate/ftdomdelegate.d.ts vendored Normal file
View File

@@ -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;
}

View File

@@ -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 <https://github.com/nestalk>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -310,4 +310,4 @@ interface JQuery {
interface JQueryStatic {
fullCalendar: FullCalendar.Calendar;
}
}

View File

@@ -38,7 +38,7 @@
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
var requestAnimationFrame = window.requestAnimationFrame || window["mozRequestAnimationFrame"];
var requestAnimationFrame = window.requestAnimationFrame || (<any>window).mozRequestAnimationFrame;
var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads;
if(getGamepads){
function runAnimation()

View File

@@ -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 <https://github.com/sgtfrankieboy>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

View File

@@ -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 <https://github.com/sgtfrankieboy>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

View File

@@ -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 <https://github.com/RodneyJT>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module google.feeds {
export class feed {

View File

@@ -1,3 +1,8 @@
// Type definitions for Google Visualisation Apis
// Project: https://developers.google.com/chart/
// Definitions by: Dan Ludwig <https://github.com/danludwig>
// 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
}
}
}

View File

@@ -0,0 +1,33 @@
/// <reference path="../googlemaps/google.maps.d.ts" />
/// <reference path="google.maps.infobubble.d.ts" />
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();
}

Some files were not shown because too many files have changed in this diff Show More