Merge remote-tracking branch 'upstream/master'

This commit is contained in:
James Roland Cabresos
2014-08-03 05:39:42 +08:00
711 changed files with 893198 additions and 50725 deletions
+1 -6
View File
@@ -23,12 +23,7 @@ Properties
*~
# test folder
!_infrastructure/*.js
!_infrastructure/tests/*
!_infrastructure/tests/*.js
!_infrastructure/tests/*/*.js
!_infrastructure/tests/*/*/*.js
!_infrastructure/tests/*/*/*/*.js
_infrastructure/tests/build
.idea
*.iml
+1 -1
View File
@@ -1,6 +1,6 @@
language: node_js
node_js:
- 0.10
- "0.10"
notifications:
email: false
+1 -1
View File
@@ -1 +1 @@
Please see the [contribution guide](https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute) for information on how to contribute to this project.
Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) at [definitelytyped.org](http://definitelytyped.org/guides/contributing.html) for information on how to contribute to DefinitelyTyped.
+367
View File
@@ -0,0 +1,367 @@
# Contributors
This is a non-exhaustive list of definitions and their creators. If you created a definition but are not listed then feel free to send a pull request on this file with your name and url.
All definitions files include a header with the author and editors, so at some point this list will be auto-generated.
* [accounting.js](http://josscrowcroft.github.io/accounting.js/) (by [Sergey Gerasimov](https://github.com/gerich-home))
* [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/))
* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga))
* [AngularBootstrapLightbox](https://github.com/compact/angular-bootstrap-lightbox) (by [Roland Zwaga](https://github.com/rolandzwaga))
* [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))
* [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib))
* [Angular Hotkeys](https://github.com/chieffancypants/angular-hotkeys/) (by [Jason Zhao](https://github.com/jlz27))
* [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))
* [asciify](https://github.com/olizilla/asciify) (by [Alan](http://alan.norbauer.com))
* [assert](https://github.com/Jxck/assert) (by [vvakame](https://github.com/vvakame))
* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov))
* [atmosphere](https://github.com/Atmosphere/atmosphere-javascript) (by [Kai Toedter](https://github.com/toedter))
* [Atom](https://atom.io/) (by [vvakame](https://github.com/vvakame))
* [Auth0](https://auth0.com/) (by [Robert McLaws](https://github.com/advancedrei))
* [Auth0.Widget](https://auth0.com/) (by [Robert McLaws](https://github.com/advancedrei))
* [aws-sdk-js](https://github.com/aws/aws-sdk-js) (by [midknight41](https://github.com/midknight41))
* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm))
* [big.js](https://github.com/MikeMcl/big.js) (by [Steve Ognibene](https://github.com/nycdotnet))
* [BigInteger](https://github.com/peterolson/BigInteger.js) (by [Ingo Bürk](https://github.com/Airblader))
* [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))
* [bootstrap-notify](https://github.com/Nijikokun/bootstrap-notify) (by [Blake Niemyjski](https://github.com/niemyjski))
* [bootstrap.datepicker](https://github.com/eternicode/bootstrap-datepicker) (by [Boris Yankov](https://github.com/borisyankov))
* [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby))
* [bucks](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli))
* [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker))
* [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle))
* [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov))
* [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber) and [otiai10](https://github.com/otiai10))
* [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay))
* [CKEditor](https://github.com/ckeditor/ckeditor-dev) (by [Ondrej Sevcik](https://github.com/ondrejsevcik))
* [Clone](https://github.com/pvorb/node-clone) (by [Kieran Simpson](https://github.com/kierans))
* [CodeMirror](http://codemirror.net) (by [François de Campredon](https://github.com/fdecampredon))
* [Commander](http://github.com/visionmedia/commander.js) (by [Marcelo Dezem](https://github.com/mdezem))
* [configstore](http://github.com/yeoman/configstore) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Cordova](http://cordova.apache.org) (by [Microsoft Open Technologies, Inc.](http://msopentech.com/))
* [Cordovarduino](https://github.com/stereolux/cordovarduino) (by [Hendrik Maus](https://github.com/hendrikmaus))
* [Couchbase / Couchnode](https://github.com/couchbase/couchnode) (by [Basarat Ali Syed](https://github.com/basarat))
* [Crossfilter](https://github.com/square/crossfilter) (by [Schmulik Raskin](https://github.com/schmuli))
* [crypto-js](https://code.google.com/p/crypto-js/) (by [Gia Bảo @ Sân Đình](https://github.com/giabao)). @see [cryptojs.d.ts repo](https://github.com/giabao/cryptojs.d.ts)
* [d3.js](http://d3js.org/) (from TypeScript samples)
* [dhtmlxGantt](http://dhtmlx.com/docs/products/dhtmlxGantt) (by [Maksim Kozhukh](http://github.com/mkozhukh))
* [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) (by [Maksim Kozhukh](http://github.com/mkozhukh))
* [diff](https://github.com/kpdecker/jsdiff) (by [vvakame](http://github.com/vvakame))
* [Dock Spawn](http://dockspawn.com) (by [Drew Noakes](https://drewnoakes.com))
* [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))
* [Elm](http://elm-lang.org) (by [Dénes Harmath](https://github.com/thSoft))
* [ember.js](http://emberjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [emissary](https://github.com/atom/emissary) (by [vvakame](https://github.com/vvakame))
* [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/))
* [Esprima](http://esprima.org/) (by [Teppei Sato](https://github.com/teppeis))
* [expect.js](https://github.com/LearnBoost/expect.js) (by [Teppei Sato](https://github.com/teppeis))
* [expectations](https://github.com/spmason/expectations) (by [vvakame](https://github.com/vvakame))
* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Ext JS](http://www.sencha.com/products/extjs/) (by [Brian Kotek](https://github.com/brian428))
* [Fabric.js](http://fabricjs.com/) (by [Oliver Klemencic](https://github.com/oklemencic/))
* [Fancybox](http://fancybox.net/) (by [Boris Yankov](https://github.com/borisyankov))
* [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/))
* [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/))
* [Finch](https://github.com/stoodder/finchjs) (by [David Sichau](https://github.com/DavidSichau/))
* [fingerprintjs](https://github.com/Valve/fingerprintjs) (by [Shunsuke Ohtani](https://github.com/zaneli))
* [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov))
* [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone))
* [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame))
* [FlexSlider](http://www.woothemes.com/flexslider/) (by [Diullei Gomes](https://github.com/Diullei))
* [Flight by Twitter](http://flightjs.github.com/flight/) (by [Jonathan Hedrén](https://github.com/jonathanhedren))
* [flipsnap.js](http://pxgrid.github.io/js-flipsnap/) (by [kubosho_](https://github.com/kubosho), [gsino](https://github.com/gsino), [Mayuki Sawatari](https://github.com/mayuki))
* [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [FPSMeter](http://darsa.in/fpsmeter/) (by [Aaron Lampros](https://github.com/alampros))
* [fs-extra](https://github.com/jprichardson/node-fs-extra) (by [midknight41](https://github.com/midknight41))
* [FullCalendar](http://arshaw.com/fullcalendar/) (by [Neil Stalker](https://github.com/nestalk))
* [Fuse.js](https://github.com/krisk/Fuse) (by [Greg Smith](https://github.com/smrq))
* [Gamepad](http://www.w3.org/TR/gamepad/) (by [Kon](http://phyzkit.net/))
* [GeoJSON](http://geojson.org/) (by [Jake Bruun](https://github.com/cobster))
* [Giraffe](https://github.com/barc/backbone.giraffe) (by [Matt McCray](https://github.com/darthapo))
* [glDatePicker](http://glad.github.com/glDatePicker/) (by [Dániel Tar](https://github.com/qcz))
* [Glob](https://github.com/isaacs/node-glob) (by [vvakame](https://github.com/vvakame))
* [GoJS](http://gojs.net/) (by [Barbara Duckworth](https://github.com/barbara42))
* [Greasemonkey](http://www.greasespot.net/) (by [Kota Saito](https://github.com/kotas))
* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt))
* [gridfs-stream](https://github.com/aheckmann/gridfs-stream) (by [Lior Mualem](https://github.com/liorm))
* [Grunt JS](http://gruntjs.com/) (by [Jeff May](https://github.com/jeffmay), [Basarat Ali Syed](https://github.com/basarat) and [San Chen](https://github.com/bigsan))
* [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))
* [Google Url Shortener](https://developers.google.com/url-shortener/) (by [Frank M](https://github.com/sgtfrankieboy))
* [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [HashMap](https://github.com/flesler/hashmap) (by [Rafał Wrzeszcz](https://wrzasq.pl))
* [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))
* [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ))
* [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))
* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac))
* [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter))
* [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz))
* [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov))
* [Imagemagick](http://github.com/rsms/node-imagemagick) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [interact.js](http://github.com/taye/interact.js) (by [Douglas Eichelberger](https://github.com/dduugg))
* [Ion.RangeSlider](https://github.com/IonDen/ion.rangeSlider) (by [Douglas Eichelberger](https://github.com/dduugg))
* [Ionic-Cordova](https://github.com/driftyco/) (by [Hendrik Maus](https://github.com/hendrikmaus))
* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski))
* [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek))
* [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/))
* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov))
* [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac))
* [jDataView](https://github.com/jDataView/jDataView) (by [Ingvar Stepanyan](https://github.com/RReverser))
* [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel))
* [jQRangeSlider](http://ghusse.github.com/jQRangeSlider) (by [Dániel Tar](https://github.com/qcz))
* [jQuery](http://jquery.com/) (from TypeScript samples)
* [jQuery Mobile](http://jquerymobile.com) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery UI](http://jqueryui.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.Address](https://github.com/asual/jquery-address) (by [Martin Duparc](https://github.com/martinduparc/) and [Tim Klingeleers](https://github.com/mardaneus86/))
* [jQuery.areYouSure](https://github.com/codedance/jquery.AreYouSure) (by [Jon Egerton](https://github.com/jonegerton))
* [jQuery.autosize](http://www.jacklmoore.com/autosize/) (by [Jack Moore](http://www.jacklmoore.com/))
* [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos))
* [jQuery.CLEditor](http://premiumsoftware.net/CLEditor) (by [Jeffery Grajkowski](https://github.com/pushplay))
* [jQuery.clientSideLogging](https://github.com/remybach/jQuery.clientSideLogging/) (by [Diullei Gomes](https://github.com/diullei/))
* [jQuery.Colorbox](http://www.jacklmoore.com/colorbox/) (by [Gidon Junge](https://github.com/gjunge))
* [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.datetimepicker](http://trentrichardson.com/examples/timepicker/) (by [Doug McDonald](https://github.com/dougajmcdonald))
* [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [François de Campredon](https://github.com/fdecampredon))
* [jQuery.Fileupload](https://github.com/blueimp/jQuery-File-Upload/) (by [Rob Alarcon](https://github.com/rob-alarcon))
* [jQuery.Finger](http://ngryman.sh/jquery.finger/) (by [Max Ackley](https://github.com/maxackley))
* [jQuery.Flot](http://www.flotcharts.org/) (by [Matt Burland](https://github.com/burlandm))
* [jQuery.form](http://malsup.com/jquery/form/) (by [François Guillot](http://fguillot.developpez.com/))
* [jQuery.Globalize](https://github.com/jquery/globalize) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.gridster](http://gridster.net) (by [Josh Baldwin](https://github.com/jbaldwin/gridster.d.ts))
* [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/))
* [jQuery.joyride](http://zurb.com/playground/jquery-joyride-feature-tour-plugin) (by [Vincent Bortone](https://github.com/vbortone))
* [jQuery.jSignature](https://github.com/willowsystems/jSignature) (by [Patrick Magee](https://github.com/pjmagee))
* [jQuery.notifyBar](http://www.whoop.ee/posts/2013-04-05-the-resurrection-of-jquery-notify-bar/) (by [Shunsuke Ohtani](https://github.com/zaneli))
* [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/))
* [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/))
* [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb))
* [jQuery.pjax](https://github.com/defunkt/jquery-pjax) (by [Junle Li](https://github.com/lijunle))
* [jQuery.pjax.falsandtru](https://github.com/falsandtru/jquery.pjax.js/) (by [NewNotMoon](http://new.not-moon.net/))
* [jQuery.pnotify](http://sciactive.github.io/pnotify/) (by [David Sichau](https://github.com/DavidSichau/))
* [jQuery.postMessage](http://benalman.com/projects/jquery-postmessage-plugin/) (by [Junle Li](https://github.com/lijunle))
* [jQuery.prettyphoto](https://github.com/scaron/prettyphoto) (by [Paul Gaske](https://github.com/pgaske))
* [jQuery.scrollTo](https://github.com/flesler/jquery.scrollTo) (by [Neil Stalker](https://github.com/nestalk/))
* [jQuery.simplePagination](https://github.com/flaviusmatis/simplePagination.js) (by [Natan Vivo](https://github.com/nvivo/))
* [jquery.superLink](http://james.padolsey.com/demos/plugins/jQuery/superLink/superlink.jquery.js) (by [Blake Niemyjski](https://github.com/niemyjski))
* [jQuery.tile](https://github.com/urin/jquery.tile.js) (by [Shunsuke Ohtani](https://github.com/zaneli))
* [jQuery.timeago](http://timeago.yarp.com/) (by [François Guillot](http://fguillot.developpez.com/))
* [jQuery.Timepicker](http://fgelinas.com/code/timepicker/) (by [Anwar Javed](https://github.com/anwarjaved))
* [jQuery.Timer](http://jchavannes.com/jquery-timer/demo) (by [Joshua Strobl](https://github.com/JoshStrobl))
* [jQuery.TinyCarousel](http://baijs.nl/tinycarousel/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.TinyScrollbar](http://baijs.nl/tinyscrollbar/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.tooltipster](https://github.com/iamceege/tooltipster) (by [Patrick Magee](https://github.com/pjmagee))
* [jQuery.total-storage](https://github.com/Upstatement/jquery-total-storage) (by [Jeremy Brooks](https://github.com/JeremyCBrooks/))
* [jQuery.Transit](http://ricostacruz.com/jquery.transit/) (by [MrBigDog2U](https://github.com/MrBigDog2U))
* [jQuery.Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.Watermark](http://jquery-watermark.googlecode.com) (by [Anwar Javed](https://github.com/anwarjaved))
* [jQuery.base64](https://github.com/yatt/jquery.base64) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki))
* [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds))
* [js-url](https://github.com/websanova/js-url) (by [MIZUNE Pine](https://github.com/pine613))
* [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/))
* [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz))
* [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk))
* [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/))
* [JSON-Pointer](https://www.npmjs.org/package/json-pointer) (by [Bart van der Schoor](https://github.com/Bartvds))
* [JsRender](http://www.jsviews.com/#jsrender) (by [Kensuke MATSUZAKI](https://github.com/zakki))
* [jStorage](http://www.jstorage.info/) (by [Danil Flores](https://github.com/dflor003/))
* [jsTree](http://www.jstree.com/) (by [Adam Pluciński](https://github.com/adaskothebeast))
* [JWPlayer](http://developer.longtailvideo.com/trac/) (by [Martin Duparc](https://github.com/martinduparc/))
* [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/))
* [keymaster.js](https://github.com/madrobby/keymaster) (by [Marting W. Kirst](https://github.com/nitram509/))
* [KineticJS](http://kineticjs.com/) (by [Basarat Ali Syed](https://github.com/basarat))
* [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit))
* [Knockout.js](http://knockoutjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.Amd.Helpers](https://github.com/rniemeyer/knockout-amd-helpers) (by [David Sichau](https://github.com/DavidSichau/))
* [Knockout.DeferredUpdates](https://github.com/mbest/knockout-deferred-updates) (by [Sebastián Galiano](https://github.com/sgaliano))
* [Knockout.ES5](https://github.com/SteveSanderson/knockout-es5) (by [Sebastián Galiano](https://github.com/sgaliano))
* [Knockout.Mapper](https://github.com/LucasLorentz/knockout.mapper) (by [Brandon Meyer](https://github.com/BMeyerKC))
* [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.Postbox](https://github.com/rniemeyer/knockout-postbox) (by [Judah Gabriel Himango](https://github.com/JudahGabriel))
* [Knockout.Rx](https://github.com/Igorbek/knockout.rx) (by [Igor Oleinikov](https://github.com/Igorbek))
* [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig))
* [Knockout.Viewmodel](http://coderenaissance.github.com/knockout.viewmodel/) (by [Oisin Grehan](https://github.com/oising))
* [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising))
* [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov))
* [Lazy.js](http://danieltao.com/lazy.js/) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Leaflet](https://github.com/Leaflet/Leaflet) (by [Vladimir](https://github.com/rgripper))
* [Libxmljs](https://github.com/polotek/libxmljs) (by [François de Campredon](https://github.com/fdecampredon))
* [ladda](https://github.com/hakimel/Ladda) (by [Danil Flores](https://github.com/dflor003))
* [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))
* [Long.js](https://github.com/dcodeIO/Long.js) (by [Toshihide Hara](https://github.com/kerug))
* [lz-string](https://github.com/pieroxy/lz-string) (by [Roman Nikitin](https://github.com/M0ns1gn0r))
* [Mapbox](https://github.com/mapbox/mapbox.js/) (by [Maxime Fabre](https://github.com/anahkiasen))
* [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr))
* [MathJax](https://github.com/mathjax/MathJax) (by [Roland Zwaga](https://github.com/rolandzwaga))
* [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 Ajax](http://msdn.microsoft.com/en-us/library/ee341002(v=vs.100).aspx) (by [Patrick Magee](https://github.com/pjmagee))
* [Microsoft Live Connect](http://msdn.microsoft.com/en-us/library/live/hh243643.aspx) (by [John Vilk](https://github.com/jvilk))
* [Minimatch](https://github.com/isaacs/minimatch) (by [vvakame](https://github.com/vvakame))
* [minimist](https://github.com/substack/minimist) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Mixpanel](https://github.com/mixpanel/mixpanel-js) (by [Knut Eirik Leira Hjelle](https://github.com/hjellek))
* [mixto](https://github.com/atom/mixto) (by [vvakame](https://github.com/vvakame))
* [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))
* [mongoose](http://mongoosejs.com/) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz))
* [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki))
* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov))
* [nconf](https://github.com/flatiron/nconf) (by [Jeff Goddard](https://github.com/jedigo))
* [noble](https://github.com/sandeepmistry/noble) (by [Seon-Wook Park](https://github.com/swook))
* [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici))
* [Node.js](http://nodejs.org/) (from TypeScript samples)
* [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov))
* [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd))
* [node-form](https://github.com/rsamec/form) (by [Roman Samec](https://github.com/rsamec))
* [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame))
* [nodeunit](https://github.com/caolan/nodeunit) (by [Jeff Goddard](https://github.com/jedigo))
* [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown))
* [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov))
* [node-uuid](https://github.com/broofa/node-uuid) (by [Jeff May](https://github.com/jeffmay))
* [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker))
* [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/))
* [object-path](https://github.com/mariocasciaro/object-path) (by [Paulo Cesar](https://github.com/pocesar/))
* [ocLazyLoad](https://github.com/ocombe/ocLazyLoad) (by [Roland Zwaga](https://github.com/rolandzwaga/))
* [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/))
* [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [passport-strategy](https://github.com/jaredhanson/passport-strategy) (by [Lior Mualem](https://github.com/liorm))
* [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame))
* [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin))
* [Parsimmon](https://github.com/jayferd/parsimmon) (by [Bart van der Schoor](https://github.com/Bartvds))
* [PDF.js](https://github.com/mozilla/pdf.js) (by [Josh Baldwin](https://github.com/jbaldwin))
* [PEG.js](http://pegjs.majda.cz/) (by [vvakame](https://github.com/vvakame))
* [Persona](http://www.mozilla.org/en-US/persona) (by [James Frasca](https://github.com/Nycto))
* [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker))
* [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov))
* [PixiJS](https://github.com/GoodBoyDigital/pixi.js) (by [Pedro Casaubon](https://github.com/xperiments))
* [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))
* [ProgressJs](http://usablica.github.io/progress.js/) (by [Shunsuke Ohtani](https://github.com/zaneli))
* [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))
* [Recaptcha.js](https://www.google.com/recaptcha) (by [Brent Jenkins](https://github.com/brentj73))
* [Rickshaw](http://code.shutterstock.com/rickshaw/) (by [Blake Niemyjski](https://github.com/niemyjski))
* [Riot.js](https://github.com/moot/riotjs) (by [vvakame](https://github.com/vvakame))
* [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle))
* [Redis](https://github.com/mranney/node_redis) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [Request](https://github.com/mikeal/request) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [Royalslider](http://dimsemenov.com/plugins/royal-slider/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [Rx.js](http://rx.codeplex.com/) (by [gsino](http://www.codeplex.com/site/users/view/gsino), [Igor Oleinikov](https://github.com/Igorbek), [Carl de Billy](http://carl.debilly.net/), [zoetrope](https://github.com/zoetrope))
* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall))
* [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov))
* [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [rtree.js](https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz))
* [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))
* [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame))
* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u))
* [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) and [Drew Noakes](https://drewnoakes.com))
* [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))
* [sockjs-node](https://github.com/sockjs/sockjs-node) (by [Phil McCloghry-Laing](https://github.com/pmccloghrylaing))
* [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))
* [sqlite3](https://github.com/mapbox/node-sqlite3) (by [Nick Malaguti](https://github.com/nmalaguti))
* [status-bar](https://github.com/atom/status-bar) (by [vvakame](https://github.com/vvakame))
* [stripe](https://stripe.com/) (by [Eric J. Smith](https://github.com/ejsmith/))
* [Store.js](https://github.com/marcuswestin/store.js/) (by [Vincent Bortone](https://github.com/vbortone))
* [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))
* [Swiz](https://github.com/racker/node-swiz) (by [Jeff Goddard](https://github.com/jedigo))
* [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))
* [text-buffer](https://github.com/atom/text-buffer) (by [vvakame](https://github.com/vvakame))
* [text-encoding](https://github.com/inexorabletash/text-encoding) (by [MIZUNE Pine](https://github.com/pine613))
* [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/))
* [TimelineJS](https://github.com/NUKnightLab/TimelineJS) (by [Roland Zwaga](https://github.com/rolandzwaga))
* [timezonecomplete](https://github.com/SpiritIT/timezonecomplete) (by [Rogier Schouten](https://github.com/rogierschouten))
* [Toastr](https://github.com/CodeSeven/toastr) (by [Boris Yankov](https://github.com/borisyankov))
* [trunk8](https://github.com/rviscomi/trunk8) (by [Blake Niemyjski](https://github.com/niemyjski))
* [TweenJS](http://www.createjs.com/#!/TweenJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [tween.js](https://github.com/sole/tween.js/) (by [Adam R. Smith](https://github.com/sunetos))
* [twitter-bootstrap-wizard](https://github.com/VinceG/twitter-bootstrap-wizard) (by [Blake Niemyjski](https://github.com/niemyjski))
* [Twitter Typeahead](http://twitter.github.io/typeahead.js) (by [Ivaylo Gochkov](https://github.com/igochkov))
* [Ubuntu Unity Web API](https://launchpad.net/libunity-webapps) (by [John Vrbanac](https://github.com/jmvrbanac))
* [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))
* [update-notifier](https://github.com/yeoman/update-notifier) (by [vvakame](https://github.com/vvakame))
* [uri-templates](https://github.com/geraintluff/uri-templates) (by [Bart van der Schoor](https://github.com/Bartvds))
* [urlrouter](https://github.com/fengmk2/urlrouter) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [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))
* [Velocity](http://velocityjs.org/) (by [Greg Smith](https://github.com/smrq))
* [Viewporter](https://github.com/zynga/viewporter) (by [Boris Yankov](https://github.com/borisyankov))
* [Vimeo](http://developer.vimeo.com/player/js-api) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [vinyl](https://github.com/wearefractal/vinyl) (by [vvakame](https://github.com/vvakame/))
* [vinyl-fs](https://github.com/wearefractal/vinyl-fs) (by [vvakame](https://github.com/vvakame/))
* [WebRTC](http://dev.w3.org/2011/webrtc/editor/webrtc.html) (by [Ken Smith](https://github.com/smithkl42))
* [websocket](https://github.com/Worlize/WebSocket-Node) (by [Paul Loyd](https://github.com/loyd))
* [WinJS](http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx) (from TypeScript samples)
* [WinRT](http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx) (from TypeScript samples)
* [ws](http://einaros.github.io/ws/) (by [Paul Loyd](https://github.com/loyd))
* [x2js](https://code.google.com/p/x2js/) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [xml2js](https://github.com/Leonidas-from-XIV/node-xml2js) (by [Michel Salib](https://github.com/michelsalib))
* [XRegExp](http://xregexp.com/) (by [Bart van der Schoor](https://github.com/Bartvds))
* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [YouTube Analytics API](https://developers.google.com/youtube/analytics/) (by [Frank M](https://github.com/sgtfrankieboy))
* [YouTube Data API](https://developers.google.com/youtube/v3/) (by [Frank M](https://github.com/sgtfrankieboy/))
* [Zepto.js](http://zeptojs.com/) (by [Josh Baldwin](https://github.com/jbaldwin))
* [Zynga Scroller](https://github.com/zynga/scroller) (by [Boris Yankov](https://github.com/borisyankov))
* [ZeroClipboard](https://github.com/jonrohan/ZeroClipboard) (by [Eric J. Smith](https://github.com/ejsmith))
+368
View File
@@ -0,0 +1,368 @@
/// <reference path="Finch.d.ts" />
function test_Finch() {
Finch.route("Hello/Route", function() {
return console.log("Well hello there! How you doin'?!");
});
Finch.route("Hello/Route/:someId", function(bindings) {
return console.log("Hey! Here's Some Id: " + bindings.someId);
});
Finch.route("Hello/Route/:someId", function(bindings, childCallback) {
console.log("Hey! Here's Some Id: " + bindings.someId);
return childCallback();
});
Finch.route("some/route", {
setup: function(bindings) {
return console.log("Some Route has been setup! :)");
},
load: function(bindings) {
return console.log("Some Route has been loaed! :D");
},
unload: function(bindings) {
return console.log("Some Route has been loaed! :(");
},
teardown: function(bindings) {
return console.log("Some Route has been torndown! :'(");
}
});
Finch.route("some/route", {
setup: function(bindings, childCallback) {
console.log("Some Route has been setup! :)");
return childCallback();
},
load: function(bindings, childCallback) {
console.log("Some Route has been loaed! :D");
return childCallback();
},
unload: function(bindings, childCallback) {
console.log("Some Route has been loaed! :(");
return childCallback();
},
teardown: function(bindings, childCallback) {
console.log("Some Route has been torndown! :'(");
return childCallback();
}
});
Finch.call("Some/Route");
Finch.route("Some/Route", function() {
return Finch.observe("hello", "foo", function(hello: any, foo: string) {
return console.log("" + hello + " and " + foo);
});
});
Finch.route("Some/Route", function() {
return Finch.observe(["hello", "foo"], function(hello: any, foo: any) {
return console.log("" + hello + " and " + foo);
});
});
Finch.route("Some/Route", function(bindings) {
return Finch.observe(function(params) {
});
});
Finch.navigate("Some/Route");
Finch.navigate("Some/Route", {
hello: 'world',
foo: 'bar'
});
Finch.navigate("Some/Route", {
foo: 'bar'
}, true);
Finch.navigate("Some/Route", true);
Finch.navigate({
hello: 'world2',
wow: 'wee'
});
Finch.navigate({
foo: 'bar',
wow: 'wee!!!'
});
Finch.navigate({
hello: 'world2'
}, true);
Finch.listen();
Finch.ignore();
Finch.abort();
//test from Finch
Finch.call("/foo/bar");
Finch.call("/foo/bar/123");
Finch.call("/foo/bar/123");
Finch.call("/foo/bar/123?x=Hello&y=World");
Finch.call("/foo/baz/456");
Finch.call("/quux/789?band=Sunn O)))&genre=Post-Progressive Fridgecore");
Finch.call("/foo/bar/baz");
Finch.call("/foo/bar/quux");
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/foo");
Finch.call("/foo");
Finch.call("/");
Finch.call("/");
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/foo/bar?baz=quux");
Finch.call("/foo/bar?baz=xyzzy");
var cb: any;
Finch.route("foo", {
setup: cb.setup_foo = this.stub(),
load: cb.load_foo = this.stub(),
unload: cb.unload_foo = this.stub(),
teardown: cb.teardown_foo = this.stub()
});
Finch.route("[foo]/bar", {
setup: cb.setup_foo_bar = this.stub(),
load: cb.load_foo_bar = this.stub(),
unload: cb.unload_foo_bar = this.stub(),
teardown: cb.teardown_foo_bar = this.stub()
});
Finch.route("[foo/bar]/:id", {
setup: cb.setup_foo_bar_id = this.stub(),
load: cb.load_foo_bar_id = this.stub(),
unload: cb.unload_foo_bar_id = this.stub(),
teardown: cb.teardown_foo_bar_id = this.stub()
});
Finch.route("[foo]/baz", {
setup: cb.setup_foo_baz = this.stub(),
load: cb.load_foo_baz = this.stub(),
unload: cb.unload_foo_baz = this.stub(),
teardown: cb.teardown_foo_baz = this.stub()
});
Finch.route("[foo/baz]/:id", {
setup: cb.setup_foo_baz_id = this.stub(),
load: cb.load_foo_baz_id = this.stub(),
unload: cb.unload_foo_baz_id = this.stub(),
teardown: cb.teardown_foo_baz_id = this.stub()
});
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/foo");
Finch.call("/foo/bar/123?x=abc");
Finch.call("/foo/bar/456?x=aaa&y=zzz");
Finch.call("/foo/bar/456?x=bbb&y=zzz");
Finch.call("/foo/bar/456?y=zzz&x=bbb");
Finch.call("/foo/baz/789");
Finch.call("/foo/baz/abc?term=Hello");
Finch.call("/foo/baz/abc?term=World");
Finch.route("bar", this.stub());
Finch.call("/foo");
Finch.call("/bar");
Finch.route("/", function() {
});
Finch.route("[/]home", function() {
});
Finch.route("[/home]/news", {
setup: function() {
},
load: function() {
},
unload: function() {
return true;
},
teardown: function() {
return false;
}
});
Finch.route("/foo", {
setup: function() {
return true;
},
load: function() {
return true;
},
unload: function() {
},
teardown: function() {
}
});
Finch.route("[/]bar", {
setup: function() {
},
load: function() {
},
unload: function() {
},
teardown: function() {
}
});
Finch.call("/bar");
Finch.call("/home/news");
Finch.call("/foo");
Finch.call("/home/news");
Finch.call("/bar");
Finch.route("baz", this.stub());
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/baz");
Finch.route("/home", {
setup: function(bindings, next) {
return next();
},
load: function(bindings, next) {
return next();
},
unload: function(bindings, next) {
return next();
},
teardown: function(bindings, next) {
return next();
}
});
Finch.route("[/home]/news", {
setup: function(bindings, next) {
return next();
},
load: function(bindings, next) {
return next();
},
unload: function(bindings, next) {
return next();
},
teardown: function(bindings, next) {
return next();
}
});
Finch.call("/home");
Finch.call("/home/news");
Finch.call("/foo");
Finch.route("/", function(bindings) {
return Finch.observe(["x"], function(x) {
});
});
Finch.call("/?x=123");
Finch.call("/?x=123.456");
Finch.call("/?x=true");
Finch.call("/?x=false");
Finch.call("/?x=stuff");
Finch.options({
CoerceParameterTypes: true
});
Finch.call("/?x=123");
Finch.call("/?x=123.456");
Finch.call("/?x=true");
Finch.call("/?x=false");
Finch.call("/?x=stuff");
Finch.route("/:x", function(_arg) {
});
Finch.call("/123");
Finch.call("/123.456");
Finch.call("/true");
Finch.call("/false");
Finch.call("/stuff");
Finch.options({
CoerceParameterTypes: true
});
Finch.call("/123");
Finch.call("/123.456");
Finch.call("/true");
Finch.call("/false");
Finch.call("/stuff");
Finch.navigate("/home");
Finch.navigate("/home/news");
Finch.navigate("/home");
Finch.navigate("/home", {
foo: "bar"
});
Finch.navigate("/home", {
hello: "world"
});
Finch.navigate({
foos: "bars"
});
Finch.navigate({
foos: "baz"
});
Finch.navigate({
hello: "world"
}, true);
Finch.navigate({
foos: null
}, true);
Finch.navigate("/home/news", true);
Finch.navigate("/hello world", {});
Finch.navigate("/hello world", {
foo: "bar bar"
});
Finch.navigate({
foo: "baz baz"
});
Finch.navigate({
hello: 'world world'
}, true);
Finch.navigate("/home?foo=bar", {
hello: "world"
});
Finch.navigate("/home?foo=bar", {
hello: "world",
foo: "baz"
});
Finch.navigate("/home?foo=bar", {
hello: "world",
free: "bird"
});
Finch.navigate("#/home", true);
Finch.navigate("#/home");
Finch.navigate("#/home/news", {
free: "birds",
hello: "worlds"
});
Finch.navigate("#/home/news", {
foo: "bar"
}, true);
Finch.navigate("/home/news");
Finch.navigate("../");
Finch.navigate("./");
Finch.navigate("./news");
Finch.navigate("/home/news/article");
Finch.navigate("../../account");
Finch.listen();
Finch.ignore();
Finch.route("/home", function(bindings, continuation) {
});
Finch.route("/foo", function(bindings, continuation) {
});
Finch.call("home");
Finch.call("foo");
Finch.abort();
Finch.call("foo");
Finch.route("/", {
'setup': cb.slash_setup = this.stub(),
'load': cb.slash_load = this.stub(),
'unload': cb.slash_unload = this.stub(),
'teardown': cb.slash_teardown = this.stub()
});
Finch.route("[/]users/profile", {
'setup': cb.profile_setup = this.stub(),
'load': cb.profile_load = this.stub(),
'unload': cb.profile_unload = this.stub(),
'teardown': cb.profile_teardown = this.stub()
});
Finch.route("[/]:page", {
'setup': cb.page_setup = this.stub(),
'load': cb.page_load = this.stub(),
'unload': cb.page_unload = this.stub(),
'teardown': cb.page_teardown = this.stub()
});
Finch.call("/users");
}
+47
View File
@@ -0,0 +1,47 @@
// Type definitions for Finch 0.5.13
// Project: https://github.com/stoodder/finchjs
// Definitions by: David Sichau <https://github.com/DavidSichau>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface FinchCallback {
(bindings?: any, childCallback? : () => void): any;
}
interface ExpandedCallback {
setup?: FinchCallback;
load?: FinchCallback;
unload?: FinchCallback;
teardown?: FinchCallback;
}
interface ObserveCallback {
(...args: any[]): string;
}
interface FinchOptions {
CoerceParameterTypes?: boolean;
}
interface FinchStatic {
route(route: string, callback: FinchCallback): void;
route(route: string, callbacks: ExpandedCallback): void;
call( uri: string ): void;
observe(argN: string[], callback: (params: ObserveCallback ) => void): void;
observe(callback: (params: ObserveCallback) => void): void;
observe(...args: any[]): void;
navigate(uri:string, queryParams?:any, doUpdate?:boolean ): void;
navigate(uri:string, doUpdate:boolean ): void;
navigate(queryParams:any, doUpdate?:boolean ): void;
listen(): boolean;
ignore(): boolean;
abort(): void;
options(options: FinchOptions): void;
}
declare var Finch: FinchStatic;
declare module "finch" {
export = Finch;
}
+15
View File
@@ -0,0 +1,15 @@
/// <reference path="JSONStream.d.ts" />
import json = require('JSONStream');
var read: NodeJS.ReadableStream;
var write: NodeJS.WritableStream;
read = read.pipe(json.parse('*'));
read = read.pipe(json.parse(['foo/*', 'bar/*']));
read = json.stringify();
read = json.stringify('{', ',', '}');
read = json.stringifyObject();
read = json.stringifyObject('{', ',', '}');
+22
View File
@@ -0,0 +1,22 @@
// Type definitions for JSONStream v0.8.0
// Project: http://github.com/dominictarr/JSONStream
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'JSONStream' {
export interface Options {
recurse: boolean;
}
export function parse(pattern: any): NodeJS.ReadWriteStream;
export function parse(patterns: any[]): NodeJS.ReadWriteStream;
export function stringify(): NodeJS.ReadWriteStream;
export function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream;
export function stringifyObject(): NodeJS.ReadWriteStream;
export function stringifyObject(open: string, sep: string, close: string): NodeJS.ReadWriteStream;
}
Executable → Regular
+28 -304
View File
@@ -1,317 +1,41 @@
DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped)
===============
# DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped)
The repository for *high quality* TypeScript type definitions.
> The repository for *high quality* TypeScript type definitions.
For more information see the [definitelytyped.org](http://definitelytyped.org) website.
## Usage
Usage
-----
Include a line like this:
```
```typescript
/// <reference path="jquery.d.ts" />
```
[TypeScript Directory: tools, libraries, projects and learning resources](https://github.com/DefinitelyTyped/typescript-directory)
## Contributions
Contributor Guidelines
----------------------
DefinitelyTyped only works because of contributions by users like you!
See the section: [How to contribute](https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute)
Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) on how to contribute to DefinitelyTyped.
Other means to get the definitions
----------------------------------
## How to get the definitions
* Directly from the Github repos
* [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped)
* [TypeScript Definition package manager](https://github.com/DefinitelyTyped/tsd)
* [TypeScript Definition manager](https://github.com/DefinitelyTyped/tsd)
List of Definitions
-------------------
* [accounting.js](http://josscrowcroft.github.io/accounting.js/) (by [Sergey Gerasimov](https://github.com/gerich-home))
* [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))
* [asciify](https://github.com/olizilla/asciify) (by [Alan](http://alan.norbauer.com))
* [assert](https://github.com/Jxck/assert) (by [vvakame](https://github.com/vvakame))
* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov))
* [Atom](https://atom.io/) (by [vvakame](https://github.com/vvakame))
* [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))
* [bootstrap-notify](https://github.com/Nijikokun/bootstrap-notify) (by [Blake Niemyjski](https://github.com/niemyjski))
* [bootstrap.datepicker](https://github.com/eternicode/bootstrap-datepicker) (by [Boris Yankov](https://github.com/borisyankov))
* [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby))
* [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker))
* [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle))
* [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov))
* [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber) and [otiai10](https://github.com/otiai10))
* [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay))
* [CKEditor](https://github.com/ckeditor/ckeditor-dev) (by [Ondrej Sevcik](https://github.com/ondrejsevcik))
* [Clone](https://github.com/pvorb/node-clone) (by [Kieran Simpson](https://github.com/kierans))
* [CodeMirror](http://codemirror.net) (by [François de Campredon](https://github.com/fdecampredon))
* [Commander](http://github.com/visionmedia/commander.js) (by [Marcelo Dezem](https://github.com/mdezem))
* [configstore](http://github.com/yeoman/configstore) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Cordova](http://cordova.apache.org) (by [Microsoft Open Technologies, Inc.](http://msopentech.com/))
* [Couchbase / Couchnode](https://github.com/couchbase/couchnode) (by [Basarat Ali Syed](https://github.com/basarat))
* [Crossfilter](https://github.com/square/crossfilter) (by [Schmulik Raskin](https://github.com/schmuli))
* [crypto-js](https://code.google.com/p/crypto-js/) (by [Gia Bảo @ Sân Đình](https://github.com/giabao)). @see [cryptojs.d.ts repo](https://github.com/giabao/cryptojs.d.ts)
* [d3.js](http://d3js.org/) (from TypeScript samples)
* [dhtmlxGantt](http://dhtmlx.com/docs/products/dhtmlxGantt) (by [Maksim Kozhukh](http://github.com/mkozhukh))
* [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) (by [Maksim Kozhukh](http://github.com/mkozhukh))
* [diff](https://github.com/kpdecker/jsdiff) (by [vvakame](http://github.com/vvakame))
* [Dock Spawn](http://dockspawn.com) (by [Drew Noakes](https://drewnoakes.com))
* [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))
* [emissary](https://github.com/atom/emissary) (by [vvakame](https://github.com/vvakame))
* [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/))
* [expect.js](https://github.com/LearnBoost/expect.js) (by [Teppei Sato](https://github.com/teppeis))
* [expectations](https://github.com/spmason/expectations) (by [vvakame](https://github.com/vvakame))
* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Ext JS](http://www.sencha.com/products/extjs/) (by [Brian Kotek](https://github.com/brian428))
* [Fabric.js](http://fabricjs.com/) (by [Oliver Klemencic](https://github.com/oklemencic/))
* [Fancybox](http://fancybox.net/) (by [Boris Yankov](https://github.com/borisyankov))
* [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/))
* [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/))
* [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov))
* [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone))
* [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame))
* [FlexSlider](http://www.woothemes.com/flexslider/) (by [Diullei Gomes](https://github.com/Diullei))
* [Flight by Twitter](http://flightjs.github.com/flight/) (by [Jonathan Hedrén](https://github.com/jonathanhedren))
* [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [FPSMeter](http://darsa.in/fpsmeter/) (by [Aaron Lampros](https://github.com/alampros))
* [FullCalendar](http://arshaw.com/fullcalendar/) (by [Neil Stalker](https://github.com/nestalk))
* [Gamepad](http://www.w3.org/TR/gamepad/) (by [Kon](http://phyzkit.net/))
* [Giraffe](https://github.com/barc/backbone.giraffe) (by [Matt McCray](https://github.com/darthapo))
* [glDatePicker](http://glad.github.com/glDatePicker/) (by [Dániel Tar](https://github.com/qcz))
* [Glob](https://github.com/isaacs/node-glob) (by [vvakame](https://github.com/vvakame))
* [GoJS](http://gojs.net/) (by [Barbara Duckworth](https://github.com/barbara42))
* [Greasemonkey](http://www.greasespot.net/) (by [Kota Saito](https://github.com/kotas))
* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt))
* [Grunt JS](http://gruntjs.com/) (by [Jeff May](https://github.com/jeffmay), [Basarat Ali Syed](https://github.com/basarat) and [San Chen](https://github.com/bigsan))
* [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))
* [Google Url Shortener](https://developers.google.com/url-shortener/) (by [Frank M](https://github.com/sgtfrankieboy))
* [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [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))
* [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ))
* [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))
* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac))
* [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter))
* [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz))
* [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov))
* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski))
* [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek))
* [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/))
* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov))
* [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac))
* [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel))
* [jQRangeSlider](http://ghusse.github.com/jQRangeSlider) (by [Dániel Tar](https://github.com/qcz))
* [jQuery](http://jquery.com/) (from TypeScript samples)
* [jQuery Mobile](http://jquerymobile.com) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery UI](http://jqueryui.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.Address](https://github.com/asual/jquery-address) (by [Martin Duparc](https://github.com/martinduparc/))
* [jQuery.areYouSure](https://github.com/codedance/jquery.AreYouSure) (by [Jon Egerton](https://github.com/jonegerton))
* [jQuery.autosize](http://www.jacklmoore.com/autosize/) (by [Jack Moore](http://www.jacklmoore.com/))
* [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos))
* [jQuery.CLEditor](http://premiumsoftware.net/CLEditor) (by [Jeffery Grajkowski](https://github.com/pushplay))
* [jQuery.clientSideLogging](https://github.com/remybach/jQuery.clientSideLogging/) (by [Diullei Gomes](https://github.com/diullei/))
* [jQuery.Colorbox](http://www.jacklmoore.com/colorbox/) (by [Gidon Junge](https://github.com/gjunge))
* [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.datetimepicker](http://trentrichardson.com/examples/timepicker/) (by [Doug McDonald](https://github.com/dougajmcdonald))
* [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))
* [jQuery.form](http://malsup.com/jquery/form/) (by [François Guillot](http://fguillot.developpez.com/))
* [jQuery.Globalize](https://github.com/jquery/globalize) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.gridster](http://gridster.net) (by [Josh Baldwin](https://github.com/jbaldwin/gridster.d.ts))
* [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/))
* [jQuery.joyride](http://zurb.com/playground/jquery-joyride-feature-tour-plugin) (by [Vincent Bortone](https://github.com/vbortone))
* [jQuery.jSignature] (https://github.com/willowsystems/jSignature) (by [Patrick Magee](https://github.com/pjmagee))
* [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/))
* [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb))
* [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/))
* [jQuery.pnotify](http://sciactive.github.io/pnotify/ (by [David Sichau](https://github.com/DavidSichau/))
* [jQuery.scrollTo](https://github.com/flesler/jquery.scrollTo) (by [Neil Stalker](https://github.com/nestalk/))
* [jQuery.simplePagination](https://github.com/flaviusmatis/simplePagination.js) (by [Natan Vivo](https://github.com/nvivo/))
* [jquery.superLink](http://james.padolsey.com/demos/plugins/jQuery/superLink/superlink.jquery.js) (by [Blake Niemyjski](https://github.com/niemyjski))
* [jQuery.timeago](http://timeago.yarp.com/) (by [François Guillot](http://fguillot.developpez.com/))
* [jQuery.Timepicker](http://fgelinas.com/code/timepicker/) (by [Anwar Javed](https://github.com/anwarjaved))
* [jQuery.Timer](http://jchavannes.com/jquery-timer/demo) (by [Joshua Strobl](https://github.com/JoshStrobl))
* [jQuery.TinyCarousel](http://baijs.nl/tinycarousel/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.TinyScrollbar](http://baijs.nl/tinyscrollbar/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.tooltipster] (https://github.com/iamceege/tooltipster) (by [Patrick Magee](https://github.com/pjmagee))
* [jQuery.Transit](http://ricostacruz.com/jquery.transit/) (by [MrBigDog2U](https://github.com/MrBigDog2U))
* [jQuery.Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.Watermark](http://jquery-watermark.googlecode.com) (by [Anwar Javed](https://github.com/anwarjaved))
* [jQuery.base64](https://github.com/yatt/jquery.base64) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki))
* [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds))
* [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/))
* [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz))
* [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk))
* [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/))
* [JSON-Pointer](https://www.npmjs.org/package/json-pointer) (by [Bart van der Schoor](https://github.com/Bartvds))
* [JsRender](http://www.jsviews.com/#jsrender) (by [Kensuke MATSUZAKI](https://github.com/zakki))
* [jStorage](http://www.jstorage.info/) (by [Danil Flores](https://github.com/dflor003/))
* [JWPlayer](http://developer.longtailvideo.com/trac/) (by [Martin Duparc](https://github.com/martinduparc/))
* [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/))
* [KineticJS](http://kineticjs.com/) (by [Basarat Ali Syed](https://github.com/basarat))
* [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit))
* [Knockout.js](http://knockoutjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.DeferredUpdates](https://github.com/mbest/knockout-deferred-updates) (by [Sebastián Galiano](https://github.com/sgaliano))
* [Knockout.ES5](https://github.com/SteveSanderson/knockout-es5) (by [Sebastián Galiano](https://github.com/sgaliano))
* [Knockout.Mapper](https://github.com/LucasLorentz/knockout.mapper) (by [Brandon Meyer](https://github.com/BMeyerKC))
* [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.Postbox](https://github.com/rniemeyer/knockout-postbox) (by [Judah Gabriel Himango](https://github.com/JudahGabriel))
* [Knockout.Rx](https://github.com/Igorbek/knockout.rx) (by [Igor Oleinikov](https://github.com/Igorbek))
* [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig))
* [Knockout.Viewmodel](http://coderenaissance.github.com/knockout.viewmodel/) (by [Oisin Grehan](https://github.com/oising))
* [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising))
* [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov))
* [Lazy.js](http://danieltao.com/lazy.js/) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Leaflet](https://github.com/Leaflet/Leaflet) (by [Vladimir](https://github.com/rgripper))
* [Libxmljs](https://github.com/polotek/libxmljs) (by [François de Campredon](https://github.com/fdecampredon))
* [ladda](https://github.com/hakimel/Ladda) (by [Danil Flores](https://github.com/dflor003))
* [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))
* [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))
* [Minimatch](https://github.com/isaacs/minimatch) (by [vvakame](https://github.com/vvakame))
* [minimist](https://github.com/substack/minimist) (by [Bart van der Schoor](https://github.com/Bartvds))
* [mixto](https://github.com/atom/mixto) (by [vvakame](https://github.com/vvakame))
* [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))
* [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz))
* [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki))
* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov))
* [Node.js](http://nodejs.org/) (from TypeScript samples)
* [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov))
* [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd))
* [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame))
* [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown))
* [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov))
* [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker))
* [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/))
* [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame))
* [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin))
* [Parsimmon](https://github.com/jayferd/parsimmon) (by [Bart van der Schoor](https://github.com/Bartvds))
* [PDF.js](https://github.com/mozilla/pdf.js) (by [Josh Baldwin](https://github.com/jbaldwin))
* [PEG.js](http://pegjs.majda.cz/) (by [vvakame](https://github.com/vvakame))
* [Persona](http://www.mozilla.org/en-US/persona) (by [James Frasca](https://github.com/Nycto))
* [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker))
* [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov))
* [PixiJS](https://github.com/GoodBoyDigital/pixi.js) (by [Pedro Casaubon](https://github.com/xperiments))
* [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))
* [Riot.js](https://github.com/moot/riotjs) (by [vvakame](https://github.com/vvakame))
* [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle))
* [Royalslider](http://dimsemenov.com/plugins/royal-slider/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [Rx.js](http://rx.codeplex.com/) (by [gsino](http://www.codeplex.com/site/users/view/gsino), [Igor Oleinikov](https://github.com/Igorbek), [Carl de Billy](http://carl.debilly.net/), [zoetrope](https://github.com/zoetrope))
* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall))
* [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov))
* [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))
* [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame))
* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u))
* [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) and [Drew Noakes](https://drewnoakes.com))
* [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))
* [stripe](https://stripe.com/) (by [Eric J. Smith](https://github.com/ejsmith/))
* [Store.js](https://github.com/marcuswestin/store.js/) (by [Vincent Bortone](https://github.com/vbortone))
* [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/))
* [Toastr](https://github.com/CodeSeven/toastr) (by [Boris Yankov](https://github.com/borisyankov))
* [trunk8](https://github.com/rviscomi/trunk8) (by [Blake Niemyjski](https://github.com/niemyjski))
* [TweenJS](http://www.createjs.com/#!/TweenJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [tween.js](https://github.com/sole/tween.js/) (by [Adam R. Smith](https://github.com/sunetos))
* [twitter-bootstrap-wizard](https://github.com/VinceG/twitter-bootstrap-wizard) (by [Blake Niemyjski](https://github.com/niemyjski))
* [Twitter Typeahead](http://twitter.github.io/typeahead.js) (by [Ivaylo Gochkov](https://github.com/igochkov))
* [Ubuntu Unity Web API](https://launchpad.net/libunity-webapps) (by [John Vrbanac](https://github.com/jmvrbanac))
* [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))
* [update-notifier](https://github.com/yeoman/update-notifier) (by [vvakame](https://github.com/vvakame))
* [uri-templates](https://github.com/geraintluff/uri-templates) (by [Bart van der Schoor](https://github.com/Bartvds))
* [urlrouter](https://github.com/fengmk2/urlrouter) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [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))
* [Vimeo](http://developer.vimeo.com/player/js-api) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [WebRTC](http://dev.w3.org/2011/webrtc/editor/webrtc.html) (by [Ken Smith](https://github.com/smithkl42))
* [websocket](https://github.com/Worlize/WebSocket-Node) (by [Paul Loyd](https://github.com/loyd))
* [WinJS](http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx) (from TypeScript samples)
* [WinRT](http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx) (from TypeScript samples)
* [ws](http://einaros.github.io/ws/) (by [Paul Loyd](https://github.com/loyd))
* [XRegExp](http://xregexp.com/) (by [Bart van der Schoor](https://github.com/Bartvds))
* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [YouTube Analytics API](https://developers.google.com/youtube/analytics/) (by [Frank M](https://github.com/sgtfrankieboy))
* [YouTube Data API](https://developers.google.com/youtube/v3/) (by [Frank M](https://github.com/sgtfrankieboy/))
* [Zepto.js](http://zeptojs.com/) (by [Josh Baldwin](https://github.com/jbaldwin))
* [Zynga Scroller](https://github.com/zynga/scroller) (by [Boris Yankov](https://github.com/borisyankov))
* [ZeroClipboard](https://github.com/jonrohan/ZeroClipboard) (by [Eric J. Smith](https://github.com/ejsmith))
## List of definitions
Requested Definitions
---------------------
Here is an updated list of [definitions people have requested](https://github.com/borisyankov/DefinitelyTyped/issues?labels=Definition%3ARequest)
* See [CONTRIBUTORS.md](CONTRIBUTORS.md)
## Requested definitions
Here is an updated list of [definitions people have requested](https://github.com/borisyankov/DefinitelyTyped/issues?labels=Definition%3ARequest).
## Licence
This project is licensed under the MIT license.
Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
+1
View File
@@ -0,0 +1 @@
require('definition-tester');
-1
View File
@@ -1 +0,0 @@
/// <reference path="typings/tsd.d.ts" />
-1
View File
@@ -1 +0,0 @@
tsc runner.ts --target ES5 --out runner.js --module commonjs --sourcemap
File diff suppressed because it is too large Load Diff
-367
View File
@@ -1,367 +0,0 @@
/// <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';
interface PackageJSON {
scripts: {[key:string]: string};
}
/////////////////////////////////
// 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(() => {
// 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();
});
// return it
return test;
});
this.step();
// defer it
return defer.promise;
}
private step(): void {
while (this.queue.length > 0 && this.active.length < this.concurrent) {
this.active.push(this.queue.pop().call(null));
}
}
}
/////////////////////////////////
// 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();
var pkg: PackageJSON = require('../../package.json');
console.log('Scripts:');
console.log('');
Lazy(pkg.scripts).keys().each((key) => {
console.log(' $ npm run ' + key);
});
process.exit(0);
}
var testFull = process.env['TRAVIS_BRANCH'] ? /\w\/full$/.test(process.env['TRAVIS_BRANCH']) : false;
new TestRunner(dtPath, {
concurrent: argv['single-thread'] ? 1 : Math.max(Math.min(24, cpuCores), 2),
tscVersion: argv['tsc-version'],
testChanges: testFull ? false : argv['test-changes'], // allow magic branch
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);
});
}
-36
View File
@@ -1,36 +0,0 @@
/// <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);
});
}
}
}
-30
View File
@@ -1,30 +0,0 @@
module DT {
'use strict';
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);
});
});
}
}
-46
View File
@@ -1,46 +0,0 @@
/// <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 + ']';
}
}
}
-208
View File
@@ -1,208 +0,0 @@
/// <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());
});
}
}
}
-281
View File
@@ -1,281 +0,0 @@
/// <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);
});
});
}
}
}
@@ -1,42 +0,0 @@
/// <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();
}
}
}
}
-82
View File
@@ -1,82 +0,0 @@
/// <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
});
}
}
}
-26
View File
@@ -1,26 +0,0 @@
/// <reference path="../../runner.ts" />
/// <reference path="../util.ts" />
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
var endDts = /\w\.d\.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);
}));
}
}
}
@@ -1,26 +0,0 @@
/// <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);
}));
}
}
}
@@ -1,59 +0,0 @@
/// <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 [];
}
}
}
-50
View File
@@ -1,50 +0,0 @@
/// <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'));
}
}
}
-54
View File
@@ -1,54 +0,0 @@
/// <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]);
});
}
}
}
-40
View File
@@ -1,40 +0,0 @@
/// <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);
});
});
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-656
View File
@@ -1,656 +0,0 @@
// 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;
}
-252
View File
@@ -1,252 +0,0 @@
// 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
-48
View File
@@ -1,48 +0,0 @@
// 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;
}
-4
View File
@@ -1,4 +0,0 @@
/// <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" />
+32
View File
@@ -0,0 +1,32 @@
/// <reference path="alertify.d.ts" />
alertify.init();
alertify.alert("This is an alert");
alertify.alert("This is an alert with a callback", () => {
alertify.success("Alert finished");
}, "myCustomClass");
alertify.confirm("This is a confirm request");
alertify.confirm("This is a confirm request with a callback", () => {
alertify.success("Confirm finished");
}, "myCustomClass");
var custom = alertify.extend("custom");
alertify.log("log message 1");
alertify.log("log message 2", "success", 3000);
alertify.prompt("prompt message 1");
alertify.prompt("prompt message 2", () => { console.log("callback"); }, "ok", "myClass");
alertify.set({ delay: 1000 });
alertify.set({ labels: { ok: "OK", cancel: "Cancel" }});
alertify.set({ buttonFocus: "ok" });
alertify.set({ buttonReverse: true });
alertify.success("This is a success message");
alertify.error("This is an error message");
alertify.debug();
+124
View File
@@ -0,0 +1,124 @@
// Type definitions for alertify 0.3.11
// Project: http://fabien-d.github.io/alertify.js/
// Definitions by: John Jeffery <http://github.com/jjeffery>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var alertify: alertify.IAlertifyStatic;
declare module alertify {
interface IAlertifyStatic {
/**
* Create an alert dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param cssClass Class(es) to append to dialog box
* @return alertify (ie this)
* @since 0.0.1
*/
alert(message: string, fn?: Function, cssClass?: string): IAlertifyStatic;
/**
* Create a confirm dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param cssClass Class(es) to append to dialog box
* @return alertify (ie this)
* @since 0.0.1
*/
confirm(message: string, fn?: Function, cssClass?: string): IAlertifyStatic;
/**
* Extend the log method to create custom methods
* @param type Custom method name
* @return function for logging
* @since 0.0.1
*/
extend(type: string): (message: string, wait?: number) => IAlertifyStatic;
/**
* Initialize Alertify and create the 2 main elements.
* Initialization will happen automatically on the first
* use of alert, confirm, prompt or log.
* @since 0.0.1
*/
init(): void;
/**
* Show a new log message box
* @param message The message passed from the callee
* @param type Optional type of log message
* @param wait Optional time (in ms) to wait before auto-hiding
* @return alertify (ie this)
* @since 0.0.1
*/
log(message: string, type?: string, wait?: number): IAlertifyStatic;
/**
* Create a prompt dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param placeholder Default value for prompt input
* @param cssClass Class(es) to append to dialog
* @return alertify (ie this)
* @since 0.0.1
*/
prompt(message: string, fn?: Function, placeholder?: string, cssClass?: string): IAlertifyStatic;
/**
* Shorthand for log messages
* @param message The message passed from the callee
* @return alertify (ie this)
* @since 0.0.1
*/
success(message: string): IAlertifyStatic;
/**
* Shorthand for log messages
* @param message The message passed from the callee
* @return alertify (ie this)
* @since 0.0.1
*/
error(message: string): IAlertifyStatic;
/**
* Used to set alertify properties
* @param Properties
* @since 0.2.11
*/
set(args: IProperties): void;
/**
* The labels used for dialog buttons
*/
labels: ILabels;
/**
* Attaches alertify.error to window.onerror method
* @since 0.3.8
*/
debug(): void;
}
/**
* Properties for alertify.set function
*/
interface IProperties {
/** Default value for milliseconds display of log messages */
delay?: number;
/** Default values for display of labels */
labels?: ILabels;
/** Default button for focus */
buttonFocus?: string;
/** Should buttons be displayed in reverse order */
buttonReverse?: boolean;
}
/** Labels for altertify.set function */
interface ILabels {
ok?: string;
cancel?: string;
}
}
+12 -2
View File
@@ -176,8 +176,7 @@ amplify.request("twitter-mentions", { user: "amplifyjs" });
//Example:
amplify.request.decoders.appEnvelope =
function (data, status, xhr, success, error) {
var appEnvelopeDecoder: amplifyDecoder = function (data, status, xhr, success, error) {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
@@ -187,6 +186,17 @@ function (data, status, xhr, success, error) {
}
};
//a new decoder can be added to the amplifyDecoders interface
interface amplifyDecoders {
appEnvelope: amplifyDecoder;
}
amplify.request.decoders.appEnvelope = appEnvelopeDecoder;
//but you can also just add it via an index
amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder;
amplify.request.define("decoderExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",
+28 -6
View File
@@ -3,11 +3,33 @@
// Definitions by: Jonas Eriksson <https://github.com/joeriks/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface amplifyRequestSettings {
resourceId: string;
data?: any;
success?: Function;
error?: Function;
success?: (...args: any[]) => void;
error?: (...args: any[]) => void;
}
interface amplifyDecoder {
(
data?: any,
status?: string,
xhr?: JQueryXHR,
success?: (...args: any[]) => void,
error?: (...args: any[]) => void
): void
}
interface amplifyDecoders {
[decoderName: string]: amplifyDecoder;
jsSend: amplifyDecoder;
}
interface amplifyAjaxSettings extends JQueryAjaxSettings {
cache?: any;
decoder?: any /* string or amplifyDecoder */;
}
interface amplifyRequest {
@@ -39,7 +61,7 @@ interface amplifyRequest {
* cache: See the cache section for more details.
* decoder: See the decoder section for more details.
*/
define(resourceId: string, requestType: string, settings?: any): void;
define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void;
/***
* Define a custom request.
@@ -50,9 +72,9 @@ interface amplifyRequest {
* success: Callback to invoke on success.
* error: Callback to invoke on error.
*/
define(resourceId: string, resource: Function): void;
decoders: any;
define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void;
decoders: amplifyDecoders;
cache: any;
}
+78
View File
@@ -0,0 +1,78 @@
/// <reference path="angular-agility.d.ts" />
/// <reference path='../angularjs/angular.d.ts' />
var validIconStrategy:aa.IValidIconStrategy = <aa.IValidIconStrategy>{};
validIconStrategy.validIcon = "";
validIconStrategy.invalidIcon = "";
validIconStrategy.getContainer(<ng.IAugmentedJQueryStatic>{});
var provider:aa.IFormExtensionsProvider = <aa.IFormExtensionsProvider>{};
provider.defaultLabelStrategy = "";
provider.defaultFieldGroupStrategy = "";
provider.defaultValMsgPlacementStrategy = "";
provider.validIconStrategy = validIconStrategy;
provider.defaultSpinnerClickStrategy = "";
provider.defaultNotifyTarget = "";
provider.defaultOnNavigateAwayStrategy = "";
provider.validationMessages['testName'] = 'testMessages';
provider.valMsgForTemplate = "";
provider.confirmResetStrategy = ():boolean=>{ return false; };
provider.globalSettings['testSetting'] = 'test';
provider.labelStrategies['testLabelStratgey'] = (element:ng.IAugmentedJQueryStatic, labelText:string, isRequired:boolean):void=>{};
provider.fieldGroupStrategies['testFieldGroupStratgey'] = (element:ng.IAugmentedJQueryStatic):void=>{};
provider.valMsgPlacementStrategies['testValMsgPlacementStrategy'] = (formFieldElement:ng.IAugmentedJQueryStatic, formName:string, formFieldName:string):void=>{};
provider.spinnerClickStrategies['testSpinnerClickStratgey'] = (element:ng.IAugmentedJQueryStatic):void=>{};
provider.onNavigateAwayStrategies['testOnNavigateAwayStrategy'] = (rootFormScope:ng.IScope, rootForm:ng.IAugmentedJQueryStatic, $injector:ng.auto.IInjectorService)=>{};
var defaults:aa.INotifyDefaults = <aa.INotifyDefaults>{};
defaults.success = (message:string, options:any, notifier:any):any=>{};
defaults.info = (message:string, options:any, notifier:any):any=>{};
defaults.warning = (message:string, options:any, notifier:any):any=>{};
defaults.danger = (message:string, options:any, notifier:any):any=>{};
defaults.error = (message:string, options:any, notifier:any):any=>{};
var configWithoutTemplate:aa.INotifyConfig = {
name: "",
options: <aa.INotifyOptions> {},
namedDefaults: <aa.INotifyDefaults> {}
}
var configWithTemplate:aa.INotifyConfig = {
name: "",
template: "",
templateName: "",
options: <aa.INotifyOptions> {},
namedDefaults: <aa.INotifyDefaults> {}
}
var notifyOptionsWithoutCssClasses:aa.INotifyOptions = {
messageType: "",
allowHtml: true,
message: ""
}
var notifyOptionsWithCssClasses:aa.INotifyOptions = {
cssClasses: "",
messageType: "",
allowHtml: true,
message: ""
}
var notifyConfigProvider:aa.INotifyConfigProvider = <aa.INotifyConfigProvider> {};
notifyConfigProvider.notifyConfigs = {};
notifyConfigProvider.defaultTargetContainerName = "";
notifyConfigProvider.defaultNotifyConfig = "";
notifyConfigProvider.addOrUpdateNotifyConfig("", configWithTemplate);
notifyConfigProvider.optionsTransformer(notifyOptionsWithCssClasses, <ng.ISCEService>{});
var fullExternalConfig:aa.IExternalFormValidationConfig = {
validations: "",
ignore: "",
globals: "",
resolve: "",
resolveFn: (modelValue:string):string=>{ return "" }
}
var minimalExternalConfig:aa.IExternalFormValidationConfig = {
validations: ""
}
+106
View File
@@ -0,0 +1,106 @@
// Type definitions for AngularAgility
// Project: https://github.com/AngularAgility/AngularAgility
// Definitions by: Roland Zwaga <https://github.com/rolandzwaga>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path='../angularjs/angular.d.ts' />
declare module aa {
export interface ILabelStrategies {
[strategyName: string]: (element:ng.IAugmentedJQueryStatic, labelText:string, isRequired:boolean)=>void;
}
export interface IFieldGroupStrategies {
[strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void;
}
export interface IValMsgPlacementStrategies {
[strategyName: string]: (formFieldElement:ng.IAugmentedJQueryStatic, formName:string, formFieldName:string)=>void;
}
export interface IValidIconStrategy {
validIcon:string;
invalidIcon:string;
getContainer(element:ng.IAugmentedJQueryStatic):void;
}
export interface ISpinnerClickStrategies {
[strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void;
}
export interface IOnNavigateAwayStrategies {
[strategyName: string]: (rootFormScope:ng.IScope, rootForm:ng.IAugmentedJQueryStatic, $injector:ng.auto.IInjectorService)=>void;
}
export interface IValidationMessages {
[validationKey: string]: string;
}
export interface IGlobalSettings {
[settingName: string]: any;
}
export interface IFormExtensionsProvider extends ng.IServiceProvider {
defaultLabelStrategy:string;
defaultFieldGroupStrategy:string;
defaultValMsgPlacementStrategy:string;
validIconStrategy:IValidIconStrategy;
defaultSpinnerClickStrategy:string;
defaultNotifyTarget:string;
defaultOnNavigateAwayStrategy:string;
validationMessages:IValidationMessages;
valMsgForTemplate:string;
confirmResetStrategy:()=>boolean;
globalSettings:IGlobalSettings;
labelStrategies:ILabelStrategies;
fieldGroupStrategies:IFieldGroupStrategies;
valMsgPlacementStrategies:IValMsgPlacementStrategies;
spinnerClickStrategies:ISpinnerClickStrategies;
onNavigateAwayStrategies:IOnNavigateAwayStrategies;
}
export interface INotifyPredicate {
(message:string, options:any, notifier:any):any;
}
export interface INotifyDefaults {
success: INotifyPredicate;
info: INotifyPredicate;
warning: INotifyPredicate;
danger: INotifyPredicate;
error: INotifyPredicate;
}
export interface INotifyConfig {
name:string;
template?:string;
templateName?:string;
options:INotifyOptions;
namedDefaults:INotifyDefaults;
}
export interface INotifyOptions {
cssClasses?:string;
messageType:string;
allowHtml:boolean;
message:string;
}
export interface INotifyConfigProvider extends ng.IServiceProvider {
notifyConfigs:any;
defaultTargetContainerName:string;
defaultNotifyConfig:string;
addOrUpdateNotifyConfig(name:string, opts:INotifyConfig):void;
optionsTransformer(options:INotifyOptions, $sce:ng.ISCEService):void;
}
export interface IExternalFormValidationConfig {
validations:any;
ignore?:any;
globals?:any;
resolve?:any;
resolveFn?:(modelValue:string)=>string;
}
}
@@ -0,0 +1,35 @@
///<reference path='angular-bootstrap-lightbox.d.ts'/>
var imageList:angular.bootstrap.lightbox.ILightboxImageInfo[] = [];
imageList.push({
url: 'url1',
width: 100,
height: 100
});
imageList.push({
url: 'url2',
width: 100,
height: 100,
thumbUrl: 'thumbUrl',
caption: 'caption'
});
var lightBox:angular.bootstrap.lightbox.ILightbox = <any> {};
lightBox.openModal(imageList, 0);
var provider:angular.bootstrap.lightbox.ILightBoxProvider = <any> {};
provider.templateUrl = 'templateUrl';
provider.calculateImageDimensionLimits = (dimensions:angular.bootstrap.lightbox.IImageDimensionParameter):angular.bootstrap.lightbox.IImageDimensionLimits=> {
return {
minWidth: 100,
minHeight: 100,
maxWidth: dimensions.windowWidth - 102,
maxHeight: dimensions.windowHeight - 136
};
};
provider.calculateModalDimensions = (dimensions:angular.bootstrap.lightbox.IModalDimensionsParameter):angular.bootstrap.lightbox.IModalDimensions=> {
return {
width: Math.max(500, dimensions.imageDisplayWidth + 42),
height: Math.max(500, dimensions.imageDisplayHeight + 76)
};
};
@@ -0,0 +1,51 @@
// Type definitions for angular-bootstrap-lightbox
// Project: https://github.com/compact/angular-bootstrap-lightbox
// Definitions by: Roland Zwaga <https://github.com/rolandzwaga>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.bootstrap.lightbox {
export interface ILightboxImageInfo {
url: string;
width: number;
height: number;
thumbUrl?: string;
caption?: string;
}
export interface IImageDimensionLimits {
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
}
export interface IImageDimensionParameter {
windowWidth:number;
windowHeight:number;
imageWidth:number;
imageHeight:number;
}
export interface IModalDimensionsParameter {
windowWidth:number;
windowHeight:number;
imageDisplayWidth:number;
imageDisplayHeight:number;
}
export interface IModalDimensions {
width:number;
height:number;
}
export interface ILightbox {
openModal(images:ILightboxImageInfo[], index:number):void;
}
export interface ILightBoxProvider {
templateUrl:string;
calculateImageDimensionLimits:(dimensions:IImageDimensionParameter)=>IImageDimensionLimits;
calculateModalDimensions:(dimensions:IModalDimensionsParameter)=>IModalDimensions;
}
}
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="angular-hotkeys.d.ts" />
var scope: ng.IScope;
var hotkeyProvider: ng.hotkeys.HotkeysProvider;
var hotkeyObj: ng.hotkeys.Hotkey;
hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} );
hotkeyProvider.add(hotkeyObj);
hotkeyProvider.bindTo(scope);
hotkeyProvider.del("mod+s");
hotkeyProvider.get("mod+s");
hotkeyProvider.toggleCheatSheet();
hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback);
hotkeyProvider.bindTo(scope)
.add(hotkeyObj)
.add(hotkeyObj)
.add({
combo: 'w',
description: 'blah blah',
callback: function() {}
});
+40
View File
@@ -0,0 +1,40 @@
// Type definitions for angular-hotkeys
// Project: https://github.com/chieffancypants/angular-hotkeys
// Definitions by: Jason Zhao <https://github.com/jlz27>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module ng.hotkeys {
interface HotkeysProvider {
template: string;
includeCheatSheet: boolean;
cheatSheetHotkey: string;
cheatSheetDescription: string;
add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): void;
add(hotkeyObj: ng.hotkeys.Hotkey): void;
bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProviderChained;
del(combo: string): void;
get(combo: string): ng.hotkeys.Hotkey;
toggleCheatSheet(): void;
}
interface HotkeysProviderChained {
add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained;
add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained;
}
interface Hotkey {
combo: string;
description?: string;
callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void;
}
}
+68 -30
View File
@@ -153,21 +153,36 @@ function TestProtractor() {
ptor.debugger();
var webElement: protractor.WebElement = ptor.findElement(by.css('.class'));
var promise: webdriver.promise.Promise;
promise = ptor.findElements(by.css('.class'));
promise = ptor.isElementPresent(by.css('.class'));
promise = ptor.isElementPresent(webElement);
ptor.clearMockModules();
ptor.addMockModule('name', 'script');
ptor.addMockModule('name', function() {});
ptor.removeMockModule('name');
ptor.waitForAngular();
var elementFinder: protractor.ElementFinder;
var elementArrayFinder: protractor.ElementArrayFinder;
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'));
elementArrayFinder = ptor.$$('.class');
var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl();
ptor.setLocation('webaddress.com');
promise = ptor.get('webaddress.com');
promise = ptor.get('webdaddress.com', 45);
ptor.refresh();
ptor.refresh(45);
var navigation: webdriver.WebDriverNavigation = ptor.navigate();
ptor.pause();
ptor.pause(8080);
}
function TestElement() {
@@ -180,6 +195,7 @@ function TestElementFinder() {
var promise: webdriver.promise.Promise;
promise = elementFinder.click();
promise = elementFinder.allowAnimations('string');
promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN);
promise = elementFinder.getTagName();
promise = elementFinder.getCssValue('display');
@@ -195,19 +211,49 @@ function TestElementFinder() {
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.$$('.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();
function TestElementArrayFinder() {
var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.id('id'));
var promise: webdriver.promise.Promise;
var elementFinder: protractor.ElementFinder;
var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements();
elementFinder = elementArrayFinder.get(42);
elementFinder = elementArrayFinder.first();
elementFinder = elementArrayFinder.last();
promise = elementArrayFinder.count();
promise = elementArrayFinder.asElementFinders_();
elementArrayFinder.each(function(element: protractor.ElementFinder){
// nothing
});
elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){
// nothing
});
elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){
return element.getText().then((text: string) => {
return text === "foo";
});
});
elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder){
return element.getText().then((text: string) => {
return accumulator + ',' + text;
});
}, '');
elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder, index: number, array: protractor.ElementFinder[]){
return element.getText().then((text: string) => {
return accumulator + ',' + text;
});
}, '');
elementArrayFinder.then(function(underlyingElementFinders: protractor.ElementFinder[]){
//nothing
});
}
// This function tests the angular specific locator strategies.
@@ -216,27 +262,19 @@ function TestLocatorStrategies() {
var webElement: webdriver.WebElement;
// Protractor Specific Locators
protractor.By.addLocator('customLocator', 'script');
protractor.By.addLocator('customLocator2', function(){
// nothing
});
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.exactBinding('exactBinding'));
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');
webElement = ptor.findElement(protractor.By.repeater('repeater').column(0));
webElement = ptor.findElement(protractor.By.repeater('repeater').row(0));
webElement = ptor.findElement(protractor.By.repeater('repeater').row(0).column(0));
webElement = ptor.findElement(protractor.By.buttonText('buttonText'));
webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText'));
webElement = ptor.findElement(protractor.By.cssContainingText('cssSelector', 'search text'));
webElement = ptor.findElement(protractor.By.options('options'));
}
+519 -262
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular Protractor 0.17.0
// Type definitions for Angular Protractor 1.0.0-rc4
// Project: https://github.com/angular/protractor
// Definitions by: Bill Armstrong <https://github.com/BillArmstrong>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -25,71 +25,7 @@ declare module protractor {
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;
}
class WebElement extends webdriver.WebElement {}
module command {
class Command extends webdriver.Command {}
@@ -273,13 +209,140 @@ declare module protractor {
}
//endregion
/**
* Use as: element(locator)
*
* The ElementFinder can be treated as a WebElement for most purposes, in
* particular, you may perform actions (i.e. click, getText) on them as you
* would a WebElement. ElementFinders extend Promise, and once an action
* is performed on an ElementFinder, the latest result from the chain can be
* accessed using then. Unlike a WebElement, an ElementFinder will wait for
* angular to settle before performing finds or actions.
*
* ElementFinder can be used to build a chain of locators that is used to find
* an element. An ElementFinder does not actually attempt to find the element
* until an action is called, which means they can be set up in helper files
* before the page is available.
*
* @param {webdriver.Locator} locator An element locator.
* @return {ElementFinder}
*/
interface Element {
(locator: webdriver.Locator): ElementFinder;
/**
* ElementArrayFinder is used for operations on an array of elements (as opposed
* to a single element).
*
* @param {webdriver.Locator} locator An element locator.
* @return {ElementArrayFinder}
*/
all(locator: webdriver.Locator): ElementArrayFinder;
}
interface ElementFinder {
/**
* Use as: element(locator).element(locator)
* Calls to element may be chained to find elements within a parent.
*
* @param {webdriver.Locator} locator The locator that will be used to find descendents.
*
* @return {protractor.ElementFinder} The descendent element found by the locator
*/
element(locator: webdriver.Locator): protractor.ElementFinder;
/**
* Use as: element(locator).all(locator)
* Calls to element may be chained to find an array of elements within a parent.
*
* @param {webdriver.Locator} locator The locator that will be used to find descendents.
*
* @return {protractor.ElementArrayFinder} The descendent elements found by the locator
*/
all(locator: webdriver.Locator): protractor.ElementArrayFinder;
/**
* 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;
/**
* Use as: element(locator).isPresent()
* Determine whether the element is present on the page.
*
* @return {protractor.ElementFinder} Which resolves to whether the element is present on the page.
*/
isPresent(): webdriver.promise.Promise;
/**
* Override for WebElement.prototype.isElementPresent so that protractor waits
* for Angular to settle before making the check.
*
* @see ElementFinder.isPresent
* @return {!webdriver.promise.Promise} which resolves to whether the element is present on the page.
*/
isElementPresent(locator: webdriver.Locator): webdriver.promise.Promise;
/**
* Return this ElementFinder's locator.
*
* @return {webdriver.Locator}
*/
locator(): webdriver.Locator;
/**
* Use as: element(locator).getWebElement()
* Returns the WebElement represented by this ElementFinder.
* Throws the WebDriver error if the element doesn't exist.
* If index is null, it makes sure that there is only one underlying WebElement
* described by the chain of locators and issues a warning otherwise.
* If index is not null, it retrieves the WebElement specified by the index..
* @return {webdriver.WebElement} The WebElement represented by the ElementFinder.
*/
getWebElement(): webdriver.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;
/**
* Determine if animation is allowed on the current element.
* @param {string} value
*
* @return {ElementFinder} which resolves to whether animation is allowed.
*/
allowAnimations(value: string): webdriver.promise.Promise;
/**
* Access the underlying actionResult of ElementFinder. Implementation allows ElementFinder to be used as a webdriver.promise.Promise.
* @param {function(webdriver.promise.Promise)} fn Function which takes the value of the underlying actionResult.
*
* @return {webdriver.promise.Promise} Promise which contains the results of evaluating fn.
*/
then(fn: IThenFunction): webdriver.promise.Promise;
/**
* Schedules a command to click on this element.
* @return {!webdriver.promise.Promise} A promise that will be resolved when
@@ -460,113 +523,163 @@ declare module protractor {
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.
* @return {!webdriver.promise.Promise.<webdriver.WebElement.Id>} A promise
* that resolves to this element's JSON representation as defined by the
* WebDriver wire protocol.
* @see http://code.google.com/p/selenium/wiki/JsonWireProtocol
*/
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;
toWireValue(): webdriver.promise.Promise;
}
interface ElementArrayFinder{
interface IThenFunction {
(promiseResult: any): any;
}
interface ElementArrayFinder {
/**
* Use as: element.all(locator).getWebElements()
* Returns the array of WebElements represented by this ElementArrayFinder.
*
* @return {Array.<webdriver.WebElement>} Array of WebElements represented by this ElementArrayFinder
*/
getWebElements(): webdriver.WebElement[];
/**
* Use as: element.all(locator).get(index)
* Get an element found by the locator by index. The index starts at 0. This does not actually retrieve the underlying element.
*
* @param {number} index Element index.
*
* @return {protractor.ElementFinder} Finder representing element at the given index
*/
get(index: number): protractor.ElementFinder;
/**
* Use as: element.all(locator).first()
* Get the first matching element for the locator. This does not actually retrieve the underlying element.
*
* @return {Protractor.ElementFinder} Finder representing the first matching element
*/
first(): protractor.ElementFinder;
/**
* Use as: element.all(locator).last()
* Get the last matching element for the locator. This does not actually retrieve the underlying element.
*
* @return {Protractor.ElementFinder} Finder representing the last matching element
*/
last(): protractor.ElementFinder;
/**
* Use as: element.all(locator).getWebElements()
* Returns the array of WebElements represented by this ElementArrayFinder.
*
* @return {!webdriver.promise.Promise} The array of WebElements represented by this ElementArrayFinder
*/
count(): webdriver.promise.Promise;
get(index: number): protractor.WebElement;
first(): protractor.WebElement;
last(): protractor.WebElement;
then(fn: (value: any) => any): webdriver.promise.Promise;
/**
* Use as: element.all(locator).each(eachFunction)
* Calls the input function on each ElementFinder found by the locator.
*
* @param {function(ElementFinder)} fn Input function.
*/
each(fn: IEachFunction): void;
/**
* Use as: element.all(locator).map(mapFunction)
* Apply a map function to each element found using the locator. The callback receives the ElementFinder as the first argument and the index as a second arg.
*
* @param {function(ElementFinder, number)} mapFn Map function that will be applied to each element.
*
* @return {!webdriver.promise.Promise} A promise that resolves to an array of values returned by the map function.
*/
map(mapFn: IMapFunction): webdriver.promise.Promise;
/**
* Use as: element.all(locator).filter(filterFn)
* Apply a filter function to each element found using the locator. Returns promise of a new array with all elements that pass the filter function. The filter function receives the ElementFinder as the first argument and the index as a second arg.
*
* @param {function(ElementFinder, number): webdriver.promise.Promise} filterFn Filter function that will test if an element should be returned. filterFn should return a promise that resolves to a boolean.
*
* @return {!webdriver.promise.Promise} A promise that resolves to an array of ElementFinders that satisfy the filter function.
*/
filter(func: IFilterFunction): webdriver.promise.Promise;
/**
* Use as: element.all(locator).reduce(reduceFn)
* Apply a reduce function against an accumulator and every element found using the locator (from left-to-right).
* The reduce function has to reduce every element into a single value (the accumulator).
* Returns promise of the accumulator.
* The reduce function receives the accumulator, current ElementFinder, the index, and the entire array of ElementFinders, respectively.
*
* @param {function(number, ElementFinder, number, Array.<ElementFinder>): webdriver.promise.Promise} reduceFn Reduce function that reduces every element into a single value.
* @param {*} initialValue Initial value of the accumulator.
*
* @return {!webdriver.promise.Promise} A promise that resolves to the final value of the accumulator.
*/
reduce(func: IReductionFunction, initialValue: any): webdriver.promise.Promise;
/**
* Represents the ElementArrayFinder as an array of ElementFinders.
*
* @return {!webdriver.promise.Promise} Return a promise, which resolves to a list (array)
* of ElementFinders specified by the locator.
*/
asElementFinders_(): webdriver.promise.Promise;
/**
* Find the elements specified by the locator. The input function is passed
* to the resulting promise, which resolves to an array of ElementFinders.
*
* Use as: element.all(locator).then(thenFunction)
* <ul class="items">
* <li>First</li>
* <li>Second</li>
* <li>Third</li>
* </ul>
*
* element.all(by.css('.items li')).then(function(arr) {
* expect(arr.length).toEqual(3);
* });
*
* @param {function(Array.<ElementFinder>)} fn
*
* @type {webdriver.promise.Promise} a promise which will resolve to
* an array of ElementFinders matching the locator.
*/
then(fn: IElementArrayFinderThenFunction): webdriver.promise.Promise;
}
interface IEachFunction {
(element: protractor.ElementFinder): void;
}
interface IMapFunction {
(element: ElementFinder, index: number): any;
}
interface IFilterFunction {
(element: ElementFinder, index: number): webdriver.promise.Promise;
}
interface IReductionFunction {
(accumulator: any, element: protractor.ElementFinder, index?: number, array?: protractor.ElementFinder[]): webdriver.promise.Promise;
}
interface IElementArrayFinderThenFunction {
(promiseResult: ElementFinder[]): any;
}
class LocatorWithColumn extends webdriver.Locator {
column(index: number): webdriver.Locator;
}
class RepeaterLocator extends LocatorWithColumn {
row(index: number): LocatorWithColumn;
}
interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy {
@@ -587,65 +700,160 @@ declare module protractor {
* Usage:
* <span>{{status}}</span>
* var status = element(by.binding('{{status}}'));
*
* @param {string} bindingDescriptor
* @return {webdriver.Locator}
*/
binding(bindingDescriptor: string): webdriver.Locator;
/**
* Usage:
* <select ng-model="user" ng-options="user.name for user in users"></select>
* element(by.select("user"));
* Find an element by exact binding.
*
* <span>{{ person.name }}</span>
* <span ng-bind="person-email"></span>
* <span>{{person_phone|uppercase}}</span>
*
* expect(element(by.exactBinding('person.name')).isPresent()).toBe(true);
* expect(element(by.exactBinding('person-email')).isPresent()).toBe(true);
* expect(element(by.exactBinding('person')).isPresent()).toBe(false);
* expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true);
* expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true);
* expect(element(by.exactBinding('phone')).isPresent()).toBe(false);
*
* @param {string} bindingDescriptor
* @return {webdriver.Locator}
*/
select(model: string): webdriver.Locator;
exactBinding(bindingDescriptor: string): webdriver.Locator;
/**
*
* Find an element by ng-model expression.
*
* 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'));
* <input type="text" ng-model="person.name"/>
* var input = element(by.model('person.name'));
* input.sendKeys('123');
* expect(input.getAttribute('value')).toBe('Foo123');
*
* @param {string} model ng-model expression.
* @return {webdriver.Locator}
*/
model(model: string): webdriver.Locator;
/**
* Find a button by text.
*
* Usage:
* <textarea ng-model="user"></textarea>
* element(by.textarea("user"));
* <button>Save</button>
* element(by.buttonText('Save'));
*
* @param {string} searchText
* @return {webdriver.Locator}
*/
textarea(model: string): webdriver.Locator;
buttonText(searchText: string): webdriver.Locator;
/**
* Find a button by partial text.
*
* Usage:
* <div ng-repeat = "cat in pets">
* <span>{{cat.name}}</span>
* <span>{{cat.age}}</span>
* </div>
* <button>Save my file</button>
* element(by.partialButtonText('Save'));
*
* @param {string} searchText
* @return {webdriver.Locator}
*/
partialButtonText(searchText: string): webdriver.Locator;
/**
* Find elements inside an ng-repeat.
*
* Usage:
* <div ng-repeat="cat in pets">
* <span>{{cat.name}}</span>
* <span>{{cat.age}}</span>
* </div>
*
* <div class="book-img" ng-repeat-start="book in library">
* <span>{{$index}}</span>
* </div>
* <div class="book-info" ng-repeat-end>
* <h4>{{book.name}}</h4>
* <p>{{book.blurb}}</p>
* </div>
*
* // Returns the DIV for the second cat.
* var secondCat = element(by.repeater("cat in pets").row(2));
* var secondCat = element(by.repeater('cat in pets').row(1));
*
* // Returns the SPAN for the first cat's name.
* var firstCatName = element(
* by.repeater("cat in pets").row(1).column("{{cat.name}}"));
* var firstCatName = element(by.repeater('cat in pets').
* row(0).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}}"));
* var ages = element.all(
* 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"));
* // all top level elements repeated by the repeater. For 2 pets rows resolves
* // to an array of 2 elements.
* var rows = element.all(by.repeater('cat in pets'));
*
* // Returns a promise that resolves to an array of WebElements containing all
* // the elements with a binding to the book's name.
* var divs = element.all(by.repeater('book in library').column('book.name'));
*
* // Returns a promise that resolves to an array of WebElements containing
* // the DIVs for the second book.
* var bookInfo = element.all(by.repeater('book in library').row(1));
*
* // Returns the H4 for the first book's name.
* var firstBookName = element(by.repeater('book in library').
* row(0).column('{{book.name}}'));
*
* // Returns a promise that resolves to an array of WebElements containing
* // all top level elements repeated by the repeater. For 2 books divs
* // resolves to an array of 4 elements.
* var divs = element.all(by.repeater('book in library'));
*/
repeater(repeatDescriptor: string): webdriver.Locator;
repeater(repeatDescriptor: string): RepeaterLocator;
/**
* Find elements by CSS which contain a certain string.
*
* @view
* <ul>
* <li class="pet">Dog</li>
* <li class="pet">Cat</li>
* </ul>
*
* @example
* // Returns the DIV for the dog, but not cat.
* var dog = element(by.cssContainingText('.pet', 'Dog'));
*
* @param cssSelector {string}
* @param searchText {string}
* @return {webdriver.Locator}
*/
cssContainingText(cssSelector: string, searchText: string): webdriver.Locator;
/**
* Find an element by ng-options expression.
*
* Usage:
* <select ng-model="color" ng-options="c for c in colors">
* <option value="0" selected="selected">red</option>
* <option value="1">green</option>
* </select>
*
* var allOptions = element.all(by.options('c for c in colors'));
* expect(allOptions.count()).toEqual(2);
* var firstOption = allOptions.first();
* expect(firstOption.getText()).toEqual('red');
*
* @param {string} optionsDescriptor ng-options expression.
* @return {webdriver.Locator}
*/
options(optionsDescriptor: string): webdriver.Locator;
}
var By: IProtractorLocatorStrategy;
@@ -714,6 +922,43 @@ declare module protractor {
//region Methods
/**
* 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;
/**
* Waits for Angular to finish rendering before searching for elements.
* @see webdriver.WebDriver.findElement
*
* @param {webdriver.Locator} locator The locator used to find the element.
* @return {!webdriver.WebElement}
*/
findElement(locator: webdriver.Locator): protractor.WebElement;
/**
* Waits for Angular to finish rendering before searching for elements.
* @see webdriver.WebDriver.findElements
*
* @param {webdriver.Locator} locator The locator used to find the elements.
* @return {!webdriver.promise.Promise} A promise that will be resolved to an
* array of the located {@link webdriver.WebElement}s.
*/
findElements(locator: webdriver.Locator): webdriver.promise.Promise;
/**
* Tests if an element is present on the page.
* @see webdriver.WebDriver.isElementPresent
* @return {!webdriver.promise.Promise} A promise that will resolve to whether
* the element is present on the page.
*/
isElementPresent(locatorOrElement: webdriver.Locator): webdriver.promise.Promise;
isElementPresent(locatorOrElement: any): webdriver.promise.Promise;
/**
* Helper function for finding elements.
*
@@ -735,40 +980,71 @@ declare module protractor {
*/
$$(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.
* @param {string} name The name of the module to load or override.
* @param {string|Function} script The JavaScript to load the module.
* @param {...*} varArgs Any additional arguments will be provided to
* the script and may be referenced using the `arguments` object.
*/
addMockModule(name: string, script: string): void;
addMockModule(name: string, script: any): void;
addMockModule(name: string, script: string, ...varArgs: any[]): void;
addMockModule(name: string, script: any, ...varArgs: any[]): void;
/**
* Clear the list of registered mock modules.
*/
clearMockModules(): void;
/**
* Remove a registered mock module.
* @param {!string} name The name of the module to remove.
*/
removeMockModule(name: string): void;
/**
* See webdriver.WebDriver.get
*
* Navigate to the given destination and loads mock modules before
* Angular. Assumes that the page being loaded uses Angular.
* If you need to access a page which does not have Angular on load, use
* the wrapped webdriver directly.
*
* @param {string} destination Destination URL.
* @param {number=} opt_timeout Number of seconds to wait for Angular to start.
*/
get(destination: string, opt_timeout?: number): webdriver.promise.Promise;
/**
* See webdriver.WebDriver.refresh
*
* Makes a full reload of the current page and loads mock modules before
* Angular. Assumes that the page being loaded uses Angular.
* If you need to access a page which does not have Angular on load, use
* the wrapped webdriver directly.
*
* @param {number=} opt_timeout Number of seconds to wait for Angular to start.
*/
refresh(opt_timeout?: number): void;
/**
* Mixin navigation methods back into the navigation object so that
* they are invoked as before, i.e. driver.navigate().refresh()
*/
navigate(): webdriver.WebDriverNavigation;
/**
* Browse to another page using in-page navigation.
*
* @param {string} url In page URL using the same syntax as $location.url()
* @returns {!webdriver.promise.Promise} A promise that will resolve once
* page has been changed.
*/
setLocation(url: string): webdriver.promise.Promise;
/**
* Returns the current absolute url from AngularJS.
*/
@@ -795,43 +1071,14 @@ declare module protractor {
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.
* Beta (unstable) pause function for debugging webdriver tests. Use
* browser.pause() in your test to enter the protractor debugger from that
* point in the control flow.
* Does not require changes to the command line (no need to add 'debug').
*
* <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.
* @param {=number} opt_debugPort Optional port to use for the debugging process
*/
findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement;
findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement;
pause(opt_debugPort?: number): void;
//endregion
}
@@ -859,9 +1106,19 @@ declare module protractor {
}
interface cssSelectorHelper {
(cssLocator: string): protractor.ElementFinder;
}
interface cssArraySelectorHelper {
(cssLocator: string): protractor.ElementArrayFinder;
}
declare var browser: protractor.Protractor;
declare var by: protractor.IProtractorLocatorStrategy;
declare var element: protractor.Element;
declare var $: cssSelectorHelper;
declare var $$: cssArraySelectorHelper;
declare module 'protractor' {
export = protractor;
@@ -0,0 +1,244 @@
/// <reference path="angular-protractor-0.17.0.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: webdriver.promise.Promise = 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'));
webElement = ptor.findElement(protractor.By.buttonText('buttonText'));
webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText'));
}
// 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');
}
+906
View File
@@ -0,0 +1,906 @@
// 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;
/**
* Use as: element(locator).element(locator)
* Calls to element may be chained to find elements within a parent.
*
* @param {webdriver.Locator} The locator that will be used to find descendents.
*
* @return {protractor.ElementFinder} the descendent element found by the locator
*/
element(locator: webdriver.Locator): protractor.ElementFinder;
/**
* Use as: element(locator).all(locator)
* Calls to element may be chained to find an array of elements within a parent.
*
* @param {webdriver.Locator} The locator that will be used to find descendents.
*
* @return {protractor.ElementArrayFinder} the descendent elements found by the locator
*/
all(locator: webdriver.Locator): protractor.ElementArrayFinder;
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;
}
class LocatorWithColumn extends webdriver.Locator {
column(index: number): webdriver.Locator;
}
class RepeaterLocator extends LocatorWithColumn {
row(index: number): LocatorWithColumn;
}
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): RepeaterLocator;
buttonText(searchText: string): webdriver.Locator;
partialButtonText(searchText: 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(): webdriver.promise.Promise;
/**
* 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;
}
interface cssSelectorHelper {
(cssLocator: string): protractor.ElementFinder;
}
declare var browser: protractor.Protractor;
declare var by: protractor.IProtractorLocatorStrategy;
declare var element: protractor.Element;
declare var $: cssSelectorHelper;
declare var $$: cssSelectorHelper;
declare module 'protractor' {
export = protractor;
}
+1 -1
View File
@@ -24,6 +24,6 @@ interface Scope extends ng.IScope {
app.controller('Ctrl', ($scope: Scope, $translate: ng.translate.ITranslateService) => {
$scope['changeLanguage'] = function (key: any) {
$translate.uses(key);
$translate.use(key);
};
});
+37 -9
View File
@@ -1,15 +1,26 @@
// Type definitions for Angular Translate (pascalprecht.translate module)
// Project: https://github.com/PascalPrecht/angular-translate
// Definitions by: Michel Salib <michelsalib@hotmail.com>
// Definitions by: Michel Salib <https://github.com/michelsalib>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module ng.translate {
interface ITranslatePartialLoaderService {
addPart(name: string): ITranslatePartialLoaderService;
deletePart(name: string, removeData?: boolean): ITranslatePartialLoaderService;
isPartAvailable(name: string): boolean;
}
interface ITranslationTable {
[key: string]: string;
}
interface ILanguageKeyAlias {
[key: string]: string;
}
interface IStorage {
get(name: string): string;
set(name: string, value: string): void;
@@ -22,22 +33,33 @@ declare module ng.translate {
}
interface ITranslateService {
(key: string, ...params: string[]): string;
fallbackLanguage(): string;
(key: string, ...params: string[]): ng.IPromise<string>;
cloakClassName(): string;
cloakClassName(name: string): ITranslateProvider;
fallbackLanguage(langKey?: string): string;
fallbackLanguage(langKey?: string[]): string;
instant(translationId: string, interpolateParams?: any, interpolationId?: string): string;
instant(translationId: string[], interpolateParams?: any, interpolationId?: string): string;
isPostCompilingEnabled(): boolean;
preferredLanguage(): string;
proposedLanguage(): string;
refresh(lankKey: string): ng.IPromise<void>;
refresh(langKey?: string): ng.IPromise<void>;
storage(): IStorage;
storageKey(): string;
uses(): string;
uses(key: string): ng.IPromise<string>;
use(): string;
use(key: string): ng.IPromise<string>;
useFallbackLanguage(langKey?: string): void;
}
interface ITranslateProvider extends ng.IServiceProvider {
interface ITranslateProvider extends ng.IServiceProvider {
translations(): ITranslationTable;
translations(key: string, translationTable: ITranslationTable): ITranslateProvider;
cloakClassName(): string;
cloakClassName(name: string): ITranslateProvider;
addInterpolation(factory: any): ITranslateProvider;
useMessageFormatInterpolation(): ITranslateProvider;
useInterpolation(factory: string): ITranslateProvider;
useSanitizeValueStrategy(value: string): ITranslateProvider;
preferredLanguage(): string;
preferredLanguage(language: string): ITranslateProvider;
translationNotFoundIndicator(indicator: string): ITranslateProvider;
@@ -48,8 +70,10 @@ declare module ng.translate {
fallbackLanguage(): string;
fallbackLanguage(language: string): ITranslateProvider;
fallbackLanguage(languages: string[]): ITranslateProvider;
uses(): string;
uses(key: string): ITranslateProvider;
use(): string;
use(key: string): ITranslateProvider;
storageKey(): string;
storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here
useUrlLoader(url: string): ITranslateProvider;
useStaticFilesLoader(options: ISTaticFilesLoaderOptions): ITranslateProvider;
useLoader(loaderFactory: string, options: any): ITranslateProvider;
@@ -60,5 +84,9 @@ declare module ng.translate {
storagePrefix(prefix: string): ITranslateProvider;
useMissingTranslationHandlerLog(): ITranslateProvider;
useMissingTranslationHandler(factory: string): ITranslateProvider;
usePostCompiling(value: boolean): ITranslateProvider;
determinePreferredLanguage(fn?: () => void): ITranslateProvider;
registerAvailableLanguageKeys(): string[];
registerAvailableLanguageKeys(languageKeys: string[], aliases?: ILanguageKeyAlias): ITranslateProvider;
}
}
+75
View File
@@ -13,6 +13,10 @@ myApp.config((
$urlMatcherFactory: ng.ui.IUrlMatcherFactory) => {
var matcher: ng.ui.IUrlMatcher = $urlMatcherFactory.compile("/foo/:bar?param1");
var obj: Object = matcher.exec('/user/bob', { x:'1', q:'hello' });
var concat: ng.ui.IUrlMatcher = matcher.concat('/test');
var str: string = matcher.format({ id:'bob', q:'yes' });
var arr: string[] = matcher.parameters();
$urlRouterProvider
.when('/test', '/list')
@@ -71,3 +75,74 @@ myApp.config((
}
});
});
interface IUrlLocatorTestService {
currentUser: any;
}
// Service for determining who the currently logged on user is.
class UrlLocatorTestService implements IUrlLocatorTestService {
static $inject = ["$http", "$rootScope", "$urlRouter", "$state"];
constructor(
private $http: ng.IHttpService,
private $rootScope: ng.IRootScopeService,
private $urlRouter: ng.ui.IUrlRouterService,
private $state: ng.ui.IStateService
) {
$rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event));
}
public currentUser: any;
private onLocationChangeSuccess(event: ng.IAngularEvent) {
if (!this.currentUser) {
// If the current user is unknown, halt the state change and request current
// user details from the server
event.preventDefault();
// Note that we do not concern ourselves with what to do if this request fails,
// because if it fails, the web page will be redirected away to the login screen.
this.$http({ url: "/api/me", method: "GET" }).success((user: any) => {
this.currentUser = user;
// sync the ui-state with the location in the browser, which effectively
// restarts the state change that was stopped previously
this.$urlRouter.sync();
});
}
}
private stateServiceTest() {
this.$state.go("myState");
this.$state.transitionTo("myState");
if (this.$state.includes("myState") === true) {
//
}
if (this.$state.is("myState") === true) {
//
}
if (this.$state.href("myState") === "/myState") {
//
}
this.$state.get("myState");
this.$state.get();
this.$state.reload();
}
}
myApp.service("urlLocatorTest", UrlLocatorTestService);
module UiViewScrollProviderTests {
var app = angular.module("uiViewScrollProviderTests", ["ui.router"]);
app.config(['$uiViewScrollProvider', function($uiViewScrollProvider: ng.ui.IUiViewScrollProvider) {
// This prevents unwanted scrolling to the active nested state view.
// Use this when you have nested states, but you don't want the browser to scroll down the page
// to the nested state view.
//
// See https://github.com/angular-ui/ui-router/issues/848
// And https://github.com/angular-ui/ui-router/releases/tag/0.2.8
$uiViewScrollProvider.useAnchorScroll();
}]);
}
+26 -3
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.1.5+ (ui.router module)
// Project: https://github.com/angular-ui/ui-router
// Definitions by: Michel Salib <michelsalib@hotmail.com>
// Definitions by: Michel Salib <https://github.com/michelsalib>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
@@ -33,13 +33,13 @@ declare module ng.ui {
interface IUrlMatcher {
concat(pattern: string): IUrlMatcher;
exec(path: string, searchParams: {}): {};
parameters(): string[];
format(values: {}): string;
}
interface IUrlMatcherFactory {
compile(pattern: string): IUrlMatcher;
isMatcher(o: any): boolean;
parameters(): string[];
format(values: {}): string;
}
interface IUrlRouterProvider extends IServiceProvider {
@@ -86,9 +86,32 @@ declare module ng.ui {
get(): IState[];
current: IState;
params: IStateParamsService;
reload(): void;
}
interface IStateParamsService {
[key: string]: any;
}
interface IUrlRouterService {
/*
* Triggers an update; the same update that happens when the address bar
* url changes, aka $locationChangeSuccess.
*
* This method is useful when you need to use preventDefault() on the
* $locationChangeSuccess event, perform some custom logic (route protection,
* auth, config, redirection, etc) and then finally proceed with the transition
* by calling $urlRouter.sync().
*
*/
sync(): void;
}
interface IUiViewScrollProvider {
/*
* Reverts back to using the core $anchorScroll service for scrolling
* based on the url anchor.
*/
useAnchorScroll(): void;
}
}
@@ -0,0 +1,27 @@
///<reference path="../angularjs/angular.d.ts" />
///<reference path="./angularLocalStorage.d.ts" />
interface TestScope extends ng.IScope {
viewType: string;
}
module ng.LocalStorageTests {
export class TestController {
constructor(private $scope: TestScope, private storage: ng.localStorage.ILocalStorageService) {
storage.bind($scope, 'varName');
storage.bind($scope,'varName', { defaultValue: 'randomValue123', storeName: 'customStoreKey' });
$scope.viewType = 'ANYTHING';
storage.unbind($scope, 'viewType');
storage.set('key', 'value');
storage.get('key');
storage.remove('key');
storage.clearAll();
}
}
}
var app = angular.module('angularLocalStorageTests', ['angularLocalStorage']);
app.controller('testCtrl', ['$scope', 'storage', ($scope: TestScope, storage: ng.localStorage.ILocalStorageService) => new ng.LocalStorageTests.TestController($scope, storage)]);
+22
View File
@@ -0,0 +1,22 @@
// Type definitions for AngularLocalStorage 0.1.7
// Project: https://github.com/agrublev/angularLocalStorage
// Definitions by: Horiuchi_H <https://github.com/horiuchi/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts"/>
declare module ng.localStorage {
interface ILocalStorageService {
set(key: string, value: any): any;
get(key: string): any;
remove(key: string): boolean;
clearAll(): void;
bind($scope: ng.IScope, key: string, opts?: {
defaultValue?: any;
storeName?: string;
}): any;
unbind($scope: ng.IScope, key: string, storeName?: string): void;
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.2+ (ngAnimate module)
// Project: http://angularjs.org
// Definitions by: Michel Salib <michelsalib@hotmail.com>
// Definitions by: Michel Salib <https://github.com/michelsalib>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
+1 -1
View File
@@ -1,4 +1,4 @@
/// Type definitions for Angular JS 1.2 (ngCookies module)
// Type definitions for Angular JS 1.2 (ngCookies module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+18 -1
View File
@@ -21,6 +21,15 @@ mock.inject(
function () { return 2; }
);
mock.inject(
['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }]);
// This overload is not documented on the website, but flows from
// how the injector works.
mock.inject(
['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }],
['$rootScope', function ($rootScope: ng.IRootScopeService) { return 2; }]);
mock.module('module1', 'module2');
mock.module(
function () { return 1; },
@@ -41,7 +50,7 @@ exceptionHandlerProvider.mode('log');
///////////////////////////////////////
// IExceptionHandlerProvider
// ITimeoutService
///////////////////////////////////////
var timeoutService: ng.ITimeoutService;
@@ -51,6 +60,14 @@ timeoutService.flushNext();
timeoutService.flushNext(1234);
timeoutService.verifyNoPendingTasks();
////////////////////////////////////////
// IIntervalService
////////////////////////////////////////
var intervalService: ng.IIntervalService;
var intervalServiceTimeActuallyAdvanced: number;
intervalServiceTimeActuallyAdvanced = intervalService.flush();
intervalServiceTimeActuallyAdvanced = intervalService.flush(1234);
///////////////////////////////////////
// ILogService, ILogCall
+11 -3
View File
@@ -30,11 +30,10 @@ declare module ng {
// see http://docs.angularjs.org/api/angular.mock.inject
inject(...fns: Function[]): any;
inject(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
// see http://docs.angularjs.org/api/angular.mock.module
module(...modules: string[]): any;
module(...modules: Function[]): any;
module(modules: Object): any;
module(...modules: any[]): any;
// see http://docs.angularjs.org/api/angular.mock.TzDate
TzDate(offset: number, timestamp: number): Date;
@@ -60,6 +59,15 @@ declare module ng {
flushNext(expectedDelay?: number): void;
verifyNoPendingTasks(): void;
}
///////////////////////////////////////////////////////////////////////////
// IntervalService
// see http://docs.angularjs.org/api/ngMock.$interval
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
flush(millis?: number): number;
}
///////////////////////////////////////////////////////////////////////////
// LogService
+52 -1
View File
@@ -19,7 +19,7 @@ actionDescriptor.params = { key: 'value' };
///////////////////////////////////////
var resourceClass: IMyResourceClass;
var resource: IMyResource;
var resourceArray: IMyResource[];
var resourceArray: ng.resource.IResourceArray<IMyResource>;
resource = resourceClass.delete();
resource = resourceClass.delete({ key: 'value' });
@@ -29,6 +29,7 @@ resource = resourceClass.delete(function () { }, function () { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function () { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function () { }, function () { });
resource.$promise.then(function(data: IMyResource) {});
resource = resourceClass.get();
resource = resourceClass.get({ key: 'value' });
@@ -47,6 +48,8 @@ resourceArray = resourceClass.query(function () { }, function () { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { }, function () { });
resourceArray.push(resource);
resourceArray.$promise.then(function(data: ng.resource.IResourceArray<IMyResource>) {});
resource = resourceClass.remove();
resource = resourceClass.remove({ key: 'value' });
@@ -66,6 +69,50 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { }, function () { });
///////////////////////////////////////
// IResource
///////////////////////////////////////
var promise : ng.IPromise<IMyResource>;
var arrayPromise : ng.IPromise<IMyResource[]>;
promise = resource.$delete();
promise = resource.$delete({ key: 'value' });
promise = resource.$delete({ key: 'value' }, function () { });
promise = resource.$delete(function () { });
promise = resource.$delete(function () { }, function () { });
promise = resource.$delete({ key: 'value' }, function () { }, function () { });
promise.then(function(data: IMyResource) {});
promise = resource.$get();
promise = resource.$get({ key: 'value' });
promise = resource.$get({ key: 'value' }, function () { });
promise = resource.$get(function () { });
promise = resource.$get(function () { }, function () { });
promise = resource.$get({ key: 'value' }, function () { }, function () { });
arrayPromise = resourceArray[0].$query();
arrayPromise = resourceArray[0].$query({ key: 'value' });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { });
arrayPromise = resourceArray[0].$query(function () { });
arrayPromise = resourceArray[0].$query(function () { }, function () { });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { }, function () { });
arrayPromise.then(function(data: ng.resource.IResourceArray<IMyResource>) {});
promise = resource.$remove();
promise = resource.$remove({ key: 'value' });
promise = resource.$remove({ key: 'value' }, function () { });
promise = resource.$remove(function () { });
promise = resource.$remove(function () { }, function () { });
promise = resource.$remove({ key: 'value' }, function () { }, function () { });
promise = resource.$save();
promise = resource.$save({ key: 'value' });
promise = resource.$save({ key: 'value' }, function () { });
promise = resource.$save(function () { });
promise = resource.$save(function () { }, function () { });
promise = resource.$save({ key: 'value' }, function () { }, function () { });
///////////////////////////////////////
// IResourceService
///////////////////////////////////////
@@ -85,3 +132,7 @@ resourceClass = resourceServiceFactoryFunction<IMyResourceClass>(resourceService
resourceServiceFactoryFunction = function (resourceService: ng.resource.IResourceService) { return <any>resourceClass; };
mod = mod.factory('factory name', resourceServiceFactoryFunction);
///////////////////////////////////////
// IResource
///////////////////////////////////////
+61 -44
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.2 (ngResource module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Michael Jess <http://github.com/miffels>
// Definitions: https://github.com/daptiv/DefinitelyTyped
/// <reference path="angular.d.ts" />
@@ -50,67 +50,84 @@ 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
//
// Only those methods with an HTTP body do have 'data' as first parameter:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L463
// More specifically, those methods are POST, PUT and PATCH:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L432
//
// Also, static calls always return the IResource (or IResourceArray) retrieved
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549
interface IResourceClass<T> {
new(dataOrParams? : any) : T;
get(): T;
get(dataOrParams: any): T;
get(dataOrParams: any, success: Function): T;
get(params: Object): T;
get(success: Function, error?: Function): T;
get(params: any, data: any, success?: Function, error?: Function): T;
get(params: Object, success: Function, error?: Function): T;
get(params: Object, data: Object, success?: Function, error?: Function): T;
query(): IResourceArray<T>;
query(params: Object): IResourceArray<T>;
query(success: Function, error?: Function): IResourceArray<T>;
query(params: Object, success: Function, error?: Function): IResourceArray<T>;
query(params: Object, data: Object, success?: Function, error?: Function): IResourceArray<T>;
save(): T;
save(dataOrParams: any): T;
save(dataOrParams: any, success: Function): T;
save(data: Object): T;
save(success: Function, error?: Function): T;
save(params: any, data: any, success?: Function, error?: Function): T;
query(): T[];
query(dataOrParams: any): T[];
query(dataOrParams: any, success: Function): T[];
query(success: Function, error?: Function): T[];
query(params: any, data: any, success?: Function, error?: Function): T[];
save(data: Object, success: Function, error?: Function): T;
save(params: Object, data: Object, success?: Function, error?: Function): T;
remove(): T;
remove(dataOrParams: any): T;
remove(dataOrParams: any, success: Function): T;
remove(params: Object): T;
remove(success: Function, error?: Function): T;
remove(params: any, data: any, success?: Function, error?: Function): T;
remove(params: Object, success: Function, error?: Function): T;
remove(params: Object, data: Object, success?: Function, error?: Function): T;
delete(): T;
delete(dataOrParams: any): T;
delete(dataOrParams: any, success: Function): T;
delete(params: Object): T;
delete(success: Function, error?: Function): T;
delete(params: any, data: any, success?: Function, error?: Function): T;
delete(params: Object, success: Function, error?: Function): T;
delete(params: Object, data: Object, success?: Function, error?: Function): T;
}
// Instance calls always return the the promise of the request which retrieved the object
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L546
interface IResource<T> {
$get(): T;
$get(dataOrParams: any): T;
$get(dataOrParams: any, success: Function): T;
$get(success: Function, error?: Function): T;
$get(params: any, data: any, success?: Function, error?: Function): T;
$save(): T;
$save(dataOrParams: any): T;
$save(dataOrParams: any, success: Function): T;
$save(success: Function, error?: Function): T;
$save(params: any, data: any, success?: Function, error?: Function): T;
$query(): T[];
$query(dataOrParams: any): T[];
$query(dataOrParams: any, success: Function): T[];
$query(success: Function, error?: Function): T[];
$query(params: any, data: any, success?: Function, error?: Function): T[];
$remove(): T;
$remove(dataOrParams: any): T;
$remove(dataOrParams: any, success: Function): T;
$remove(success: Function, error?: Function): T;
$remove(params: any, data: any, success?: Function, error?: Function): T;
$delete(): T;
$delete(dataOrParams: any): T;
$delete(dataOrParams: any, success: Function): T;
$delete(success: Function, error?: Function): T;
$delete(params: any, data: any, success?: Function, error?: Function): T;
$get(): ng.IPromise<T>;
$get(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$get(success: Function, error?: Function): ng.IPromise<T>;
$query(): ng.IPromise<IResourceArray<T>>;
$query(params?: Object, success?: Function, error?: Function): ng.IPromise<IResourceArray<T>>;
$query(success: Function, error?: Function): ng.IPromise<IResourceArray<T>>;
$save(): ng.IPromise<T>;
$save(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$save(success: Function, error?: Function): ng.IPromise<T>;
$remove(): ng.IPromise<T>;
$remove(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$remove(success: Function, error?: Function): ng.IPromise<T>;
$delete(): ng.IPromise<T>;
$delete(params?: Object, success?: Function, error?: Function): ng.IPromise<T>;
$delete(success: Function, error?: Function): ng.IPromise<T>;
/** the promise of the original server interaction that created this instance. **/
$promise : ng.IPromise<T>;
$resolved : boolean;
}
/**
* Really just a regular Array object with $promise and $resolve attached to it
*/
interface IResourceArray<T> extends Array<T> {
/** the promise of the original server interaction that created this collection. **/
$promise : ng.IPromise<IResourceArray<T>>;
$resolved : boolean;
}
/** when creating a resource factory via IModule.factory */
interface IResourceServiceFactoryFunction<T> {
($resource: ng.resource.IResourceService): IResourceClass<T>;
+4 -1
View File
@@ -9,6 +9,9 @@
declare var $routeProvider: ng.route.IRouteProvider;
$routeProvider
.when('/projects/:projectId/dashboard',{
controller: ''
controller: '',
templateUrl: '',
caseInsensitiveMatch: true,
reloadOnSearch: false
})
.otherwise({redirectTo: '/'});
+79 -7
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.2 (ngRoute module)
// Project: http://angularjs.org
// Definitions by: Jonathan Park
// Definitions by: Jonathan Park <https://github.com/park9140>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
@@ -15,7 +15,9 @@ declare module ng.route {
// RouteParamsService
// see http://docs.angularjs.org/api/ngRoute.$routeParams
///////////////////////////////////////////////////////////////////////////
interface IRouteParamsService {}
interface IRouteParamsService {
[key: string]: any;
}
///////////////////////////////////////////////////////////////////////////
// RouteService
@@ -30,17 +32,73 @@ declare module ng.route {
// to a controller that was not initialized as a result of a route maching.
current?: ICurrentRoute;
}
// see http://docs.angularjs.org/api/ngRoute.$routeProvider#when for options explanations
/**
* see http://docs.angularjs.org/api/ngRoute/provider/$routeProvider#when for API documentation
*/
interface IRoute {
/**
* {(string|function()=}
* Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.
*/
controller?: any;
controllerAs?: any;
/**
* A controller alias name. If present the controller will be published to scope under the controllerAs name.
*/
controllerAs?: string;
/**
* Undocumented?
*/
name?: string;
/**
* {string=|function()=}
* Html template as a string or a function that returns an html template as a string which should be used by ngView or ngInclude directives. This property takes precedence over templateUrl.
*
* If template is a function, it will be called with the following parameters:
*
* {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route
*/
template?: string;
/**
* {string=|function()=}
* Path or function that returns a path to an html template that should be used by ngView.
*
* If templateUrl is a function, it will be called with the following parameters:
*
* {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route
*/
templateUrl?: any;
/**
* {Object.<string, function>=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is:
*
* - key - {string}: a name of a dependency to be injected into the controller.
* - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead.
*/
resolve?: any;
/**
* {(string|function())=}
* Value to update $location path with and trigger route redirection.
*
* If redirectTo is a function, it will be called with the following parameters:
*
* - {Object.<string>} - route parameters extracted from the current $location.path() by applying the current route templateUrl.
* - {string} - current $location.path()
* - {Object} - current $location.search()
* - The custom redirectTo function is expected to return a string which will be used to update $location.path() and $location.search().
*/
redirectTo?: any;
/**
* Reload route when only $location.search() or $location.hash() changes.
*
* This option defaults to true. If the option is set to false and url in the browser changes, then $routeUpdate event is broadcasted on the root scope.
*/
reloadOnSearch?: boolean;
/**
* Match routes without being case sensitive
*
* This option defaults to false. If the option is set to true, then the particular route can be matched without being case sensitive
*/
caseInsensitiveMatch?: boolean;
}
@@ -55,10 +113,24 @@ declare module ng.route {
}
interface IRouteProvider extends IServiceProvider {
otherwise(params: any): IRouteProvider;
/**
* This is a description
* Sets route definition that will be used on route change when no other route definition is matched.
*
* @params Mapping information to be assigned to $route.current.
*/
otherwise(params: IRoute): IRouteProvider;
/**
* Adds a new route definition to the $route service.
*
* @param path Route path (matched against $location.path). If $location.path contains redundant trailing slash or is missing one, the route will still match and the $location.path will be updated to add or drop the trailing slash to exactly match the route definition.
*
* - path can contain named groups starting with a colon: e.g. :name. All characters up to the next slash are matched and stored in $routeParams under the given name when the route matches.
* - path can contain named groups starting with a colon and ending with a star: e.g.:name*. All characters are eagerly stored in $routeParams under the given name when the route matches.
* - path can contain optional named groups with a question mark: e.g.:name?.
*
* For example, routes like /color/:color/largecode/:largecode*\/edit will match /color/brown/largecode/code/with/slashes/edit and extract: color: brown and largecode: code/with/slashes.
*
* @param route Mapping information to be assigned to $route.current on route match.
*/
when(path: string, route: IRoute): IRouteProvider;
}
+1 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular Scenario Testing
// Project: http://angularjs.org
// Definitions by: RomanoLindano
// Definitions by: RomanoLindano <https://github.com/RomanoLindano>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
+321 -30
View File
@@ -7,27 +7,27 @@
* (c) 2012 Witold Szczerba
* License: MIT
*/
angular.module('http-auth-interceptor', [])
.provider('authService', function () {
/**
* Holds all the requests which failed due to 401 response,
* so they can be re-requested in future, once login is completed.
*/
var buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred<any>; }[] = [];
class AuthService {
/**
* Holds all the requests which failed due to 401 response,
* so they can be re-requested in future, once login is completed.
*/
buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred<any>; }[] = [];
/**
* Required by HTTP interceptor.
* Function is attached to provider to be invisible for regular users of this service.
*/
this.pushToBuffer = function (config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
buffer.push({
config: config,
deferred: deferred
});
}
/**
* Required by HTTP interceptor.
* Function is attached to provider to be invisible for regular users of this service.
*/
pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
this.buffer.push({
config: config,
deferred: deferred
});
}
this.$get = ['$rootScope', '$injector', <any>function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) {
$get = [
'$rootScope', '$injector', <any>function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) {
var $http: ng.IHttpService; //initialized later because of circular dependency problem
function retry(config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
$http = $http || $injector.get('$http');
@@ -36,20 +36,25 @@ angular.module('http-auth-interceptor', [])
});
}
function retryAll() {
for (var i = 0; i < buffer.length; ++i) {
retry(buffer[i].config, buffer[i].deferred);
for (var i = 0; i < this.buffer.length; ++i) {
retry(this.buffer[i].config, this.buffer[i].deferred);
}
buffer = [];
this.buffer = [];
}
return {
return {
loginConfirmed: function () {
$rootScope.$broadcast('event:auth-loginConfirmed');
retryAll();
}
}
}]
})
}
];
}
angular.module('http-auth-interceptor', [])
.provider('authService', AuthService)
/**
* $http interceptor.
@@ -64,7 +69,7 @@ angular.module('http-auth-interceptor', [])
function error(response: ng.IHttpPromiseCallbackArg<any>) {
if (response.status === 401) {
var deferred = $q.defer();
var deferred = $q.defer<void>();
authServiceProvider.pushToBuffer(response.config, deferred);
$rootScope.$broadcast('event:auth-loginRequired');
return deferred.promise;
@@ -95,15 +100,16 @@ module HttpAndRegularPromiseTests {
theAnswer: number;
letters: string[];
snack: string;
nothing?: string;
}
var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => {
$http.get("http://somewhere/some/resource")
$http.get<ExpectedResponse>("http://somewhere/some/resource")
.success((data: ExpectedResponse) => {
$scope.person = data;
});
$http.get("http://somewhere/some/resource")
$http.get<ExpectedResponse>("http://somewhere/some/resource")
.then((response: ng.IHttpPromiseCallbackArg<ExpectedResponse>) => {
// typing lost, so something like
// var i: number = response.data
@@ -111,7 +117,7 @@ module HttpAndRegularPromiseTests {
$scope.person = response.data;
});
$http.get("http://somewhere/some/resource")
$http.get<ExpectedResponse>("http://somewhere/some/resource")
.then((response: ng.IHttpPromiseCallbackArg<ExpectedResponse>) => {
// typing lost, so something like
// var i: number = response.data
@@ -139,6 +145,12 @@ module HttpAndRegularPromiseTests {
dPromise.then((snack: string) => {
$scope.snack = snack;
});
// $q.when may be called without arguments
var ePromise: ng.IPromise<void> = $q.when();
ePromise.then(() => {
$scope.nothing = "really nothing";
});
}
// Test that we can pass around a type-checked success/error Promise Callback
@@ -148,7 +160,7 @@ module HttpAndRegularPromiseTests {
var buildFooData: Function = () => 42;
var doFoo: Function = (callback: ng.IHttpPromiseCallback<ExpectedResponse>) => {
$http.get('/foo', buildFooData())
$http.get<ExpectedResponse>('/foo', buildFooData())
.success(callback);
}
@@ -176,7 +188,8 @@ mod.factory(My.Namespace);
mod.filter('name', function ($scope: ng.IScope) { })
mod.filter('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.filter(My.Namespace);
mod.provider('name', function ($scope: ng.IScope) { })
mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } })
mod.provider('name', TestProvider);
mod.provider('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.provider(My.Namespace);
mod.service('name', function ($scope: ng.IScope) { })
@@ -189,6 +202,13 @@ mod.value('name', 23);
mod.value('name', "23");
mod.value(My.Namespace);
class TestProvider implements ng.IServiceProvider {
constructor(private $scope: ng.IScope) {
}
$get() {
}
}
// Promise signature tests
var foo: ng.IPromise<number>;
@@ -220,9 +240,30 @@ foo.then((x) => {
});
var httpFoo: ng.IHttpPromise<number>;
httpFoo.then((x) => {
// When returning a promise the generic type must be inferred.
var innerPromise : ng.IPromise<number>;
return innerPromise;
}).then((x) => {
// must still be number.
x.toFixed();
});
function test_angular_forEach() {
var values: { [key: string]: string } = { name: 'misko', gender: 'male' };
var log: string[] = [];
angular.forEach(values, function (value, key) {
this.push(key + ': ' + value);
}, log);
//expect(log).toEqual(['name: misko', 'gender: male']);
}
// angular.element() tests
var element = angular.element("div.myApp");
var scope: ng.IScope = element.scope();
var isolateScope: ng.IScope = element.isolateScope();
@@ -239,3 +280,253 @@ test_IAttributes({
},
$attr: {}
});
// test from https://docs.angularjs.org/guide/directive
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
return {
template: 'Name: {{customer.name}} Address: {{customer.address}}'
};
});
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
return {
templateUrl: 'my-customer.html'
};
});
angular.module('docsRestrictDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
templateUrl: 'my-customer.html'
};
});
angular.module('docsScopeProblemExample', [])
.controller('NaomiController', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.controller('IgorController', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Igor',
address: '123 Somewhere'
};
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
templateUrl: 'my-customer.html'
};
});
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.igor = { name: 'Igor', address: '123 Somewhere' };
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-iso.html'
};
});
angular.module('docsIsolationExample', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-plus-vojta.html'
};
});
angular.module('docsTimeDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.format = 'M/d/yy h:mm:ss a';
}])
.directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective {
return {
link: function(scope: any, element: any, attrs: any) {
var format: any,
timeoutId: any;
function updateTime() {
element.text(dateFilter(new Date(), format));
}
scope.$watch(attrs.myCurrentTime, function (value: any) {
format = value;
updateTime();
});
element.on('$destroy', function () {
$interval.cancel(timeoutId);
});
// start the UI update process; save the timeoutId for canceling
timeoutId = $interval(function () {
updateTime(); // update DOM
}, 1000);
}
};
}]);
angular.module('docsTransclusionDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.name = 'Tobias';
}])
.directive('myDialog', function() {
return {
restrict: 'E',
transclude: true,
templateUrl: 'my-dialog.html'
};
});
angular.module('docsTransclusionExample', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.name = 'Tobias';
}])
.directive('myDialog', function() {
return {
restrict: 'E',
transclude: true,
scope: {},
templateUrl: 'my-dialog.html',
link: function (scope: any, element: any) {
scope.name = 'Jeff';
}
};
});
angular.module('docsIsoFnBindExample', [])
.controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) {
$scope.name = 'Tobias';
$scope.hideDialog = function () {
$scope.dialogIsHidden = true;
$timeout(function () {
$scope.dialogIsHidden = false;
}, 2000);
};
}])
.directive('myDialog', function() {
return {
restrict: 'E',
transclude: true,
scope: {
'close': '&onClose'
},
templateUrl: 'my-dialog-close.html'
};
});
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document: any) {
return function(scope: any, element: any, attr: any) {
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer'
});
element.on('mousedown', function(event: any) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event: any) {
y = event.pageY - startY;
x = event.pageX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
};
}]);
angular.module('docsTabsExample', [])
.directive('myTabs', function() {
return {
restrict: 'E',
transclude: true,
scope: {},
controller: function($scope: any) {
var panes: any = $scope.panes = [];
$scope.select = function(pane: any) {
angular.forEach(panes, function(pane: any) {
pane.selected = false;
});
pane.selected = true;
};
this.addPane = function(pane: any) {
if (panes.length === 0) {
$scope.select(pane);
}
panes.push(pane);
};
},
templateUrl: 'my-tabs.html'
};
})
.directive('myPane', function() {
return {
require: '^myTabs',
restrict: 'E',
transclude: true,
scope: {
title: '@'
},
link: function(scope, element, attrs, tabsCtrl) {
tabsCtrl.addPane(scope);
},
templateUrl: 'my-pane.html'
};
});
+397 -86
View File
@@ -18,6 +18,15 @@ interface Function {
///////////////////////////////////////////////////////////////////////////////
declare module ng {
// not directly implemented, but ensures that constructed class implements $get
interface IServiceProviderClass {
new(...args: any[]): IServiceProvider;
}
interface IServiceProviderFactory {
(...args: any[]): IServiceProvider;
}
// All service providers extend this interface
interface IServiceProvider {
$get: any;
@@ -37,7 +46,38 @@ declare module ng {
element: IAugmentedJQueryStatic;
equals(value1: any, value2: any): boolean;
extend(destination: any, ...sources: any[]): any;
/**
* Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.
*
* It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method.
*
* @param obj Object to iterate over.
* @param iterator Iterator function.
* @param context Object to become context (this) for the iterator function.
*/
forEach<T>(obj: T[], iterator: (value: T, key: number) => any, context?: any): any;
/**
* Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.
*
* It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method.
*
* @param obj Object to iterate over.
* @param iterator Iterator function.
* @param context Object to become context (this) for the iterator function.
*/
forEach<T>(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any;
/**
* Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.
*
* It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method.
*
* @param obj Object to iterate over.
* @param iterator Iterator function.
* @param context Object to become context (this) for the iterator function.
*/
forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any;
fromJson(json: string): any;
identity(arg?: any): any;
injector(modules?: any[]): auto.IInjectorService;
@@ -51,16 +91,21 @@ declare module ng {
isString(value: any): boolean;
isUndefined(value: any): boolean;
lowercase(str: string): string;
/** construct your angular application
official docs: Interface for configuring angular modules.
see: http://docs.angularjs.org/api/angular.Module
*/
/**
* The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism.
*
* When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved.
*
* @param name The name of the module to create or retrieve.
* @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration.
* @param configFn Optional configuration function for the module.
*/
module(
/** name of your module you want to create */
name: string,
/** name of modules yours depends on */
requires?: string[],
configFunction?: any): IModule;
configFn?: Function): IModule;
noop(...args: any[]): void;
toJson(obj: any, pretty?: boolean): string;
uppercase(str: string): string;
@@ -81,37 +126,90 @@ declare module ng {
animation(name: string, animationFactory: Function): 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
*/
/**
* Use this method to register work which needs to be performed on module loading.
*
* @param configFn Execute this function on module load. Useful for service configuration.
*/
config(configFn: Function): IModule;
/** configure existing services.
Use this method to register work which needs to be performed on module loading
*/
/**
* Use this method to register work which needs to be performed on module loading.
*
* @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration.
*/
config(inlineAnnotatedFunction: any[]): IModule;
/**
* Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator.
*
* @param name The name of the constant.
* @param value The constant value.
*/
constant(name: string, value: any): IModule;
constant(object: Object): IModule;
/**
* The $controller service is used by Angular to create new controllers.
*
* This provider allows controller registration via the register method.
*
* @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.
* @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).
*/
controller(name: string, controllerConstructor: Function): IModule;
/**
* The $controller service is used by Angular to create new controllers.
*
* This provider allows controller registration via the register method.
*
* @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.
* @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).
*/
controller(name: string, inlineAnnotatedConstructor: any[]): IModule;
controller(object : Object): IModule;
directive(name: string, directiveFactory: Function): IModule;
directive(name: string, directiveFactory: IDirectiveFactory): IModule;
directive(name: string, inlineAnnotatedFunction: any[]): IModule;
directive(object: Object): IModule;
factory(name: string, serviceFactoryFunction: Function): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
*
* @param name The name of the instance.
* @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
*/
factory(name: string, $getFn: Function): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
*
* @param name The name of the instance.
* @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
*/
factory(name: string, inlineAnnotatedFunction: any[]): IModule;
factory(object: Object): IModule;
filter(name: string, filterFactoryFunction: Function): IModule;
filter(name: string, inlineAnnotatedFunction: any[]): IModule;
filter(object: Object): IModule;
provider(name: string, serviceProviderConstructor: Function): IModule;
provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule;
provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule;
provider(name: string, inlineAnnotatedConstructor: any[]): IModule;
provider(name: string, providerObject: auto.IProvider): IModule;
provider(name: string, providerObject: IServiceProvider): IModule;
provider(object: Object): IModule;
/**
* Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
*/
run(initializationFunction: Function): IModule;
/**
* Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
*/
run(inlineAnnotatedFunction: any[]): IModule;
service(name: string, serviceConstructor: Function): IModule;
service(name: string, inlineAnnotatedConstructor: any[]): IModule;
service(object: Object): IModule;
/**
* Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service.
Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator.
*
* @param name The name of the instance.
* @param value The value.
*/
value(name: string, value: any): IModule;
value(object: Object): IModule;
@@ -125,10 +223,10 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.$compile.directive.Attributes
///////////////////////////////////////////////////////////////////////////
interface IAttributes {
// this is necessary to be able to access the scoped attributes. it's not very elegant
// because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way
// this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656
[name: string]: any;
// this is necessary to be able to access the scoped attributes. it's not very elegant
// because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way
// this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656
[name: string]: any;
// Adds the CSS class value specified by the classVal parameter to the
// element. If animations are enabled then an animation will be triggered
@@ -154,11 +252,17 @@ declare module ng {
$attr: Object;
}
///////////////////////////////////////////////////////////////////////////
// FormController
// see http://docs.angularjs.org/api/ng.directive:form.FormController
///////////////////////////////////////////////////////////////////////////
/**
* form.FormController - type in module ng
* see https://docs.angularjs.org/api/ng/type/form.FormController
*/
interface IFormController {
/**
* Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272
*/
[name: string]: any;
$pristine: boolean;
$dirty: boolean;
$valid: boolean;
@@ -166,6 +270,7 @@ declare module ng {
$error: any;
$addControl(control: ng.INgModelController): void;
$removeControl(control: ng.INgModelController): void;
$setValidity(validationErrorKey: string, isValid: boolean, control: ng.INgModelController): void;
$setDirty(): void;
$setPristine(): void;
}
@@ -186,6 +291,7 @@ declare module ng {
$parsers: IModelParser[];
$formatters: IModelFormatter[];
$viewChangeListeners: IModelViewChangeListener[];
$error: any;
$pristine: boolean;
$dirty: boolean;
@@ -201,6 +307,10 @@ declare module ng {
(value: any): any;
}
interface IModelViewChangeListener {
(): void;
}
///////////////////////////////////////////////////////////////////////////
// Scope
// see http://docs.angularjs.org/api/ng.$rootScope.Scope
@@ -236,8 +346,13 @@ declare module ng {
$watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;
$watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;
$watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;
$watchGroup(watchExpressions: {(scope: IScope) : any}[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;
$parent: IScope;
$root: IRootScopeService;
$id: string;
// Hidden members
@@ -260,13 +375,17 @@ declare module ng {
// WindowService
// see http://docs.angularjs.org/api/ng.$window
///////////////////////////////////////////////////////////////////////////
interface IWindowService extends Window {}
interface IWindowService extends Window {
[key: string]: any;
}
///////////////////////////////////////////////////////////////////////////
// BrowserService
// TODO undocumented, so we need to get it from the source code
///////////////////////////////////////////////////////////////////////////
interface IBrowserService {}
interface IBrowserService {
[key: string]: any;
}
///////////////////////////////////////////////////////////////////////////
// TimeoutService
@@ -351,6 +470,7 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
// LogService
// see http://docs.angularjs.org/api/ng.$log
// see http://docs.angularjs.org/api/ng.$logProvider
///////////////////////////////////////////////////////////////////////////
interface ILogService {
debug: ILogCall;
@@ -360,6 +480,11 @@ declare module ng {
warn: ILogCall;
}
interface ILogProvider {
debugEnabled(enabled: boolean): ILogProvider;
debugEnabled(): boolean;
}
// We define this as separete interface so we can reopen it later for
// the ngMock module.
interface ILogCall {
@@ -376,11 +501,11 @@ declare module ng {
}
interface IParseProvider {
logPromiseWarnings(): boolean;
logPromiseWarnings(value: boolean): IParseProvider;
logPromiseWarnings(): boolean;
logPromiseWarnings(value: boolean): IParseProvider;
unwrapPromises(): boolean;
unwrapPromises(value: boolean): IParseProvider;
unwrapPromises(): boolean;
unwrapPromises(value: boolean): IParseProvider;
}
interface ICompiledExpression {
@@ -446,17 +571,58 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
interface IRootElementService extends JQuery {}
///////////////////////////////////////////////////////////////////////////
// QService
// see http://docs.angularjs.org/api/ng.$q
///////////////////////////////////////////////////////////////////////////
/**
* $q - service in module ng
* A promise/deferred implementation inspired by Kris Kowal's Q.
* See http://docs.angularjs.org/api/ng/service/$q
*/
interface IQService {
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
*
* Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.
*
* @param promises An array or hash of promises.
*/
all(promises: IPromise<any>[]): IPromise<any[]>;
all(promises: {[id: string]: IPromise<any>;}): IPromise<{[id: string]: any}>;
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
*
* Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.
*
* @param promises An array or hash of promises.
*/
all(promises: { [id: string]: IPromise<any>; }): IPromise<{ [id: string]: any }>;
/**
* Creates a Deferred object which represents a task which will finish in the future.
*/
defer<T>(): IDeferred<T>;
/**
* Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject.
*
* @param reason Constant, message, exception or an object representing the rejection reason.
*/
reject(reason?: any): IPromise<void>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
* @param value Value or a promise
*/
when<T>(value: IPromise<T>): IPromise<T>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
* @param value Value or a promise
*/
when<T>(value: T): IPromise<T>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
* @param value Value or a promise
*/
when(): IPromise<void>;
}
interface IPromise<T> {
@@ -538,6 +704,12 @@ declare module ng {
// Undocumented, but it is there...
directive(directivesMap: any): ICompileProvider;
aHrefSanitizationWhitelist(): RegExp;
aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider;
imgSrcSanitizationWhitelist(): RegExp;
imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider;
}
interface ICloneAttachFunction {
@@ -574,44 +746,157 @@ declare module ng {
register(name: string, dependencyAnnotatedConstructor: any[]): void;
}
///////////////////////////////////////////////////////////////////////////
// HttpService
// see http://docs.angularjs.org/api/ng.$http
///////////////////////////////////////////////////////////////////////////
/**
* HttpService
* see http://docs.angularjs.org/api/ng/service/$http
*/
interface IHttpService {
// At least moethod and url must be provided...
(config: IRequestConfig): IHttpPromise<any>;
get (url: string, RequestConfig?: any): IHttpPromise<any>;
delete (url: string, RequestConfig?: any): IHttpPromise<any>;
head(url: string, RequestConfig?: any): IHttpPromise<any>;
jsonp(url: string, RequestConfig?: any): IHttpPromise<any>;
post(url: string, data: any, RequestConfig?: any): IHttpPromise<any>;
put(url: string, data: any, RequestConfig?: any): IHttpPromise<any>;
/**
* Object describing the request to be made and how it should be processed.
*/
<T>(config: IRequestConfig): IHttpPromise<T>;
/**
* Shortcut method to perform GET request.
*
* @param url Relative or absolute URL specifying the destination of the request
* @param config Optional configuration object
*/
get<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;
/**
* Shortcut method to perform DELETE request.
*
* @param url Relative or absolute URL specifying the destination of the request
* @param config Optional configuration object
*/
delete<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;
/**
* Shortcut method to perform HEAD request.
*
* @param url Relative or absolute URL specifying the destination of the request
* @param config Optional configuration object
*/
head<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;
/**
* Shortcut method to perform JSONP request.
*
* @param url Relative or absolute URL specifying the destination of the request
* @param config Optional configuration object
*/
jsonp<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;
/**
* Shortcut method to perform POST request.
*
* @param url Relative or absolute URL specifying the destination of the request
* @param data Request content
* @param config Optional configuration object
*/
post<T>(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise<T>;
/**
* Shortcut method to perform PUT request.
*
* @param url Relative or absolute URL specifying the destination of the request
* @param data Request content
* @param config Optional configuration object
*/
put<T>(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise<T>;
/**
* Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations.
*/
defaults: IRequestConfig;
// For debugging, BUT it is documented as public, so...
/**
* Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes.
*/
pendingRequests: any[];
}
// This is just for hinting.
// Some opetions might not be available depending on the request.
// see http://docs.angularjs.org/api/ng.$http#Usage for options explanations
interface IRequestConfig {
method: string;
url: string;
/**
* Object describing the request to be made and how it should be processed.
* see http://docs.angularjs.org/api/ng/service/$http#usage
*/
interface IRequestShortcutConfig {
/**
* {Object.<string|Object>}
* Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
*/
params?: any;
// XXX it has it's own structure... perhaps we should define it in the future
/**
* Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent.
*/
headers?: any;
/**
* Name of HTTP header to populate with the XSRF token.
*/
xsrfHeaderName?: string;
/**
* Name of cookie containing the XSRF token.
*/
xsrfCookieName?: string;
/**
* {boolean|Cache}
* If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
*/
cache?: any;
/**
* whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information.
*/
withCredentials?: boolean;
// These accept multiple types, so let's define them as any
/**
* {string|Object}
* Data to be sent as the request message data.
*/
data?: any;
/**
* {function(data, headersGetter)|Array.<function(data, headersGetter)>}
* Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.
*/
transformRequest?: any;
/**
* {function(data, headersGetter)|Array.<function(data, headersGetter)>}
* Transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version.
*/
transformResponse?: any;
timeout?: any; // number | promise
/**
* {number|Promise}
* Timeout in milliseconds, or promise that should abort the request when resolved.
*/
timeout?: any;
/**
* See requestType.
*/
responseType?: string;
}
/**
* Object describing the request to be made and how it should be processed.
* see http://docs.angularjs.org/api/ng/service/$http#usage
*/
interface IRequestConfig extends IRequestShortcutConfig {
/**
* HTTP method (e.g. 'GET', 'POST', etc)
*/
method: string;
/**
* Absolute or relative URL of the resource that is being requested.
*/
url: string;
}
interface IHttpPromiseCallback<T> {
@@ -623,13 +908,14 @@ declare module ng {
status?: number;
headers?: (headerName: string) => string;
config?: IRequestConfig;
statusText?: string;
}
interface IHttpPromise<T> extends IPromise<T> {
success(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;
error(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg<T>) => any): IPromise<TResult>;
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => IPromise<TResult>, errorCallback?: (response: IHttpPromiseCallbackArg<T>) => any): IPromise<TResult>;
error(callback: IHttpPromiseCallback<any>): IHttpPromise<T>;
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => IPromise<TResult>, errorCallback?: (response: IHttpPromiseCallbackArg<any>) => any): IPromise<TResult>;
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg<any>) => any): IPromise<TResult>;
}
interface IHttpProvider extends IServiceProvider {
@@ -686,26 +972,26 @@ declare module ng {
// SCEService
// see http://docs.angularjs.org/api/ng.$sce
///////////////////////////////////////////////////////////////////////////
interface ISCEService {
getTrusted(type: string, mayBeTrusted: any): any;
getTrustedCss(value: any): any;
getTrustedHtml(value: any): any;
getTrustedJs(value: any): any;
getTrustedResourceUrl(value: any): any;
getTrustedUrl(value: any): any;
parse(type: string, expression: string): (context: any, locals: any) => any;
parseAsCss(expression: string): (context: any, locals: any) => any;
parseAsHtml(expression: string): (context: any, locals: any) => any;
parseAsJs(expression: string): (context: any, locals: any) => any;
parseAsResourceUrl(expression: string): (context: any, locals: any) => any;
parseAsUrl(expression: string): (context: any, locals: any) => any;
trustAs(type: string, value: any): any;
trustAsHtml(value: any): any;
trustAsJs(value: any): any;
trustAsResourceUrl(value: any): any;
trustAsUrl(value: any): any;
isEnabled(): boolean;
}
interface ISCEService {
getTrusted(type: string, mayBeTrusted: any): any;
getTrustedCss(value: any): any;
getTrustedHtml(value: any): any;
getTrustedJs(value: any): any;
getTrustedResourceUrl(value: any): any;
getTrustedUrl(value: any): any;
parse(type: string, expression: string): (context: any, locals: any) => any;
parseAsCss(expression: string): (context: any, locals: any) => any;
parseAsHtml(expression: string): (context: any, locals: any) => any;
parseAsJs(expression: string): (context: any, locals: any) => any;
parseAsResourceUrl(expression: string): (context: any, locals: any) => any;
parseAsUrl(expression: string): (context: any, locals: any) => any;
trustAs(type: string, value: any): any;
trustAsHtml(value: any): any;
trustAsJs(value: any): any;
trustAsResourceUrl(value: any): any;
trustAsUrl(value: any): any;
isEnabled(): boolean;
}
///////////////////////////////////////////////////////////////////////////
// SCEProvider
@@ -741,6 +1027,11 @@ declare module ng {
// and http://docs.angularjs.org/guide/directive
///////////////////////////////////////////////////////////////////////////
interface IDirectiveFactory {
(...args: any[]): IDirective;
}
interface IDirective{
compile?:
(templateElement: IAugmentedJQuery,
@@ -796,6 +1087,7 @@ declare module ng {
controller(name: string): any;
injector(): any;
scope(): IScope;
isolateScope(): IScope;
inheritedData(key: string, value: any): JQuery;
inheritedData(obj: { [key: string]: any; }): JQuery;
@@ -818,9 +1110,6 @@ declare module ng {
// AUTO module (angular.js)
///////////////////////////////////////////////////////////////////////////
export module auto {
interface IProvider {
$get: any;
}
///////////////////////////////////////////////////////////////////////
// InjectorService
@@ -830,7 +1119,7 @@ declare module ng {
annotate(fn: Function): string[];
annotate(inlineAnnotatedFunction: any[]): string[];
get(name: string): any;
has(name: string): boolean;
has(name: string): boolean;
instantiate(typeConstructor: Function, locals?: any): any;
invoke(inlineAnnotatedFunction: any[]): any;
invoke(func: Function, context?: any, locals?: any): any;
@@ -844,10 +1133,32 @@ declare module ng {
// Documentation says it returns the registered instance, but actual
// implementation does not return anything.
// constant(name: string, value: any): any;
/**
* Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator.
*
* @param name The name of the constant.
* @param value The constant value.
*/
constant(name: string, value: any): void;
/**
* Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.
*
* @param name The name of the service to decorate.
* @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:
*
* $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.
*/
decorator(name: string, decorator: Function): void;
decorator(name: string, decoratorInline: any[]): void;
/**
* Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.
*
* @param name The name of the service to decorate.
* @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:
*
* $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.
*/
decorator(name: string, inlineAnnotatedFunction: any[]): void;
factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider;
factory(name: string, inlineAnnotatedFunction: any[]): ng.IServiceProvider;
provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider;
+1 -1
View File
@@ -64,7 +64,7 @@ angular.module('http-auth-interceptor', [])
function error(response: ng.IHttpPromiseCallbackArg<any>) {
if (response.status === 401) {
var deferred = $q.defer();
var deferred = $q.defer<void>();
authServiceProvider.pushToBuffer(response.config, deferred);
$rootScope.$broadcast('event:auth-loginRequired');
return deferred.promise;
+9
View File
@@ -0,0 +1,9 @@
// Type definitions for ansicolors
// Project: https://github.com/thlorenz/ansicolors
// Definitions by: rogierschouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "ansicolors" {
var colors: {[index: string]: (s: string) => string;};
export = colors;
}
+2 -2
View File
@@ -121,12 +121,12 @@ declare module ArbiterDef {
/**
* Unsubscribing simply sets a flag which prevents the subscriber from executing, in case you want to re-subscribe later.
*/
unsubscribe(subscription_id: number);
unsubscribe(subscription_id: number): boolean;
/**
* After unsubscribing, you can later re-subscribe to begin receiving messages again.
*/
resubscribe(subscription_id: number);
resubscribe(subscription_id: number): boolean;
}
}
-1
View File
@@ -1 +0,0 @@
""
+2 -2
View File
@@ -1,6 +1,6 @@
// Type definitions for asciify 1.3.5
// Project: https://www.npmjs.org/package/asciify
// Definitions by: Alan Norbauer http://alan.norbauer.com
// Definitions by: Alan Norbauer <http://alan.norbauer.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
@@ -26,4 +26,4 @@ declare module "asciify" {
}
export = asciify
}
}
+60 -3
View File
@@ -145,9 +145,8 @@ q.drain = function () {
console.log('all items have been processed');
}
q.push({ name: 'foo' }, function (err) {
console.log('finished processing foo');
});
q.push({ name: 'foo' });
q.push({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
@@ -156,6 +155,64 @@ q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) {
console.log('finished processing bar');
});
q.unshift({ name: 'foo' });
q.unshift({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) {
console.log('finished processing bar');
});
var qLength : number = q.length();
var qStarted : boolean = q.started;
var qPaused : boolean = q.paused;
var qProcessingCount : number = q.running();
var qIsIdle : boolean = q.idle();
q.saturated = function() {
console.log('queue is saturated.');
}
q.empty = function() {
console.log('queue is empty.');
}
q.drain = function() {
console.log('queue was drained.');
}
q.pause();
q.resume();
q.kill();
// tests for strongly typed tasks
var q2 = async.queue(function (task: string, callback) {
console.log('Task: ' + task);
callback();
}, 1);
q2.push('task1');
q2.push('task2', function (error, results: string[]) {
console.log('Finished tasks: ' + results.join(', '));
});
q2.push(['task3', 'task4', 'task5'], function (error, results: string[]) {
console.log('Finished tasks: ' + results.join(', '));
});
q2.unshift('task1');
q2.unshift('task2', function (error, results: string[]) {
console.log('Finished tasks: ' + results.join(', '));
});
q2.unshift(['task3', 'task4', 'task5'], function (error, results: string[]) {
console.log('Finished tasks: ' + results.join(', '));
});
var filename = '';
async.auto({
get_data: function (callback) { },
+37 -27
View File
@@ -3,8 +3,8 @@
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AsyncMultipleResultsCallback<T> { (err: string, results: T[]): any; }
interface AsyncSingleResultCallback<T> { (err: string, result: T): void; }
interface AsyncMultipleResultsCallback<T> { (err: Error, results: T[]): any; }
interface AsyncSingleResultCallback<T> { (err: Error, result: T): void; }
interface AsyncTimesCallback<T> { (n: number, callback: AsyncMultipleResultsCallback<T>): void; }
interface AsyncIterator<T, R> { (item: T, callback: AsyncSingleResultCallback<R>): void; }
@@ -15,10 +15,20 @@ interface AsyncWorker<T> { (task: T, callback: Function): void; }
interface AsyncQueue<T> {
length(): number;
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, callback?: AsyncMultipleResultsCallback<T>): void;
saturated: AsyncMultipleResultsCallback<T>;
empty: AsyncMultipleResultsCallback<T>;
drain: AsyncMultipleResultsCallback<T>;
push(task: T[], callback?: AsyncMultipleResultsCallback<T>): void;
unshift(task: T, callback?: AsyncMultipleResultsCallback<T>): void;
unshift(task: T[], callback?: AsyncMultipleResultsCallback<T>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
running(): number;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface Async {
@@ -27,28 +37,28 @@ interface Async {
forEach<T,R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
forEachSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
forEachLimit<T, R>(arr: T[], limit: number, iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
map<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>);
mapSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>);
filter<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
select<T, R>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
filterSeries<T, R>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
selectSeries<T, R>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
reject<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
rejectSeries<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>);
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>);
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>);
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>);
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>);
detect<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
detectSeries<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
sortBy<T, V>(arr: T[], iterator: AsyncIterator<T, V>, callback: AsyncMultipleResultsCallback<T>);
some<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
any<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>);
every<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: (result: boolean) => any);
all<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: (result: boolean) => any);
concat<T, R>(arr: T[], iterator: AsyncIterator<T, R[]>, callback: AsyncMultipleResultsCallback<R>);
concatSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R[]>, callback: AsyncMultipleResultsCallback<R>);
map<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
select<T, R>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
filterSeries<T, R>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
selectSeries<T, R>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
reject<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
rejectSeries<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncSingleResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
detectSeries<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
sortBy<T, V>(arr: T[], iterator: AsyncIterator<T, V>, callback: AsyncMultipleResultsCallback<T>): any;
some<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
any<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
every<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncIterator<T, R[]>, callback: AsyncMultipleResultsCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R[]>, callback: AsyncMultipleResultsCallback<R>): any;
// Control Flow
series<T>(tasks: T[], callback?: AsyncMultipleResultsCallback<T>): void;
-1
View File
@@ -1 +0,0 @@
""
-1
View File
@@ -1 +0,0 @@
""
+46
View File
@@ -0,0 +1,46 @@
/// <reference path="atmosphere.d.ts" />
var socket = atmosphere;
var request1:Atmosphere.Request = new atmosphere.AtmosphereRequest();
request1.url = document.location.toString() + 'chat';
request1.contentType = "application/json";
request1.transport = 'websocket';
request1.fallbackTransport = 'long-polling';
var request2:Atmosphere.Request = {
url: 'http://localhost:8080/chat',
contentType: "application/json",
logLevel: 'debug',
transport: 'websocket',
fallbackTransport: 'long-polling'
};
request1.onError = function (response?:Atmosphere.Response) {};
request1.onClose = function (response?:Atmosphere.Response) {};
request1.onOpen = function (response?:Atmosphere.Response) {};
request1.onMessage = function (response:Atmosphere.Response) {};
request1.onReopen = function (request?:Atmosphere.Request, response?:Atmosphere.Response) {};
request1.onReconnect = function (request?:Atmosphere.Request, response?:Atmosphere.Response) {};
request1.onMessagePublished = function (response?:Atmosphere.Response) {};
request1.onTransportFailure = function (reason?:string, response?:Atmosphere.Response) {};
request1.onLocalMessage = function (request?:Atmosphere.Request) {};
request1.onFailureToReconnect = function (request?:Atmosphere.Request, response?:Atmosphere.Response) {};
request1.onClientTimeout = function (request?:Atmosphere.Request) {};
request1.subscribe = function (options:Atmosphere.Request) {};
request1.execute = function () {};
request1.close = function () {};
request1.disconnect = function () {};
request1.getUrl = function ():string { return "http://www.toedter.com" };
request1.push = function (message:string, dispatchUrl?:string) {};
request1.getUUID = function () {};
request1.pushLocal = function (message:string) {};
var subSocket:Atmosphere.Request = socket.subscribe(request1);
var subSocket2:Atmosphere.Request = socket.subscribe('http://chat.com', function() {}, request2);
subSocket2.close();
subSocket.push("test");
socket.unsubscribe();
+106
View File
@@ -0,0 +1,106 @@
// Type definitions for Atmosphere v2.1.5
// Project: https://github.com/Atmosphere/atmosphere-javascript
// Definitions by: Kai Toedter <https://github.com/toedter/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Atmosphere {
interface Atmosphere {
/**
* The atmosphere API is a little bit special here: the first parameter can either be
* a URL string or a Request object. If it is a URL string, then the additional parameters are expected.
*/
subscribe?: (requestOrUrl:any, callback?:Function, request?:Request) => Request;
unsubscribe?: () => void;
AtmosphereRequest?: AtmosphereRequest;
}
// needed to fit JavaScript "new atmosphere.AtmosphereRequest()"
// and compile with --noImplicitAny
interface AtmosphereRequest {
new(): Request;
}
interface Request {
timeout?: number;
method?: string;
headers?: any;
contentType?: string;
callback?: Function;
url?: string;
data?: string;
suspend?: boolean;
maxRequest?: number;
reconnect?: boolean;
maxStreamingLength?: number;
lastIndex?: number;
logLevel?: string;
requestCount?: number;
fallbackMethod?: string;
fallbackTransport?: string;
transport?: string;
webSocketImpl?: any;
webSocketBinaryType?: any;
dispatchUrl?: string;
webSocketPathDelimiter?: string;
enableXDR?: boolean;
rewriteURL?: boolean;
attachHeadersAsQueryString?: boolean;
executeCallbackBeforeReconnect?: boolean;
readyState?: number;
lastTimestamp?: number;
withCredentials?: boolean;
trackMessageLength?: boolean;
messageDelimiter?: string;
connectTimeout?: number;
reconnectInterval?: number;
dropHeaders?: boolean;
uuid?: number;
async?: boolean;
shared?: boolean;
readResponsesHeaders?: boolean;
maxReconnectOnClose?: number;
enableProtocol?: boolean;
pollingInterval?: number;
onError?: (response?:Response) => void;
onClose?: (response?:Response) => void;
onOpen?: (response?:Response) => void;
onMessage?: (response:Response) => void;
onReopen?: (request?:Request, response?:Response) => void;
onReconnect?: (request?:Request, response?:Response) => void;
onMessagePublished?: (response?:Response) => void;
onTransportFailure?: (reason?:string, response?:Response) => void;
onLocalMessage?: (request?:Request) => void;
onFailureToReconnect?: (request?:Request, response?:Response) => void;
onClientTimeout?: (request?:Request) => void;
subscribe?: (options:Request) => void;
execute?: () => void;
close?: () => void;
disconnect?: () => void;
getUrl?: () => string;
push?: (message:string, dispatchUrl?:string) => void;
getUUID?: () => void;
pushLocal?: (message:string) => void;
}
interface Response {
status?: number;
reasonPhrase?: string;
responseBody?: string;
messages?: string[];
headers?: string[];
state?: string;
transport?: string;
error?: string;
request?: Request;
partialMessage?: string;
errorHandled?: boolean;
closedByClientTimeout?: boolean;
}
}
declare var atmosphere:Atmosphere.Atmosphere;
+1 -1
View File
@@ -11,7 +11,7 @@ var File = pathwatcher.File;
class SampleView extends _atom.ScrollView {
editorId:string;
file:pathwatcher.IFile;
file:PathWatcher.IFile;
editor:AtomCore.IEditor;
static deserialize(state:any):SampleView {
+1132 -207
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="atpl.d.ts" />
import atpl = require('atpl');
var bool: boolean;
var str: string;
var err: Error;
var items: any;
var options: Object;
var callback: Function;
atpl.compile(str, options);
atpl.__express(str, options, callback);
atpl.registerExtension(items);
atpl.registerTags(items);
atpl.registerFunctions(items);
atpl.registerFilters(items);
atpl.registerTests(items);
atpl.registerTags(null);
atpl.renderFile(str, str, options, bool, (e, res?) => {
err = err;
str = res;
});
+20
View File
@@ -0,0 +1,20 @@
// Type definitions for atpl
// Project: https://github.com/soywiz/atpl.js
// Definitions by: Carlos Ballesteros Velasco <https://github.com/soywiz>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Imported from: https://github.com/soywiz/typescript-node-definitions/atpl.d.ts
declare module "atpl" {
export function compile(templateString: string, options: any): (context:any) => string;
export function __express(filename: string, options: any, callback: Function): any;
export function registerExtension(items: any): void;
export function registerTags(items: any): void;
export function registerFunctions(items: any): void;
export function registerFilters(items: any): void;
export function registerTests(items: any): void;
export function renderFileSync(viewsPath: string, filename: string, parameters: any, cache: boolean ): string;
export function renderFile(viewsPath: string, filename: string, parameters: any, cache: boolean, done: (err: Error, result?: string) => void): void;
}
+18
View File
@@ -0,0 +1,18 @@
/// <reference path="../auth0/auth0.d.ts" />
/// <reference path="auth0.widget.d.ts" />
var widget: Auth0WidgetStatic = new Auth0Widget({
domain: 'mine.auth0.com',
clientID: 'dsa7d77dsa7d7',
callbackURL: 'http://my-app.com/callback',
callbackOnLocationHash: true
});
widget.signin({
connections: ['facebook', 'google-oauth2', 'twitter', 'Username-Password-Authentication'],
icon: 'https://contoso.com/logo-32.png',
showIcon: true
},
() => {
// The Auth0 Widget is now loaded.
});
+48
View File
@@ -0,0 +1,48 @@
// Type definitions for Auth0Widget.js
// Project: http://auth0.com
// Definitions by: Robert McLaws <https://github.com/advancedrei>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../auth0/auth0.d.ts" />
interface Auth0WidgetStatic {
new(params: Auth0Constructor): Auth0WidgetStatic;
getClient(): Auth0Static;
getProfile(token: string, callback: Function): Auth0UserProfile;
parseHash(hash: string): Auth0DecodedHash;
reset(options: Auth0Options, callback?: Function): Auth0WidgetStatic;
signin(options: Auth0Options, widgetLoadedCallback?: Function, popupCallback?: Function): Auth0WidgetStatic;
signup(options: Auth0Options, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): Auth0WidgetStatic;
}
interface Auth0Constructor extends Auth0ClientOptions {
assetsUrl?: string;
cdn?: string;
dict?: any;
}
interface Auth0Options {
access_token?: string;
connections?: string[];
container?: string;
enableReturnUserExperience?: boolean;
extraParameters?: any;
icon?: string;
protocol?: string;
request_id?: string;
scope?: string;
showIcon?: boolean;
showForgot?: boolean;
showSignup?: boolean;
state?: any;
userPwdConnectionName?: string;
username_style?: string;
}
declare var Auth0Widget: Auth0WidgetStatic;
declare module "Auth0Widget" {
export = Auth0Widget
}
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="../auth0/auth0.d.ts" />
var auth0 = new Auth0({
domain: 'mine.auth0.com',
clientID: 'dsa7d77dsa7d7',
callbackURL: 'http://my-app.com/callback',
callbackOnLocationHash: true
});
auth0.login({
connection: 'google-oauth2',
popup: true,
popupOptions: {
width: 450,
height: 800
}
}, (err, profile, idToken, accessToken, state) => {
if (err) {
alert("something went wrong: " + err.message);
return;
}
alert('hello ' + profile.name);
});
+133
View File
@@ -0,0 +1,133 @@
// Type definitions for Auth0.js
// Project: http://auth0.com
// Definitions by: Robert McLaws <https://github.com/advancedrei>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/** Extensions to the browser Window object. */
interface Window {
/** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */
token: string;
}
interface Location {
origin: string;
}
/** This is the interface for the main Auth0 client. */
interface Auth0Static {
new(options: Auth0ClientOptions): Auth0Static;
changePassword(options: any, callback?: Function): void;
decodeJwt(jwt: string): any;
login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void;
loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
logout(query: string): void;
getConnections(callback?: Function): void;
getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void;
getProfile(id_token: string, callback?: Function): Auth0UserProfile;
getSSOData(withActiveDirectories: any, callback?: Function): void;
parseHash(hash: string): Auth0DecodedHash;
signup(options: Auth0SignupOptions, callback: Function): void;
validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void;
}
/** Represents constructor options for the Auth0 client. */
interface Auth0ClientOptions {
clientID: string;
callbackURL: string;
callbackOnLoactionHash?: boolean;
domain: string;
forceJSONP?: boolean;
}
/** Represents a normalized UserProfile. */
interface Auth0UserProfile {
email: string;
family_name: string;
gender: string;
given_name: string;
locale: string;
name: string;
nickname: string;
picture: string;
user_id: string;
/** Represents one or more Identities that may be associated with the User. */
identities: Auth0Identity[];
}
/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */
interface MicrosoftUserProfile extends Auth0UserProfile {
emails: string[];
}
/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */
interface Office365UserProfile extends Auth0UserProfile {
tenantid: string;
upn: string;
}
/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */
interface AdfsUserProfile extends Auth0UserProfile {
issuer: string;
}
/** Represents multiple identities assigned to a user. */
interface Auth0Identity {
access_token: string;
connection: string;
isSocial: boolean;
provider: string;
user_id: string;
}
interface Auth0DecodedHash {
access_token: string;
id_token: string;
profile: Auth0UserProfile;
state: any;
}
interface Auth0PopupOptions {
width: number;
height: number;
}
interface Auth0LoginOptions {
auto_login?: boolean;
connection?: string;
email?: string;
username?: string;
password?: string;
popup?: boolean;
popupOptions?: Auth0PopupOptions;
}
interface Auth0SignupOptions extends Auth0LoginOptions {
auto_login: boolean;
}
interface Auth0Error {
code: any;
details: any;
name: string;
message: string;
status: any;
}
/** Represents the response from an API Token Delegation request. */
interface Auth0DelegationToken {
/** The length of time in seconds the token is valid for. */
expires_in: string;
/** The JWT for delegated access. */
id_token: string;
/** The type of token being returned. Possible values: "Bearer" */
token_type: string;
}
declare var Auth0: Auth0Static;
declare module "Auth0" {
export = Auth0
}
+13
View File
@@ -0,0 +1,13 @@
/// <reference path="aws-sdk.d.ts" />
import awsSdk = require('aws-sdk');
var str: string;
var creds: awsSdk.Credentials;
creds = new awsSdk.Credentials(str, str);
creds = new awsSdk.Credentials(str, str, str);
str = creds.accessKeyId;
// more
+909
View File
@@ -0,0 +1,909 @@
// Type definitions for aws-sdk
// Project: https://github.com/aws/aws-sdk-js
// Definitions by: midknight41 <https://github.com/midknight41>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Imported from: https://github.com/soywiz/typescript-node-definitions/aws-sdk.d.ts
/// <reference path="../node/node.d.ts" />
declare module "aws-sdk" {
export var config: ClientConfig;
export function Config(json: any): void;
export class Credentials {
constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string);
accessKeyId: string;
}
export interface ClientConfig {
credentials: Credentials;
region: string;
}
export class SQS {
constructor(options?: any);
public client: Sqs.Client;
}
export class SES {
constructor(options?: any);
public client: Ses.Client;
}
export class SNS {
constructor(options?: any);
public client: Sns.Client;
}
export class SimpleWorkflow {
constructor(options?: any);
public client: Swf.Client;
}
export class S3 {
constructor(options?: any);
public client: s3.Client;
}
export module Sqs {
export interface Client {
config: ClientConfig;
sendMessage(params: SendMessageRequest, callback: (err: any, data: SendMessageResult) => void): void;
sendMessageBatch(params: SendMessageBatchRequest, callback: (err: any, data: SendMessageBatchResult) => void): void;
receiveMessage(params: ReceiveMessageRequest, callback: (err: any, data: ReceiveMessageResult) => void): void;
deleteMessage(params: DeleteMessageRequest, callback: (err: any, data: any) => void): void;
deleteMessageBatch(params: DeleteMessageBatchRequest, callback: (err: any, data: DeleteMessageBatchResult) => void): void;
createQueue(params: CreateQueueRequest, callback: (err: any, data: CreateQueueResult) => void): void;
deleteQueue(params: DeleteQueueRequest, callback: (err: any, data: any) => void): void;
}
export interface SendMessageRequest {
QueueUrl?: string;
MessageBody?: string;
DelaySeconds?: number;
}
export interface ReceiveMessageRequest {
QueueUrl?: string;
MaxNumberOfMessages?: number;
VisibilityTimeout?: number;
AttributeNames?: string[];
}
export interface DeleteMessageBatchRequest {
QueueUrl?: string;
Entries?: DeleteMessageBatchRequestEntry[];
}
export interface DeleteMessageBatchRequestEntry {
Id: string;
ReceiptHandle: string;
}
export interface DeleteMessageRequest {
QueueUrl?: string;
ReceiptHandle?: string;
}
export class Attribute {
Name: string;
Value: string;
}
export interface SendMessageBatchRequest {
QueueUrl?: string;
Entries?: SendMessageBatchRequestEntry[];
}
export class SendMessageBatchRequestEntry {
Id: string;
MessageBody: string;
DelaySeconds: number;
}
export interface CreateQueueRequest {
QueueName?: string;
DefaultVisibilityTimeout?: number;
DelaySeconds?: number;
Attributes?: Attribute[];
}
export interface DeleteQueueRequest {
QueueUrl?: string;
}
export class SendMessageResult {
MessageId: string;
MD5OfMessageBody: string;
}
export class ReceiveMessageResult {
Messages: Message[];
}
export class Message {
MessageId: string;
ReceiptHandle: string;
MD5OfBody: string;
Body: string;
Attributes: Attribute[];
}
export class DeleteMessageBatchResult {
Successful: DeleteMessageBatchResultEntry[];
Failed: BatchResultErrorEntry[];
}
export class DeleteMessageBatchResultEntry {
Id: string;
}
export class BatchResultErrorEntry {
Id: string;
Code: string;
Message: string;
SenderFault: string;
}
export class SendMessageBatchResult {
Successful: SendMessageBatchResultEntry[];
Failed: BatchResultErrorEntry[];
}
export class SendMessageBatchResultEntry {
Id: string;
MessageId: string;
MD5OfMessageBody: string;
}
export class CreateQueueResult {
QueueUrl: string;
}
}
export module Ses {
export interface Client {
config: ClientConfig;
sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void;
}
export interface SendEmailRequest {
Source: string;
Destination: Destination;
Message: Message;
ReplyToAddresses: string[];
ReturnPath: string;
}
export class Destination {
ToAddresses: string[];
CcAddresses: string[];
BccAddresses: string[];
}
export class Message {
Subject: Content;
Body: Body;
}
export class Content {
Data: string;
Charset: string;
}
export class Body {
Text: Content;
Html: Content;
}
export class SendEmailResult {
MessageId: string;
}
}
export module Swf {
export class Client {
//constructor(options?: any);
public config: ClientConfig;
countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void;
countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void;
countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void;
countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void;
deprecateActivityType(params: any, callback: (err: any, data: any) => void): void;
deprecateDomain(params: any, callback: (err: any, data: any) => void): void;
deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void;
describeActivityType(params: any, callback: (err: any, data: any) => void): void;
describeDomain(params: any, callback: (err: any, data: any) => void): void;
describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void;
describeWorkflowType(params: any, callback: (err: any, data: any) => void): void;
getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void;
listActivityTypes(params: any, callback: (err: any, data: any) => void): void;
listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void;
listDomains(params: any, callback: (err: any, data: any) => void): void;
listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void;
listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void;
pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void;
pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void;
recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void;
registerActivityType(params: any, callback: (err: any, data: any) => void): void;
registerDomain(params: any, callback: (err: any, data: any) => void): void;
registerWorkflowType(params: any, callback: (err: any, data: any) => void): void;
requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void;
respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void;
respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void;
respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void;
respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void;
signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void;
startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void;
terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void;
}
export interface PollForActivityTaskRequest {
domain?: string;
taskList?: TaskList;
identity?: string;
}
export interface TaskList {
name?: string;
}
export interface PollForDecisionTaskRequest {
domain?: string;
taskList?: TaskList;
identity?: string;
nextPageToken?: string;
maximumPageSize?: number;
reverseOrder?: Boolean;
}
export interface StartWorkflowExecutionRequest {
domain?: string;
workflowId?: string;
workflowType?: WorkflowType;
taskList?: TaskList;
input?: string;
executionStartToCloseTimeout?: string;
tagList?: string[];
taskStartToCloseTimeout?: string;
childPolicy?: string;
}
export interface WorkflowType {
name?: string;
version?: string;
}
export interface RespondDecisionTaskCompletedRequest {
taskToken?: string;
decisions?: Decision[];
executionContext?: string;
}
export interface Decision {
decisionType?: string;
scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes;
requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes;
completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes;
failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes;
cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes;
continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes;
recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes;
startTimerDecisionAttributes?: StartTimerDecisionAttributes;
cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes;
signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes;
requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes;
startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes;
}
export interface ScheduleActivityTaskDecisionAttributes {
activityType?: ActivityType;
activityId?: string;
control?: string;
input?: string;
scheduleToCloseTimeout?: string;
taskList?: TaskList;
scheduleToStartTimeout?: string;
startToCloseTimeout?: string;
heartbeatTimeout?: string;
}
export interface ActivityType {
name?: string;
version?: string;
}
export interface RequestCancelActivityTaskDecisionAttributes {
activityId?: string;
}
export interface CompleteWorkflowExecutionDecisionAttributes {
result?: string;
}
export interface FailWorkflowExecutionDecisionAttributes {
reason?: string;
details?: string;
}
export interface CancelWorkflowExecutionDecisionAttributes {
details?: string;
}
export interface ContinueAsNewWorkflowExecutionDecisionAttributes {
input?: string;
executionStartToCloseTimeout?: string;
taskList?: TaskList;
taskStartToCloseTimeout?: string;
childPolicy?: string;
tagList?: string[];
workflowTypeVersion?: string;
}
export interface RecordMarkerDecisionAttributes {
markerName?: string;
details?: string;
}
export interface StartTimerDecisionAttributes {
timerId?: string;
control?: string;
startToFireTimeout?: string;
}
export interface CancelTimerDecisionAttributes {
timerId?: string;
}
export interface SignalExternalWorkflowExecutionDecisionAttributes {
workflowId?: string;
runId?: string;
signalName?: string;
input?: string;
control?: string;
}
export interface RequestCancelExternalWorkflowExecutionDecisionAttributes {
workflowId?: string;
runId?: string;
control?: string;
}
export interface StartChildWorkflowExecutionDecisionAttributes {
workflowType?: WorkflowType;
workflowId?: string;
control?: string;
input?: string;
executionStartToCloseTimeout?: string;
taskList?: TaskList;
taskStartToCloseTimeout?: string;
childPolicy?: string;
tagList?: string[];
}
export interface RespondActivityTaskCompletedRequest {
taskToken?: string;
result?: string;
}
export interface RespondActivityTaskFailedRequest {
taskToken?: string;
reason?: string;
details?: string;
}
export interface RespondActivityTaskCanceledRequest {
taskToken?: string;
details?: string;
}
export interface DecisionTask {
taskToken?: string;
startedEventId?: number;
workflowExecution?: WorkflowExecution;
workflowType?: WorkflowType;
events?: HistoryEvent[];
nextPageToken?: string;
previousStartedEventId?: number;
}
export interface WorkflowExecution {
workflowId?: string;
runId?: string;
}
export interface HistoryEvent {
eventTimestamp?: any;
eventType?: string;
eventId?: number;
workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes;
workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes;
completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes;
workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes;
failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes;
workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes;
workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes;
cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes;
workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes;
continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes;
workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes;
workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes;
decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes;
decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes;
decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes;
decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes;
activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes;
activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes;
activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes;
activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes;
activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes;
activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes;
activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes;
workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes;
markerRecordedEventAttributes?: MarkerRecordedEventAttributes;
timerStartedEventAttributes?: TimerStartedEventAttributes;
timerFiredEventAttributes?: TimerFiredEventAttributes;
timerCanceledEventAttributes?: TimerCanceledEventAttributes;
startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes;
childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes;
childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes;
childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes;
childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes;
childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes;
childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes;
signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes;
externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes;
signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes;
externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes;
requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes;
requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes;
scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes;
requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes;
startTimerFailedEventAttributes?: StartTimerFailedEventAttributes;
cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes;
startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes;
}
export interface WorkflowExecutionStartedEventAttributes {
input?: string;
executionStartToCloseTimeout?: string;
taskStartToCloseTimeout?: string;
childPolicy?: string;
taskList?: TaskList;
workflowType?: WorkflowType;
tagList?: string[];
continuedExecutionRunId?: string;
parentWorkflowExecution?: WorkflowExecution;
parentInitiatedEventId?: number;
}
export interface WorkflowExecutionCompletedEventAttributes {
result?: string;
decisionTaskCompletedEventId?: number;
}
export interface CompleteWorkflowExecutionFailedEventAttributes {
cause?: string;
decisionTaskCompletedEventId?: number;
}
export interface WorkflowExecutionFailedEventAttributes {
reason?: string;
details?: string;
decisionTaskCompletedEventId?: number;
}
export interface FailWorkflowExecutionFailedEventAttributes {
cause?: string;
decisionTaskCompletedEventId?: number;
}
export interface WorkflowExecutionTimedOutEventAttributes {
timeoutType?: string;
childPolicy?: string;
}
export interface WorkflowExecutionCanceledEventAttributes {
details?: string;
decisionTaskCompletedEventId?: number;
}
export interface CancelWorkflowExecutionFailedEventAttributes {
cause?: string;
decisionTaskCompletedEventId?: number;
}
export interface WorkflowExecutionContinuedAsNewEventAttributes {
input?: string;
decisionTaskCompletedEventId?: number;
newExecutionRunId?: string;
executionStartToCloseTimeout?: string;
taskList?: TaskList;
taskStartToCloseTimeout?: string;
childPolicy?: string;
tagList?: string[];
workflowType?: WorkflowType;
}
export interface ContinueAsNewWorkflowExecutionFailedEventAttributes {
cause?: string;
decisionTaskCompletedEventId?: number;
}
export interface WorkflowExecutionTerminatedEventAttributes {
reason?: string;
details?: string;
childPolicy?: string;
cause?: string;
}
export interface WorkflowExecutionCancelRequestedEventAttributes {
externalWorkflowExecution?: WorkflowExecution;
externalInitiatedEventId?: number;
cause?: string;
}
export interface DecisionTaskScheduledEventAttributes {
taskList?: TaskList;
startToCloseTimeout?: string;
}
export interface DecisionTaskStartedEventAttributes {
identity?: string;
scheduledEventId?: number;
}
export interface DecisionTaskCompletedEventAttributes {
executionContext?: string;
scheduledEventId?: number;
startedEventId?: number;
}
export interface DecisionTaskTimedOutEventAttributes {
timeoutType?: string;
scheduledEventId?: number;
startedEventId?: number;
}
export interface ActivityTaskScheduledEventAttributes {
activityType?: ActivityType;
activityId?: string;
input?: string;
control?: string;
scheduleToStartTimeout?: string;
scheduleToCloseTimeout?: string;
startToCloseTimeout?: string;
taskList?: TaskList;
decisionTaskCompletedEventId?: number;
heartbeatTimeout?: string;
}
export interface ActivityTaskStartedEventAttributes {
identity?: string;
scheduledEventId?: number;
}
export interface ActivityTaskCompletedEventAttributes {
result?: string;
scheduledEventId?: number;
startedEventId?: number;
}
export interface ActivityTaskFailedEventAttributes {
reason?: string;
details?: string;
scheduledEventId?: number;
startedEventId?: number;
}
export interface ActivityTaskTimedOutEventAttributes {
timeoutType?: string;
scheduledEventId?: number;
startedEventId?: number;
details?: string;
}
export interface ActivityTaskCanceledEventAttributes {
details?: string;
scheduledEventId?: number;
startedEventId?: number;
latestCancelRequestedEventId?: number;
}
export interface ActivityTaskCancelRequestedEventAttributes {
decisionTaskCompletedEventId?: number;
activityId?: string;
}
export interface WorkflowExecutionSignaledEventAttributes {
signalName?: string;
input?: string;
externalWorkflowExecution?: WorkflowExecution;
externalInitiatedEventId?: number;
}
export interface MarkerRecordedEventAttributes {
markerName?: string;
details?: string;
decisionTaskCompletedEventId?: number;
}
export interface TimerStartedEventAttributes {
timerId?: string;
control?: string;
startToFireTimeout?: string;
decisionTaskCompletedEventId?: number;
}
export interface TimerFiredEventAttributes {
timerId?: string;
startedEventId?: number;
}
export interface TimerCanceledEventAttributes {
timerId?: string;
startedEventId?: number;
decisionTaskCompletedEventId?: number;
}
export interface StartChildWorkflowExecutionInitiatedEventAttributes {
workflowId?: string;
workflowType?: WorkflowType;
control?: string;
input?: string;
executionStartToCloseTimeout?: string;
taskList?: TaskList;
decisionTaskCompletedEventId?: number;
childPolicy?: string;
taskStartToCloseTimeout?: string;
tagList?: string[];
}
export interface ChildWorkflowExecutionStartedEventAttributes {
workflowExecution?: WorkflowExecution;
workflowType?: WorkflowType;
initiatedEventId?: number;
}
export interface ChildWorkflowExecutionCompletedEventAttributes {
workflowExecution?: WorkflowExecution;
workflowType?: WorkflowType;
result?: string;
initiatedEventId?: number;
startedEventId?: number;
}
export interface ChildWorkflowExecutionFailedEventAttributes {
workflowExecution?: WorkflowExecution;
workflowType?: WorkflowType;
reason?: string;
details?: string;
initiatedEventId?: number;
startedEventId?: number;
}
export interface ChildWorkflowExecutionTimedOutEventAttributes {
workflowExecution?: WorkflowExecution;
workflowType?: WorkflowType;
timeoutType?: string;
initiatedEventId?: number;
startedEventId?: number;
}
export interface ChildWorkflowExecutionCanceledEventAttributes {
workflowExecution?: WorkflowExecution;
workflowType?: WorkflowType;
details?: string;
initiatedEventId?: number;
startedEventId?: number;
}
export interface ChildWorkflowExecutionTerminatedEventAttributes {
workflowExecution?: WorkflowExecution;
workflowType?: WorkflowType;
initiatedEventId?: number;
startedEventId?: number;
}
export interface SignalExternalWorkflowExecutionInitiatedEventAttributes {
workflowId?: string;
runId?: string;
signalName?: string;
input?: string;
decisionTaskCompletedEventId?: number;
control?: string;
}
export interface ExternalWorkflowExecutionSignaledEventAttributes {
workflowExecution?: WorkflowExecution;
initiatedEventId?: number;
}
export interface SignalExternalWorkflowExecutionFailedEventAttributes {
workflowId?: string;
runId?: string;
cause?: string;
initiatedEventId?: number;
decisionTaskCompletedEventId?: number;
control?: string;
}
export interface ExternalWorkflowExecutionCancelRequestedEventAttributes {
workflowExecution?: WorkflowExecution;
initiatedEventId?: number;
}
export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes {
workflowId?: string;
runId?: string;
decisionTaskCompletedEventId?: number;
control?: string;
}
export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes {
workflowId?: string;
runId?: string;
cause?: string;
initiatedEventId?: number;
decisionTaskCompletedEventId?: number;
control?: string;
}
export interface ScheduleActivityTaskFailedEventAttributes {
activityType?: ActivityType;
activityId?: string;
cause?: string;
decisionTaskCompletedEventId?: number;
}
export interface RequestCancelActivityTaskFailedEventAttributes {
activityId?: string;
cause?: string;
decisionTaskCompletedEventId?: number;
}
export interface StartTimerFailedEventAttributes {
timerId?: string;
cause?: string;
decisionTaskCompletedEventId?: number;
}
export interface CancelTimerFailedEventAttributes {
timerId?: string;
cause?: string;
decisionTaskCompletedEventId?: number;
}
export interface StartChildWorkflowExecutionFailedEventAttributes {
workflowType?: WorkflowType;
cause?: string;
workflowId?: string;
initiatedEventId?: number;
decisionTaskCompletedEventId?: number;
control?: string;
}
export interface ActivityTask {
taskToken?: string;
activityId?: string;
startedEventId?: number;
workflowExecution?: WorkflowExecution;
activityType?: ActivityType;
input?: string;
}
export interface PollForActivityTaskResult {
activityTask?: ActivityTask;
}
export interface PollForDecisionTaskResult {
decisionTask?: DecisionTask;
}
export interface StartWorkflowExecutionResult {
run?: Run;
}
export interface Run {
runId?: string;
}
}
export module Sns {
export interface Client {
config: ClientConfig;
publicTopic(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void;
createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void;
deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void;
}
export interface PublishRequest {
TopicArn?: string;
Message?: string;
MessageStructure?: string;
Subject?: string;
}
export interface PublishResult {
MessageId?: string;
}
export interface CreateTopicRequest {
Name?: string;
}
export interface CreateTopicResult {
TopicArn?: string;
}
export interface DeleteTopicRequest {
TopicArn?: string;
}
}
export module s3 {
export interface Client {
config: ClientConfig;
putObject(params: PutObjectRequest, callback: (err: any, data: any) => void): void;
getObject(params: GetObjectRequest, callback: (err: any, data: any) => void): void;
}
export interface PutObjectRequest {
ACL?: string;
Body?: any;
Bucket: string;
CacheControl?: string;
ContentDisposition?: string;
ContentEncoding?: string;
ContentLanguage?: string;
ContentLength?: string;
ContentMD5?: string;
ContentType?: string;
Expires?: any;
GrantFullControl?: string;
GrantRead?: string;
GrantReadACP?: string;
GrantWriteACP?: string;
Key: string;
Metadata?: string[];
ServerSideEncryption?: string;
StorageClass?: string;
WebsiteRedirectLocation?: string;
}
export interface GetObjectRequest {
Bucket: string;
IfMatch?: string;
IfModifiedSince?: any;
IfNoneMatch?: string;
IfUnmodifiedSince?: any;
Key: string;
Range?: string;
ResponseCacheControl?: string;
ResponseContentDisposition?: string;
ResponseContentEncoding?: string;
ResponseContentLanguage?: string;
ResponseContentType?: string;
ResponseExpires?: any;
VersionId?: string;
}
}
}
@@ -42,21 +42,21 @@ declare module Microsoft.WindowsAzure {
getTableName(): string;
getMobileServiceClient(): MobileServiceClient;
insert(istance: any, paramsQS: Object, callback: (error: any, retInserted: any) => any): void;
insert(istance: any, paramsQS: Object): asyncPromise;
insert(istance: any): asyncPromise;
insert(instance: any, paramsQS: Object, callback: (error: any, retInserted: any) => any): void;
insert(instance: any, paramsQS: Object): asyncPromise;
insert(instance: any): asyncPromise;
update(istance: any, paramsQS: Object, callback: (error: any, retUpdated: any) => any): void;
update(istance: any, paramsQS: Object): asyncPromise;
update(istance: any): asyncPromise;
update(instance: any, paramsQS: Object, callback: (error: any, retUpdated: any) => any): void;
update(instance: any, paramsQS: Object): asyncPromise;
update(instance: any): asyncPromise;
lookup(id: number, paramsQS: Object, callback: (error: any, retValue: any) => any): void;
lookup(id: number, paramsQS: Object): asyncPromise;
lookup(id: number): asyncPromise;
del(istance: any, paramsQS: Object, callback: (error?: any) => void ): void;
del(istance: any, paramsQS: Object): asyncPromise;
del(istance: any): asyncPromise;
del(instance: any, paramsQS: Object, callback: (error?: any) => void ): void;
del(instance: any, paramsQS: Object): asyncPromise;
del(instance: any): asyncPromise;
read(query: IQuery, paramsQS: Object, callback: (error: any, retValues: any) => any): void;
+14 -11
View File
@@ -5,12 +5,15 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../backbone/backbone.d.ts" />
declare module Backbone {
export class RelationalModel extends Model {
static extend(properties:any, classProperties?:any):any; // do not use, prefer TypeScript's extend functionality
class RelationalModel extends Model {
/**
* Do not use, prefer TypeScript's extend functionality.
**/
//private static extend(properties:any, classProperties?:any):any;
relations:any;
subModelTypes:any;
subModelTypeAttribute:any;
@@ -58,7 +61,7 @@ declare module Backbone {
setRelated(related:Model):void;
setRelated(related:Collection):void;
setRelated(related:Collection<Model>):void;
getReverseRelations(model:RelationalModel):Relation;
@@ -78,15 +81,15 @@ declare module Backbone {
setKeyContents(keyContents:number[]):void;
setKeyContents(keyContents:Collection):void;
setKeyContents(keyContents:Collection<Model>):void;
onChange(model:Model, attr:any, options:any):void;
handleAddition(model:Model, coll:Collection, options:any):void;
handleAddition(model:Model, coll:Collection<Model>, options:any):void;
handleRemoval(model:Model, coll:Collection, options:any):void;
handleRemoval(model:Model, coll:Collection<Model>, options:any):void;
handleReset(coll:Collection, options:any):void;
handleReset(coll:Collection<Model>, options:any):void;
tryAddRelated(model:Model, coll:any, options:any):void;
@@ -135,9 +138,9 @@ declare module Backbone {
processOrphanRelations():void;
retroFitRelation(relation:RelationalModel, create:boolean):Collection;
retroFitRelation(relation:RelationalModel, create:boolean):Collection<Model>;
getCollection(type:RelationalModel, create:boolean):Collection;
getCollection(type:RelationalModel, create:boolean):Collection<Model>;
getObjectByName(name:string):any;
@@ -158,7 +161,7 @@ declare module Backbone {
update(model:RelationalModel):void;
unregister(model:RelationalModel, collection:Collection, options:any):void;
unregister(model:RelationalModel, collection:Collection<Model>, options:any):void;
reset():void;
+112 -66
View File
@@ -4,7 +4,7 @@
function test_events() {
var object = new Backbone.Events();
object.on("alert", (msg) => alert("Triggered " + msg));
object.on("alert", (eventName: string) => alert("Triggered " + eventName));
object.trigger("alert", "an event");
@@ -18,48 +18,74 @@ function test_events() {
object.off();
}
class SettingDefaults extends Backbone.Model {
// 'defaults' could be set in one of the following ways:
defaults() {
return {
name: "Joe"
}
}
constructor(attributes?: any, options?: any) {
this.defaults = <any>{
name: "Joe"
}
// super has to come last
super(attributes, options);
}
// or set it like this
initialize() {
this.defaults = <any>{
name: "Joe"
}
}
// same patterns could be used for setting 'Router.routes' and 'View.events'
}
class Sidebar extends Backbone.Model {
promptColor() {
var cssColor = prompt("Please enter a CSS color:");
this.set({ color: cssColor });
}
}
class Note extends Backbone.Model {
initialize() { }
author() { }
coordinates() { }
allowedToEdit(account: any) {
return true;
}
}
class PrivateNote extends Note {
allowedToEdit(account: any) {
return account.owns(this);
}
set(attributes: any, options?: any): Backbone.Model {
return Backbone.Model.prototype.set.call(this, attributes, options);
}
}
function test_models() {
var Sidebar = Backbone.Model.extend({
promptColor: function () {
var cssColor = prompt("Please enter a CSS color:");
this.set({ color: cssColor });
}
});
var sidebar = new Sidebar();
sidebar.on('change:color', (model, color) => $('#sidebar').css({ background: color }));
sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color }));
sidebar.set({ color: 'white' });
sidebar.promptColor();
////////
var Note = Backbone.Model.extend({
initialize: () => { },
author: () => { },
coordinates: () => { },
allowedToEdit: (account) => {
return true;
}
});
var PrivateNote = Note.extend({
allowedToEdit: function (account) {
return account.owns(this);
}
});
//////////
var note = Backbone.Model.extend({
set: function (attributes, options) {
Backbone.Model.prototype.set.call(this, attributes, options);
}
});
var note = new PrivateNote();
note.get("title")
note.get("title");
note.set({ title: "March 20", content: "In his eyes she eclipses..." });
@@ -69,7 +95,7 @@ function test_models() {
class Employee extends Backbone.Model {
reports: EmployeeCollection;
constructor (options? ) {
constructor(attributes?: any, options?: any) {
super(options);
this.reports = new EmployeeCollection();
this.reports.url = '../api/employees/' + this.id + '/reports';
@@ -80,31 +106,51 @@ class Employee extends Backbone.Model {
}
}
class EmployeeCollection extends Backbone.Collection {
findByName(key) { }
class EmployeeCollection extends Backbone.Collection<Employee> {
findByName(key: any) { }
}
class Book extends Backbone.Model {
title: string;
author: string;
published: boolean;
}
class Library extends Backbone.Collection<Book> {
// This model definition is here only to test type compatibility of the model, but it
// is not necessary in working code as it is automatically inferred through generics.
model: typeof Book;
}
class Books extends Backbone.Collection<Book> { }
function test_collection() {
var Book: Backbone.Model;
var Library = Backbone.Collection.extend({
model: Book
});
var Books: Backbone.Collection;
var books = new Books();
Books.each(function (book) {
});
var book1: Book = new Book({ title: "Title 1", author: "Mike" });
books.add(book1);
var titles = Books.map(function (book) {
return book.get("title");
});
// Objects can be added to collection by casting to model type.
// Compiler will check if object properties are valid for the cast.
// This gives better type checking than declaring an `any` overload.
books.add(<Book>{ title: "Title 2", author: "Mikey" });
var publishedBooks = Books.filter(function (book) {
return book.get("published") === true;
});
var model: Book = book1.collection.first();
if (model !== book1) {
throw new Error("Error");
}
var alphabetical = Books.sortBy(function (book) {
return null;
});
books.each(book =>
book.get("title"));
var titles = books.map(book =>
book.get("title"));
var publishedBooks = books.filter(book =>
book.get("published") === true);
var alphabetical = books.sortBy((book: Book): number => null);
}
//////////
@@ -121,26 +167,26 @@ module v1Changes {
function test_listenTo() {
var model = new Employee;
var view = new Backbone.View;
var view = new Backbone.View<Employee>();
view.listenTo(model, 'invalid', () => { });
}
function test_listenToOnce() {
var model = new Employee;
var view = new Backbone.View;
var view = new Backbone.View<Employee>();
view.listenToOnce(model, 'invalid', () => { });
}
function test_stopListening() {
var model = new Employee;
var view = new Backbone.View;
var view = new Backbone.View<Employee>();
view.stopListening(model, 'invalid', () => { });
view.stopListening(model, 'invalid');
view.stopListening(model);
}
}
module modelandcollection {
module ModelAndCollection {
function test_url() {
Employee.prototype.url = () => '/employees';
EmployeeCollection.prototype.url = () => '/employees';
@@ -168,7 +214,7 @@ module v1Changes {
}
}
module model {
module Model {
function test_validationError() {
var model = new Employee;
if (model.validationError) {
@@ -195,17 +241,17 @@ module v1Changes {
model.destroy({
wait: true,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?: JQueryXHR, options?) => { }
error: (m?, jqxhr?, options?) => { }
});
model.destroy({
success: (m?, response?, options?) => { },
error: (m?, jqxhr?: JQueryXHR) => { }
error: (m?, jqxhr?) => { }
});
model.destroy({
success: () => { },
error: (m?, jqxhr?: JQueryXHR) => { }
error: (m?, jqxhr?) => { }
});
}
@@ -220,7 +266,7 @@ module v1Changes {
wait: true,
validate: false,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?: JQueryXHR, options?) => { }
error: (m?, jqxhr?, options?) => { }
});
model.save({
@@ -229,7 +275,7 @@ module v1Changes {
},
{
success: () => { },
error: (m?, jqxhr?: JQueryXHR) => { }
error: (m?, jqxhr?) => { }
});
}
@@ -240,7 +286,7 @@ module v1Changes {
}
}
module collection {
module Collection {
function test_fetch() {
var collection = new EmployeeCollection;
collection.fetch({ reset: true });
@@ -256,7 +302,7 @@ module v1Changes {
}
}
module router {
module Router {
function test_navigate() {
var router = new Backbone.Router;
@@ -264,4 +310,4 @@ module v1Changes {
router.navigate('/employees', true);
}
}
}
}
-1
View File
@@ -1 +0,0 @@
""
+159 -120
View File
@@ -1,11 +1,10 @@
// Type definitions for Backbone 1.0.0
// Project: http://backbonejs.org/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions by: Natan Vivo <https://github.com/nvivo/>
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Natan Vivo <https://github.com/nvivo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../underscore/underscore.d.ts" />
declare module Backbone {
@@ -67,7 +66,7 @@ declare module Backbone {
}
class Events {
on(eventName: any, callback?: Function, context?: any): any;
on(eventName: string, callback?: Function, context?: any): any;
off(eventName?: string, callback?: Function, context?: any): any;
trigger(eventName: string, ...args: any[]): any;
bind(eventName: string, callback: Function, context?: any): any;
@@ -86,17 +85,24 @@ declare module Backbone {
sync(...arg: any[]): JQueryXHR;
}
interface OptionalDefaults {
defaults?(): any;
}
class Model extends ModelBase {
class Model extends ModelBase implements OptionalDefaults {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
/**
* Do not use, prefer TypeScript's extend functionality.
**/
private static extend(properties: any, classProperties?: any): any;
attributes: any;
changed: any[];
cid: string;
collection: Collection<any>;
/**
* Default attributes for the model. It can be an object hash or a method returning an object hash.
* For assigning an object hash, do it like this: this.defaults = <any>{ attribute: value, ... };
* That works only if you set it in the constructor or the initialize method.
**/
defaults(): any;
id: any;
idAttribute: string;
validationError: any;
@@ -107,8 +113,23 @@ declare module Backbone {
fetch(options?: ModelFetchOptions): JQueryXHR;
get(attributeName: string): any;
set(attributeName: string, value: any, options?: ModelSetOptions): Model;
/**
* For strongly-typed access to attributes, use the `get` method only privately in public getter properties.
* @example
* get name(): string {
* return super.get("name");
* }
**/
/*private*/ get(attributeName: string): any;
/**
* For strongly-typed assignment of attributes, use the `set` method only privately in public setter properties.
* @example
* set name(value: string) {
* super.set("name", value);
* }
**/
/*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model;
set(obj: any, options?: ModelSetOptions): Model;
change(): any;
@@ -127,7 +148,7 @@ declare module Backbone {
unset(attribute: string, options?: Silenceable): Model;
validate(attributes: any, options?: any): any;
_validate(attrs: any, options: any): boolean;
private _validate(attrs: any, options: any): boolean;
// mixins from underscore
@@ -141,115 +162,129 @@ declare module Backbone {
omit(...keys: string[]): any;
}
class Collection extends ModelBase {
class Collection<TModel extends Model> extends ModelBase {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
/**
* Do not use, prefer TypeScript's extend functionality.
**/
private static extend(properties: any, classProperties?: any): any;
model: any;
models: any;
collection: Model;
// TODO: this really has to be typeof TModel
//model: typeof TModel;
model: { new(): TModel; }; // workaround
models: TModel[];
length: number;
constructor(models?: any, options?: any);
constructor(models?: TModel[], options?: any);
fetch(options?: CollectionFetchOptions): JQueryXHR;
comparator(element: Model): any;
comparator(compare: Model, to?: Model): any;
comparator(element: TModel): number;
comparator(compare: TModel, to?: TModel): number;
add(model: Model, options?: AddOptions): Collection;
add(model: any, options?: AddOptions): Collection;
add(models: Model[], options?: AddOptions): Collection;
add(models: any[], options?: AddOptions): Collection;
at(index: number): Model;
get(id: any): Model;
create(attributes: any, options?: ModelSaveOptions): Model;
add(model: TModel, options?: AddOptions): Collection<TModel>;
add(models: TModel[], options?: AddOptions): Collection<TModel>;
at(index: number): TModel;
/**
* Get a model from a collection, specified by an id, a cid, or by passing in a model.
**/
get(id: number): TModel;
get(id: string): TModel;
get(id: Model): TModel;
create(attributes: any, options?: ModelSaveOptions): TModel;
pluck(attribute: string): any[];
push(model: Model, options?: AddOptions): Model;
pop(options?: Silenceable): Model;
remove(model: Model, options?: Silenceable): Model;
remove(models: Model[], options?: Silenceable): Model[];
reset(models?: Model[], options?: Silenceable): Model[];
reset(models?: any[], options?: Silenceable): Model[];
set(models?: any[], options?: Silenceable): Model[];
shift(options?: Silenceable): Model;
sort(options?: Silenceable): Collection;
unshift(model: Model, options?: AddOptions): Model;
where(properies: any): Model[];
findWhere(properties: any): Model;
push(model: TModel, options?: AddOptions): TModel;
pop(options?: Silenceable): TModel;
remove(model: TModel, options?: Silenceable): TModel;
remove(models: TModel[], options?: Silenceable): TModel[];
reset(models?: TModel[], options?: Silenceable): TModel[];
set(models?: TModel[], options?: Silenceable): TModel[];
shift(options?: Silenceable): TModel;
sort(options?: Silenceable): Collection<TModel>;
unshift(model: TModel, options?: AddOptions): TModel;
where(properies: any): TModel[];
findWhere(properties: any): TModel;
_prepareModel(attrs?: any, options?: any): any;
_removeReference(model: Model): void;
_onModelEvent(event: string, model: Model, collection: Collection, options: any): void;
private _prepareModel(attrs?: any, options?: any): any;
private _removeReference(model: TModel): void;
private _onModelEvent(event: string, model: TModel, collection: Collection<TModel>, options: any): void;
// mixins from underscore
all(iterator: (element: Model, index: number) => boolean, context?: any): boolean;
any(iterator: (element: Model, index: number) => boolean, context?: any): boolean;
collect(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[];
all(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[];
chain(): any;
compact(): Model[];
compact(): TModel[];
contains(value: any): boolean;
countBy(iterator: (element: Model, index: number) => any): any[];
countBy(attribute: string): any[];
countBy(iterator: (element: TModel, index: number) => any): _.Dictionary<number>;
countBy(attribute: string): _.Dictionary<number>;
detect(iterator: (item: any) => boolean, context?: any): any; // ???
difference(...model: Model[]): Model[];
drop(): Model;
drop(n: number): Model[];
each(iterator: (element: Model, index: number, list?: any) => void , context?: any): any;
every(iterator: (element: Model, index: number) => boolean, context?: any): boolean;
filter(iterator: (element: Model, index: number) => boolean, context?: any): Model[];
find(iterator: (element: Model, index: number) => boolean, context?: any): Model;
first(): Model;
first(n: number): Model[];
flatten(shallow?: boolean): Model[];
foldl(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any;
forEach(iterator: (element: Model, index: number, list?: any) => void , context?: any): any;
difference(...model: TModel[]): TModel[];
drop(): TModel;
drop(n: number): TModel[];
each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any;
every(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
filter(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[];
find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel;
first(): TModel;
first(n: number): TModel[];
flatten(shallow?: boolean): TModel[];
foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any;
forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any;
groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary<TModel[]>;
groupBy(attribute: string, context?: any): _.Dictionary<TModel[]>;
include(value: any): boolean;
indexOf(element: Model, isSorted?: boolean): number;
initial(): Model;
initial(n: number): Model[];
inject(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any;
intersection(...model: Model[]): Model[];
indexOf(element: TModel, isSorted?: boolean): number;
initial(): TModel;
initial(n: number): TModel[];
inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any;
intersection(...model: TModel[]): TModel[];
isEmpty(object: any): boolean;
invoke(methodName: string, arguments?: any[]): any;
last(): Model;
last(n: number): Model[];
lastIndexOf(element: Model, fromIndex?: number): number;
map(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[];
max(iterator?: (element: Model, index: number) => any, context?: any): Model;
min(iterator?: (element: Model, index: number) => any, context?: any): Model;
last(): TModel;
last(n: number): TModel[];
lastIndexOf(element: TModel, fromIndex?: number): number;
map(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[];
max(iterator?: (element: TModel, index: number) => any, context?: any): TModel;
min(iterator?: (element: TModel, index: number) => any, context?: any): TModel;
object(...values: any[]): any[];
reduce(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any;
reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any;
select(iterator: any, context?: any): any[];
size(): number;
shuffle(): any[];
some(iterator: (element: Model, index: number) => boolean, context?: any): boolean;
sortBy(iterator: (element: Model, index: number) => number, context?: any): Model[];
sortBy(attribute: string, context?: any): Model[];
sortedIndex(element: Model, iterator?: (element: Model, index: number) => number): number;
some(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[];
sortBy(attribute: string, context?: any): TModel[];
sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number;
range(stop: number, step?: number): any;
range(start: number, stop: number, step?: number): any;
reduceRight(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any[];
reject(iterator: (element: Model, index: number) => boolean, context?: any): Model[];
rest(): Model;
rest(n: number): Model[];
tail(): Model;
tail(n: number): Model[];
reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[];
reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[];
rest(): TModel;
rest(n: number): TModel[];
tail(): TModel;
tail(n: number): TModel[];
toArray(): any[];
union(...model: Model[]): Model[];
uniq(isSorted?: boolean, iterator?: (element: Model, index: number) => boolean): Model[];
without(...values: any[]): Model[];
zip(...model: Model[]): Model[];
union(...model: TModel[]): TModel[];
uniq(isSorted?: boolean, iterator?: (element: TModel, index: number) => boolean): TModel[];
without(...values: any[]): TModel[];
zip(...model: TModel[]): TModel[];
}
interface OptionalRoutes {
routes?(): any;
}
class Router extends Events {
class Router extends Events implements OptionalRoutes {
/**
* Do not use, prefer TypeScript's extend functionality.
**/
private static extend(properties: any, classProperties?: any): any;
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
/**
* Routes hash or a method returning the routes hash that maps URLs with parameters to methods on your Router.
* For assigning routes as object hash, do it like this: this.routes = <any>{ "route": callback, ... };
* That works only if you set it in the constructor or the initialize method.
**/
routes(): any;
constructor(options?: RouterOptions);
initialize(options?: RouterOptions): void;
@@ -257,9 +292,9 @@ declare module Backbone {
navigate(fragment: string, options?: NavigateOptions): Router;
navigate(fragment: string, trigger?: boolean): Router;
_bindRoutes(): void;
_routeToRegExp(route: string): RegExp;
_extractParameters(route: RegExp, fragment: string): string[];
private _bindRoutes(): void;
private _routeToRegExp(route: string): RegExp;
private _extractParameters(route: RegExp, fragment: string): string[];
}
var history: History;
@@ -279,14 +314,14 @@ declare module Backbone {
loadUrl(fragmentOverride: string): boolean;
navigate(fragment: string, options?: any): boolean;
started: boolean;
options: any;
_updateHash(location: Location, fragment: string, replace: boolean): void;
options: any;
private _updateHash(location: Location, fragment: string, replace: boolean): void;
}
interface ViewOptions {
model?: Backbone.Model;
collection?: Backbone.Collection;
interface ViewOptions<TModel extends Model> {
model?: TModel;
collection?: Backbone.Collection<TModel>;
el?: any;
id?: string;
className?: string;
@@ -294,35 +329,41 @@ declare module Backbone {
attributes?: any[];
}
interface OptionalEvents {
events?(): any;
}
class View<TModel extends Model> extends Events {
class View extends Events implements OptionalEvents {
/**
* Do not use, prefer TypeScript's extend functionality.
**/
private static extend(properties: any, classProperties?: any): any;
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
constructor(options?: ViewOptions<TModel>);
constructor(options?: ViewOptions);
/**
* Events hash or a method returning the events hash that maps events/selectors to methods on your View.
* For assigning events as object hash, do it like this: this.events = <any>{ "event:selector": callback, ... };
* That works only if you set it in the constructor or the initialize method.
**/
events(): any;
$(selector: string): JQuery;
model: Model;
collection: Collection;
make(tagName: string, attrs?: any, opts?: any): View;
setElement(element: HTMLElement, delegate?: boolean): View;
setElement(element: JQuery, delegate?: boolean): View;
model: TModel;
collection: Collection<TModel>;
//template: (json, options?) => string;
make(tagName: string, attrs?: any, opts?: any): View<TModel>;
setElement(element: HTMLElement, delegate?: boolean): View<TModel>;
setElement(element: JQuery, delegate?: boolean): View<TModel>;
id: string;
cid: string;
className: string;
tagName: string;
options: any;
el: any;
$el: JQuery;
setElement(element: any): View;
setElement(element: any): View<TModel>;
attributes: any;
$(selector: any): JQuery;
render(): View;
remove(): View;
render(): View<TModel>;
remove(): View<TModel>;
make(tagName: any, attributes?: any, content?: any): any;
delegateEvents(events?: any): any;
undelegateEvents(): any;
@@ -333,13 +374,11 @@ declare module Backbone {
// SYNC
function sync(method: string, model: Model, options?: JQueryAjaxSettings): any;
function ajax(options?: JQueryAjaxSettings): JQueryXHR;
var emulateHTTP: boolean;
var emulateJSONBackbone: boolean;
var emulateHTTP: boolean;
var emulateJSON: boolean;
// Utility
function noConflict(): typeof Backbone;
function setDomLibrary(jQueryNew: any): any;
var $: JQueryStatic;
}
+3 -3
View File
@@ -23,7 +23,7 @@ class TestModel extends Backbone.Model {
}
class TestCollection extends Backbone.Collection {
class TestCollection extends Backbone.Collection<TestModel> {
constructor(models?: any, options?: any) {
this.model = TestModel;
@@ -41,11 +41,11 @@ class TestCollection extends Backbone.Collection {
}
}
class TestView extends Backbone.View {
class TestView extends Backbone.View<TestModel> {
gridView: Backgrid.Grid;
testCollection: TestCollection;
constructor(viewOptions?: Backbone.ViewOptions) {
constructor(viewOptions?: Backbone.ViewOptions<TestModel>) {
this.testCollection = new TestCollection();
this.gridView = new Backgrid.Grid({
columns: [new Backgrid.Column({name: "FirstName", cell: "string", label: "First Name"}),
+10 -10
View File
@@ -9,20 +9,20 @@ declare module Backgrid {
interface GridOptions {
columns: Column[];
collection: Backbone.Collection;
collection: Backbone.Collection<Backbone.Model>;
header: Header;
body: Body;
row: Row;
footer: Footer;
}
class Header extends Backbone.View {
class Header extends Backbone.View<Backbone.Model> {
}
class Footer extends Backbone.View {
class Footer extends Backbone.View<Backbone.Model> {
}
class Row extends Backbone.View {
class Row extends Backbone.View<Backbone.Model> {
}
class Command {
@@ -50,19 +50,19 @@ declare module Backgrid {
initialize(options?: any);
}
class Body extends Backbone.View {
class Body extends Backbone.View<Backbone.Model> {
tagName: string;
initialize(options?: any);
insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any);
insertRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
moveToNextCell(model: Backbone.Model, cell: Column, command: Command);
refresh(): Body;
remove(): Body;
removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any);
removeRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
render(): Body;
}
class Grid extends Backbone.View {
class Grid extends Backbone.View<Backbone.Model> {
body: Backgrid.Body;
className: string;
footer: any;
@@ -72,10 +72,10 @@ declare module Backgrid {
initialize(options: any);
getSelectedModels(): Backbone.Model[];
insertColumn(...options: any[]): Grid;
insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any);
insertRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
remove():Grid;
removeColumn(...options: any[]): Grid;
removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any);
removeRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
render():Grid;
}
+114
View File
@@ -0,0 +1,114 @@
/// <reference path="big-integer.d.ts" />
// constructor tests
var noArgument = bigInt(),
numberArgument = bigInt( 93 ),
stringArgument = bigInt( "75643564363473453456342378564387956906736546456235345" ),
bigIntArgument = bigInt( noArgument );
// method tests
var x = bigInt(),
isBigInteger: BigInteger,
isNumber: number,
isBoolean: boolean,
isString: string,
isDivmod: {
quotient: BigInteger;
remainder: BigInteger;
};
isBigInteger = x.abs();
isBigInteger = x.add( 0 );
isBigInteger = x.add( x );
isBigInteger = x.add( "100" );
isBigInteger = x.compare( 0 );
isBigInteger = x.compare( x );
isBigInteger = x.compare( "100" );
isBigInteger = x.compareAbs( 0 );
isBigInteger = x.compareAbs( x );
isBigInteger = x.compareAbs( "100" );
isBigInteger = x.divide( 0 );
isBigInteger = x.divide( x );
isBigInteger = x.divide( "100" );
isDivmod = x.divmod( 0 );
isDivmod = x.divmod( x );
isDivmod = x.divmod( "100" );
isBoolean = x.equals( 0 );
isBoolean = x.equals( x );
isBoolean = x.equals( "100" );
isBoolean = x.greater( 0 );
isBoolean = x.greater( x );
isBoolean = x.greater( "100" );
isBoolean = x.greaterOrEquals( 0 );
isBoolean = x.greaterOrEquals( x );
isBoolean = x.greaterOrEquals( "100" );
isBoolean = x.isEven();
isBoolean = x.isNegative();
isBoolean = x.isOdd();
isBoolean = x.isPositive();
isBoolean = x.lesser( 0 );
isBoolean = x.lesser( x );
isBoolean = x.lesser( "100" );
isBoolean = x.lesserOrEquals( 0 );
isBoolean = x.lesserOrEquals( x );
isBoolean = x.lesserOrEquals( "100" );
isBigInteger = x.minus( 0 );
isBigInteger = x.minus( x );
isBigInteger = x.minus( "100" );
isBigInteger = x.mod( 0 );
isBigInteger = x.mod( x );
isBigInteger = x.mod( "100" );
isBigInteger = x.multiply( 0 );
isBigInteger = x.multiply( x );
isBigInteger = x.multiply( "100" );
isBigInteger = x.next();
isBoolean = x.notEquals( 0 );
isBoolean = x.notEquals( x );
isBoolean = x.notEquals( "100" );
isBigInteger = x.over( 0 );
isBigInteger = x.over( x );
isBigInteger = x.over( "100" );
isBigInteger = x.plus( 0 );
isBigInteger = x.plus( x );
isBigInteger = x.plus( "100" );
isBigInteger = x.pow( 0 );
isBigInteger = x.pow( x );
isBigInteger = x.pow( "100" );
isBigInteger = x.prev();
isBigInteger = x.subtract( 0 );
isBigInteger = x.subtract( x );
isBigInteger = x.subtract( "100" );
isBigInteger = x.times( 0 );
isBigInteger = x.times( x );
isBigInteger = x.times( "100" );
isNumber = x.toJSNumber();
isString = x.toString();
isNumber = x.valueOf();

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