Merge remote-tracking branch 'upstream/master'

Conflicts:
	sharepoint/SharePoint.d.ts
This commit is contained in:
gandjustas
2013-10-17 01:13:20 +04:00
459 changed files with 234795 additions and 166820 deletions
+24
View File
@@ -1,5 +1,6 @@
*.dll
*.exe
*.cmd
*.pdb
*.suo
*.js
@@ -22,8 +23,31 @@ Properties
*~
# test folder
!_infrastructure/*.js
!_infrastructure/tests/*
!_infrastructure/tests/*.js
!_infrastructure/tests/*/*.js
!_infrastructure/tests/*/*/*.js
!_infrastructure/tests/*/*/*/*.js
.idea/.name
.idea/DefinitelyTyped.iml
.idea/encodings.xml
.idea/libraries/Generated_files.xml
.idea/misc.xml
.idea/modules.xml
.idea/scopes/scope_settings.xml
.idea/vcs.xml
.idea/workspace.xml
.idea/watcherTasks.xml
.idea/watcherTasks.xml
+67 -13
View File
@@ -1,4 +1,4 @@
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.
@@ -29,6 +29,7 @@ List of Definitions
* [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei))
* [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/))
* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes))
* [AppFramework](http://app-framework-software.intel.com/) (by [Kyo Ago](https://github.com/kyo-ago))
* [Arbiter](http://arbiterjs.com/) (by [Arash Shakery](https://github.com/arash16))
* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov))
* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
@@ -39,13 +40,18 @@ List of Definitions
* [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))
* [CodeMirror](http://codemirror.net) (by [Franois de Campredon](https://github.com/fdecampredon))
* [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay))
* [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))
* [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))
* [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))
* [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))
@@ -60,49 +66,68 @@ List of Definitions
* [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))
* [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))
* [GoJS](http://gojs.net/) (by [Barbara Duckworth](https://github.com/barbara42))
* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt))
* [Grunt JS](http://gruntjs.com/) (by [Basarat Ali Syed](https://github.com/basarat))
* [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))
* [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))
* [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog))
* [History.js](https://github.com/balupton/History.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [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))
* [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))
* [Intl](http://www.ecma-international.org/ecma-402/1.0/) (by [Jeffery Grajkowski](http://github.com/pushplay))
* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski))
* [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.contextMenu](http://medialize.github.com/jQuery-contextMenu/) (by [Natan Vivo](https://github.com/nvivo/))
* [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.Cookie](https://github.com/carhartl/jquery-cookie) (by [Roy Goode](https://github.com/RoyGoode))
* [jQuery.Cycle](http://jquery.malsup.com/cycle/) (by [Franois Guillot](http://fguillot.developpez.com/))
* [jQuery.Cycle](http://jquery.malsup.com/cycle/) (by [François Guillot](http://fguillot.developpez.com/))
* [jQuery.dataTables](http://www.datatables.net) (by [Armin Sander](https://github.com/pragmatrix))
* [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [Franois de Campredon](https://github.com/fdecampredon))
* [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 [Franois Guillot](http://fguillot.developpez.com/))
* [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.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.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.timeago](http://timeago.yarp.com/) (by [Franois Guillot](http://fguillot.developpez.com/))
* [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.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.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))
@@ -110,9 +135,14 @@ List of Definitions
* [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/))
* [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/))
* [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](https://github.com/JudahGabriel))
* [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig))
@@ -121,25 +151,39 @@ List of Definitions
* [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov))
* [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))
* [Livestamp.js](https://github.com/mattbradley/livestampjs) (by [Vincent Bortone](https://github.com/vbortone))
* [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))
* [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [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))
* [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))
* [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_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))
* [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/))
* [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin))
* [PDF.js](https://github.com/mozilla/pdf.js) (by [Josh Baldwin](https://github.com/jbaldwin))
* [Persona](http://www.mozilla.org/en-US/persona) (by [James Frasca](https://github.com/Nycto))
* [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))
* [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))
* [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))
* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall))
* [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov))
@@ -147,15 +191,18 @@ List of Definitions
* [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))
* [Sencha Touch](http://www.sencha.com/products/touch/) (by [Brian Kotek](https://github.com/brian428))
* [SharePoint](http://sptypescript.codeplx.com) (by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru) and [Andrey Markeev](http://markeev.com))
* [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))
* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u))
* [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin))
* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr))
* [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))
* [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))
@@ -169,17 +216,21 @@ List of Definitions
* [Underscore.js](http://underscorejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Underscore.js (Typed)](http://underscorejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Underscore-ko.js](https://github.com/kamranayub/UnderscoreKO) (by [Maurits Elbers](https://github.com/MagicMau))
* [UUID.js](https://github.com/LiosK/UUID.js) (by [Jason Jarrett](https://github.com/staxmanade))
* [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))
* [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)
* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [Zepto.js] (http://zeptojs.com/) (by [Josh Baldwin](https://github.com/jbaldwin))
* [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))
Requested Definitions
---------------------
* [Rickshaw](https://github.com/shutterstock/rickshaw)
* [jQuery ScrollTo](https://github.com/balupton/jquery-scrollto)
* [Crossfilter](https://github.com/square/crossfilter)
* [dc.js](https://github.com/NickQiZhu/dc.js)
@@ -188,3 +239,6 @@ Requested Definitions
* [MooTools](http://mootools.net/)
* [Lo-Dash](http://lodash.com/)
* [java](https://github.com/nearinfinity/node-java)
* [SVG.js](http://www.svgjs.com/)
In addition you can find the [updated open requests that you can contribute here](https://github.com/borisyankov/DefinitelyTyped/issues?labels=request&page=1&state=open)
File diff suppressed because it is too large Load Diff
+561
View File
@@ -0,0 +1,561 @@
/// <reference path='src/exec.ts' />
/// <reference path='src/io.ts' />
module DefinitelyTyped {
export module TestManager {
var path = require('path');
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
class Iterator {
index: number = -1;
constructor(public list: any[]){}
public next() {
this.index++;
return this.list[this.index];
}
public hasNext() {
return this.list[1 + this.index] != null;
}
}
class Tsc {
public static run(tsfile: string, callback: Function) {
var command = 'node ./_infrastructure/tests/typescript/tsc.js --module commonjs ';
if (IO.fileExists(tsfile + '.tscparams')) {
command += '@' + tsfile + '.tscparams';
}
Exec.exec(command, [tsfile], (ExecResult) => {
callback(ExecResult);
});
}
}
class Test {
constructor(public tsfile: string) {}
public run(callback: Function) {
Tsc.run(this.tsfile , callback);
}
}
class Typing {
public fileHandler: FileHandler;
constructor(public name: string, baseDir: string) {
this.fileHandler = new FileHandler(baseDir + '/' + name + '/', /.\.ts/g);
}
}
class FileHandler {
public files: string[] = [];
public typings: Typing[] = [];
constructor(public path: string, pattern: any) {
this.files = IO.dir(path, pattern, { recursive: true }).sort();
}
public allTS(): string[] {
return this.files;
}
public allTests(): string[] {
var tests = [];
for(var i = 0; i < this.files.length; i++) {
if (endsWith(this.files[i].toUpperCase(), '-TESTS.TS')) {
tests.push(this.files[i]);
}
}
return tests;
}
public allTypings(): string[] {
var typings = {};
for(var i = 0; i < this.files.length; i++) {
var file = this.files[i];
var firName = path.dirname(file.substr(this.path.length + 1)).replace('\\', '/');
var dir = firName.split('/')[0];
if(!typings[dir]) typings[dir] = true;
}
var list = [];
for(var attr in typings) {
list.push(attr);
}
return list;
}
}
class Timer {
public startTime;
public time = 0;
public asString: string;
private static prettyDate(date1, date2): string {
var diff = ((date2 - date1) / 1000),
day_diff = Math.floor(diff / 86400);
if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
return;
return <string><any> (day_diff == 0 && (
diff < 60 && (diff + " seconds") ||
diff < 120 && "1 minute" ||
diff < 3600 && Math.floor( diff / 60 ) + " minutes" ||
diff < 7200 && "1 hour" ||
diff < 86400 && Math.floor( diff / 3600 ) + " hours") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days" ||
day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks");
}
public start() {
this.time = 0;
this.startTime = this.now();
}
private now() {
return Date.now();
}
public end() {
this.time = (this.now() - this.startTime) / 1000;
this.asString = Timer.prettyDate(this.startTime, this.now());
}
}
class Print {
constructor(public version: string, public typings: number, public tsFiles: number) { }
public out(s) {
process.stdout.write(s);
}
public printHeader() {
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.3.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[1mTypeScript files :\33[0m ' + this.tsFiles + '\n');
}
public printSyntaxChecking() {
this.out('============================ \33[34m\33[1mSyntax checking\33[0m ================================\n');
}
public printTypingTests() {
this.out('============================= \33[34m\33[1mTyping tests\33[0m ==================================\n');
}
public printSuccess() {
this.out('\33[36m\33[1m.\33[0m');
}
public printFailure() {
this.out('x');
}
public printDiv() {
this.out('-----------------------------------------------------------------------------\n');
}
public printfilesWithSintaxErrorMessage() {
this.out(' \33[36m\33[1mFiles with syntax error\33[0m\n');
}
public printFailedTestMessage() {
this.out(' \33[36m\33[1mFailed tests\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 printErrorFile(file) {
this.out(' - ' + file + '\n');
}
public printTypingsWithoutTest(file) {
this.out(' - \33[33m\33[1m' + file + '\33[0m\n');
}
public breack() {
this.out('\n');
}
public printSuccessCount(current: number, total: number) {
this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printFailedCount(current: number, total: number) {
this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printElapsedTime(time, s) {
this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n');
}
public printSyntaxErrorCount(current: number, total: number) {
this.out(' \33[36m\33[1mSyntax error :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printTestErrorCount(current: number, total: number) {
this.out(' \33[36m\33[1mFailed tests :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printWithoutTestCount(current: number, total: number) {
this.out(' \33[36m\33[1mWithout tests :\33[0m \33[33m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
}
class File {
constructor(public name: string, public hasError: boolean) {}
public formatName(baseDir: string): string {
var dirName = path.dirname(this.name.substr(baseDir.length + 1)).replace('\\', '/');
var dir = dirName.split('/')[0];
var file = path.basename(this.name, '.ts');
var ext = path.extname(this.name);
return dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + '\33[36m\33[1m' + file + '\33[0m' + ext;
}
}
class SyntaxChecking {
private timer: Timer;
public files: File[] = [];
private getFailedFiles(): File[] {
var list: File[] = [];
for(var i = 0; i < this.files.length; i++) {
if(this.files[i].hasError) {
list.push(this.files[i]);
}
}
return list;
}
private getSuccessFiles(): File[] {
var list: File[] = [];
for(var i = 0; i < this.files.length; i++) {
if(!this.files[i].hasError) {
list.push(this.files[i]);
}
}
return list;
}
constructor(public fileHandler: FileHandler, public out: Print) {
this.timer = new Timer();
}
private printStats() {
this.out.printDiv();
this.out.printElapsedTime(this.timer.asString, this.timer.time);
this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length);
this.out.printFailedCount(this.getFailedFiles().length, this.files.length);
}
private printFailedFiles() {
if (this.getFailedFiles().length > 0) {
this.out.printDiv();
this.out.printfilesWithSintaxErrorMessage();
this.out.printDiv();
for(var i = 0; i < this.getFailedFiles().length; i++) {
var errorFile = this.getFailedFiles()[i];
this.out.printErrorFile(errorFile.formatName(this.fileHandler.path));
}
}
}
private run(it, file, len, maxLen, callback: Function) {
if (!endsWith(file.toUpperCase(), '-TESTS.TS') && endsWith(file.toUpperCase(), '.TS') && file.indexOf('../_infrastructure') < 0) {
new Test(file).run((o) => {
var failed = false;
if(o.exitCode === 1) {
this.out.printFailure();
failed = true;
len++;
} else {
this.out.printSuccess();
len++;
}
this.files.push(new File(file, failed));
if(len > maxLen) {
len = 0;
this.out.breack();
}
if (it.hasNext()) {
this.run(it, it.next(), len, maxLen, callback);
} else {
this.out.breack();
this.timer.end();
this.printFailedFiles();
this.printStats();
callback(this.getFailedFiles().length, this.files.length);
}
});
} else if (it.hasNext()) {
this.run(it, it.next(), len, maxLen, callback);
} else {
this.out.breack();
this.timer.end();
this.printStats();
this.printFailedFiles();
callback(this.getFailedFiles().length, this.files.length);
}
}
public start(callback: Function) {
this.timer.start();
var tsFiles = this.fileHandler.allTS();
var it = new Iterator(tsFiles);
var len = 0;
var maxLen = 76;
if (it.hasNext()) {
this.run(it, it.next(), len, maxLen, callback);
}
}
}
class TestEval {
private timer: Timer;
public files: File[] = [];
private getFailedFiles(): File[] {
var list: File[] = [];
for(var i = 0; i < this.files.length; i++) {
if(this.files[i].hasError) {
list.push(this.files[i]);
}
}
return list;
}
private getSuccessFiles(): File[] {
var list: File[] = [];
for(var i = 0; i < this.files.length; i++) {
if(!this.files[i].hasError) {
list.push(this.files[i]);
}
}
return list;
}
constructor(public fileHandler: FileHandler, public out: Print) {
this.timer = new Timer();
}
private printStats() {
this.out.printDiv();
this.out.printElapsedTime(this.timer.asString, this.timer.time);
this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length);
this.out.printFailedCount(this.getFailedFiles().length, this.files.length);
}
private printFailedFiles() {
if (this.getFailedFiles().length > 0) {
this.out.printDiv();
this.out.printFailedTestMessage();
this.out.printDiv();
for(var i = 0; i < this.getFailedFiles().length; i++) {
var errorFile = this.getFailedFiles()[i];
this.out.printErrorFile(errorFile.formatName(this.fileHandler.path));
}
}
}
private run(it, file, len, maxLen, callback: Function) {
if (endsWith(file.toUpperCase(), '-TESTS.TS')) {
new Test(file).run((o) => {
var failed = false;
if(o.exitCode === 1) {
this.out.printFailure();
failed = true;
len++;
} else {
this.out.printSuccess();
len++;
}
this.files.push(new File(file, failed));
if(len > maxLen) {
len = 0;
this.out.breack();
}
if (it.hasNext()) {
this.run(it, it.next(), len, maxLen, callback);
} else {
this.out.breack();
this.timer.end();
this.printFailedFiles();
this.printStats();
callback(this.getFailedFiles().length, this.files.length);
}
});
} else if (it.hasNext()) {
this.run(it, it.next(), len, maxLen, callback);
} else {
this.out.breack();
this.timer.end();
this.printFailedFiles();
this.printStats();
callback(this.getFailedFiles().length, this.files.length);
}
}
public start(callback: Function) {
this.timer.start();
var tsFiles = this.fileHandler.allTS();
var it = new Iterator(tsFiles);
var len = 0;
var maxLen = 76;
if (it.hasNext()) {
this.run(it, it.next(), len, maxLen, callback);
}
}
}
export class TestRunner {
private fh: FileHandler;
private out: Print;
private sc: SyntaxChecking;
private te: TestEval;
private typings: Typing[] = [];
private printTypingsWithoutTest() {
var count = 0;
if (this.typings.length > 0) {
this.out.printDiv();
this.out.printTypingsWithoutTestsMessage();
this.out.printDiv();
for(var i = 0; i < this.typings.length; i++) {
var typing = this.typings[i];
if(typing.fileHandler.allTests().length == 0) {
if (typing.name != '_infrastructure'
&& typing.name != '_ReSharper.DefinitelyTyped'
&& typing.name != 'obj'
&& typing.name != 'bin'
&& typing.name != 'Properties') {
this.out.printTypingsWithoutTest(typing.name);
count++;
}
}
}
}
return count;
}
constructor(public dtPath: string) {
this.fh = new FileHandler(dtPath, /.\.ts/g);
this.out = new Print('0.9.1.1', this.fh.allTypings().length, this.fh.allTS().length);
this.sc = new SyntaxChecking(this.fh, this.out);
this.te = new TestEval(this.fh, this.out);
var tpgs = this.fh.allTypings();
for(var i = 0; i < tpgs.length; i++) {
this.typings.push(new Typing(tpgs[i], this.dtPath));
}
}
public run() {
var timer = new Timer();
timer.start();
this.out.printHeader();
this.out.printSyntaxChecking();
this.sc.start((syntaxFailedCount, syntaxTotal) => {
this.out.printTypingTests();
this.te.start((testFailedCount, testTotal) => {
var total = this.printTypingsWithoutTest();
timer.end();
this.out.printDiv();
this.out.printTotalMessage();
this.out.printDiv();
this.out.printElapsedTime(timer.asString, timer.time);
this.out.printSyntaxErrorCount(syntaxFailedCount, syntaxTotal);
this.out.printTestErrorCount(testFailedCount, testTotal);
this.out.printWithoutTestCount(total, this.fh.allTypings().length);
this.out.printDiv();
if (syntaxFailedCount > 0 || testFailedCount > 0) {
process.exit(1);
}
});
});
}
}
}
}
declare var __dirname: any;
var dtPath = __dirname + '/../..';
var runner = new DefinitelyTyped.TestManager.TestRunner(dtPath);
runner.run();
+79 -57
View File
@@ -1,57 +1,79 @@
var ExecResult = (function () {
function ExecResult() {
this.stdout = "";
this.stderr = "";
}
return ExecResult;
})();
var WindowsScriptHostExec = (function () {
function WindowsScriptHostExec() { }
WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var result = new ExecResult();
var shell = new ActiveXObject('WScript.Shell');
try {
var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' '));
} catch (e) {
result.stderr = e.message;
result.exitCode = 1;
handleResult(result);
return;
}
while(process.Status != 0) {
}
result.exitCode = process.ExitCode;
if(!process.StdOut.AtEndOfStream) {
result.stdout = process.StdOut.ReadAll();
}
if(!process.StdErr.AtEndOfStream) {
result.stderr = process.StdErr.ReadAll();
}
handleResult(result);
};
return WindowsScriptHostExec;
})();
var NodeExec = (function () {
function NodeExec() { }
NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var nodeExec = require('child_process').exec;
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
var process = nodeExec(cmdLine, function (error, stdout, stderr) {
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
handleResult(result);
});
};
return NodeExec;
})();
var Exec = (function () {
var global = Function("return this;").call(null);
if(typeof global.ActiveXObject !== "undefined") {
return new WindowsScriptHostExec();
} else {
return new NodeExec();
}
})();
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
var ExecResult = (function () {
function ExecResult() {
this.stdout = "";
this.stderr = "";
}
return ExecResult;
})();
var WindowsScriptHostExec = (function () {
function WindowsScriptHostExec() {
}
WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var result = new ExecResult();
var shell = new ActiveXObject('WScript.Shell');
try {
var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' '));
} catch (e) {
result.stderr = e.message;
result.exitCode = 1;
handleResult(result);
return;
}
while (process.Status != 0) {
}
result.exitCode = process.ExitCode;
if (!process.StdOut.AtEndOfStream)
result.stdout = process.StdOut.ReadAll();
if (!process.StdErr.AtEndOfStream)
result.stderr = process.StdErr.ReadAll();
handleResult(result);
};
return WindowsScriptHostExec;
})();
var NodeExec = (function () {
function NodeExec() {
}
NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var nodeExec = require('child_process').exec;
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
var process = nodeExec(cmdLine, function (error, stdout, stderr) {
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
handleResult(result);
});
};
return NodeExec;
})();
var Exec = (function () {
var global = Function("return this;").call(null);
if (typeof global.ActiveXObject !== "undefined") {
return new WindowsScriptHostExec();
} else {
return new NodeExec();
}
})();
+475 -425
View File
@@ -1,425 +1,475 @@
var IOUtils;
(function (IOUtils) {
function createDirectoryStructure(ioHost, dirName) {
if(ioHost.directoryExists(dirName)) {
return;
}
var parentDirectory = ioHost.dirName(dirName);
if(parentDirectory != "") {
createDirectoryStructure(ioHost, parentDirectory);
}
ioHost.createDirectory(dirName);
}
function createFileAndFolderStructure(ioHost, fileName, useUTF8) {
var path = ioHost.resolvePath(fileName);
var dirName = ioHost.dirName(path);
createDirectoryStructure(ioHost, dirName);
return ioHost.createFile(path, useUTF8);
}
IOUtils.createFileAndFolderStructure = createFileAndFolderStructure;
function throwIOError(message, error) {
var errorMessage = message;
if(error && error.message) {
errorMessage += (" " + error.message);
}
throw new Error(errorMessage);
}
IOUtils.throwIOError = throwIOError;
})(IOUtils || (IOUtils = {}));
var IO = (function () {
function getWindowsScriptHostIO() {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var streamObjectPool = [];
function getStreamObject() {
if(streamObjectPool.length > 0) {
return streamObjectPool.pop();
} else {
return new ActiveXObject("ADODB.Stream");
}
}
function releaseStreamObject(obj) {
streamObjectPool.push(obj);
}
var args = [];
for(var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
return {
readFile: function (path) {
try {
var streamObj = getStreamObject();
streamObj.Open();
streamObj.Type = 2;
streamObj.Charset = 'x-ansi';
streamObj.LoadFromFile(path);
var bomChar = streamObj.ReadText(2);
streamObj.Position = 0;
if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) {
streamObj.Charset = 'unicode';
} else if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) {
streamObj.Charset = 'utf-8';
}
var str = streamObj.ReadText(-1);
streamObj.Close();
releaseStreamObject(streamObj);
return str;
} catch (err) {
IOUtils.throwIOError("Error reading file \"" + path + "\".", err);
}
},
writeFile: function (path, contents) {
var file = this.createFile(path);
file.Write(contents);
file.Close();
},
fileExists: function (path) {
return fso.FileExists(path);
},
resolvePath: function (path) {
return fso.GetAbsolutePathName(path);
},
dirName: function (path) {
return fso.GetParentFolderName(path);
},
findFile: function (rootPath, partialFilePath) {
var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath;
while(true) {
if(fso.FileExists(path)) {
try {
var content = this.readFile(path);
return {
content: content,
path: path
};
} catch (err) {
}
} else {
rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath));
if(rootPath == "") {
return null;
} else {
path = fso.BuildPath(rootPath, partialFilePath);
}
}
}
},
deleteFile: function (path) {
try {
if(fso.FileExists(path)) {
fso.DeleteFile(path, true);
}
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
createFile: function (path, useUTF8) {
try {
var streamObj = getStreamObject();
streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi';
streamObj.Open();
return {
Write: function (str) {
streamObj.WriteText(str, 0);
},
WriteLine: function (str) {
streamObj.WriteText(str, 1);
},
Close: function () {
try {
streamObj.SaveToFile(path, 2);
} catch (saveError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError);
}finally {
if(streamObj.State != 0) {
streamObj.Close();
}
releaseStreamObject(streamObj);
}
}
};
} catch (creationError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError);
}
},
directoryExists: function (path) {
return fso.FolderExists(path);
},
createDirectory: function (path) {
try {
if(!this.directoryExists(path)) {
fso.CreateFolder(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
dir: function (path, spec, options) {
options = options || {
};
function filesInFolder(folder, root) {
var paths = [];
var fc;
if(options.recursive) {
fc = new Enumerator(folder.subfolders);
for(; !fc.atEnd(); fc.moveNext()) {
paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name));
}
}
fc = new Enumerator(folder.files);
for(; !fc.atEnd(); fc.moveNext()) {
if(!spec || fc.item().Name.match(spec)) {
paths.push(root + "/" + fc.item().Name);
}
}
return paths;
}
var folder = fso.GetFolder(path);
var paths = [];
return filesInFolder(folder, path);
},
print: function (str) {
WScript.StdOut.Write(str);
},
printLine: function (str) {
WScript.Echo(str);
},
arguments: args,
stderr: WScript.StdErr,
stdout: WScript.StdOut,
watchFile: null,
run: function (source, filename) {
try {
eval(source);
} catch (e) {
IOUtils.throwIOError("Error while executing file '" + filename + "'.", e);
}
},
getExecutingFilePath: function () {
return WScript.ScriptFullName;
},
quit: function (exitCode) {
if (typeof exitCode === "undefined") { exitCode = 0; }
try {
WScript.Quit(exitCode);
} catch (e) {
}
}
};
}
;
function getNodeIO() {
var _fs = require('fs');
var _path = require('path');
var _module = require('module');
return {
readFile: function (file) {
try {
var buffer = _fs.readFileSync(file);
switch(buffer[0]) {
case 254:
if(buffer[1] == 255) {
var i = 0;
while((i + 1) < buffer.length) {
var temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
i += 2;
}
return buffer.toString("ucs2", 2);
}
break;
case 255:
if(buffer[1] == 254) {
return buffer.toString("ucs2", 2);
}
break;
case 239:
if(buffer[1] == 187) {
return buffer.toString("utf8", 3);
}
}
return buffer.toString();
} catch (e) {
IOUtils.throwIOError("Error reading file \"" + file + "\".", e);
}
},
writeFile: _fs.writeFileSync,
deleteFile: function (path) {
try {
_fs.unlinkSync(path);
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
fileExists: function (path) {
return _fs.existsSync(path);
},
createFile: function (path, useUTF8) {
function mkdirRecursiveSync(path) {
var stats = _fs.statSync(path);
if(stats.isFile()) {
IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null);
} else if(stats.isDirectory()) {
return;
} else {
mkdirRecursiveSync(_path.dirname(path));
_fs.mkdirSync(path, 775);
}
}
mkdirRecursiveSync(_path.dirname(path));
try {
var fd = _fs.openSync(path, 'w');
} catch (e) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e);
}
return {
Write: function (str) {
_fs.writeSync(fd, str);
},
WriteLine: function (str) {
_fs.writeSync(fd, str + '\r\n');
},
Close: function () {
_fs.closeSync(fd);
fd = null;
}
};
},
dir: function dir(path, spec, options) {
options = options || {
};
function filesInFolder(folder) {
var paths = [];
var files = _fs.readdirSync(folder);
for(var i = 0; i < files.length; i++) {
var stat = _fs.statSync(folder + "/" + files[i]);
if(options.recursive && stat.isDirectory()) {
paths = paths.concat(filesInFolder(folder + "/" + files[i]));
} else if(stat.isFile() && (!spec || files[i].match(spec))) {
paths.push(folder + "/" + files[i]);
}
}
return paths;
}
return filesInFolder(path);
},
createDirectory: function (path) {
try {
if(!this.directoryExists(path)) {
_fs.mkdirSync(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
directoryExists: function (path) {
return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory();
},
resolvePath: function (path) {
return _path.resolve(path);
},
dirName: function (path) {
return _path.dirname(path);
},
findFile: function (rootPath, partialFilePath) {
var path = rootPath + "/" + partialFilePath;
while(true) {
if(_fs.existsSync(path)) {
try {
var content = this.readFile(path);
return {
content: content,
path: path
};
} catch (err) {
}
} else {
var parentPath = _path.resolve(rootPath, "..");
if(rootPath === parentPath) {
return null;
} else {
rootPath = parentPath;
path = _path.resolve(rootPath, partialFilePath);
}
}
}
},
print: function (str) {
process.stdout.write(str);
},
printLine: function (str) {
process.stdout.write(str + '\n');
},
arguments: process.argv.slice(2),
stderr: {
Write: function (str) {
process.stderr.write(str);
},
WriteLine: function (str) {
process.stderr.write(str + '\n');
},
Close: function () {
}
},
stdout: {
Write: function (str) {
process.stdout.write(str);
},
WriteLine: function (str) {
process.stdout.write(str + '\n');
},
Close: function () {
}
},
watchFile: function (filename, callback) {
var firstRun = true;
var processingChange = false;
var fileChanged = function (curr, prev) {
if(!firstRun) {
if(curr.mtime < prev.mtime) {
return;
}
_fs.unwatchFile(filename, fileChanged);
if(!processingChange) {
processingChange = true;
callback(filename);
setTimeout(function () {
processingChange = false;
}, 100);
}
}
firstRun = false;
_fs.watchFile(filename, {
persistent: true,
interval: 500
}, fileChanged);
};
fileChanged();
return {
filename: filename,
close: function () {
_fs.unwatchFile(filename, fileChanged);
}
};
},
run: function (source, filename) {
require.main.filename = filename;
require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename)));
require.main._compile(source, filename);
},
getExecutingFilePath: function () {
return process.mainModule.filename;
},
quit: process.exit
};
}
;
if(typeof ActiveXObject === "function") {
return getWindowsScriptHostIO();
} else if(typeof require === "function") {
return getNodeIO();
} else {
return null;
}
})();
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
var IOUtils;
(function (IOUtils) {
// Creates the directory including its parent if not already present
function createDirectoryStructure(ioHost, dirName) {
if (ioHost.directoryExists(dirName)) {
return;
}
var parentDirectory = ioHost.dirName(dirName);
if (parentDirectory != "") {
createDirectoryStructure(ioHost, parentDirectory);
}
ioHost.createDirectory(dirName);
}
// Creates a file including its directory structure if not already present
function createFileAndFolderStructure(ioHost, fileName, useUTF8) {
var path = ioHost.resolvePath(fileName);
var dirName = ioHost.dirName(path);
createDirectoryStructure(ioHost, dirName);
return ioHost.createFile(path, useUTF8);
}
IOUtils.createFileAndFolderStructure = createFileAndFolderStructure;
function throwIOError(message, error) {
var errorMessage = message;
if (error && error.message) {
errorMessage += (" " + error.message);
}
throw new Error(errorMessage);
}
IOUtils.throwIOError = throwIOError;
})(IOUtils || (IOUtils = {}));
var IO = (function () {
// Create an IO object for use inside WindowsScriptHost hosts
// Depends on WSCript and FileSystemObject
function getWindowsScriptHostIO() {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var streamObjectPool = [];
function getStreamObject() {
if (streamObjectPool.length > 0) {
return streamObjectPool.pop();
} else {
return new ActiveXObject("ADODB.Stream");
}
}
function releaseStreamObject(obj) {
streamObjectPool.push(obj);
}
var args = [];
for (var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
return {
readFile: function (path) {
try {
var streamObj = getStreamObject();
streamObj.Open();
streamObj.Type = 2;
streamObj.Charset = 'x-ansi';
streamObj.LoadFromFile(path);
var bomChar = streamObj.ReadText(2);
streamObj.Position = 0;
if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) {
streamObj.Charset = 'unicode';
} else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) {
streamObj.Charset = 'utf-8';
}
// Read the whole file
var str = streamObj.ReadText(-1);
streamObj.Close();
releaseStreamObject(streamObj);
return str;
} catch (err) {
IOUtils.throwIOError("Error reading file \"" + path + "\".", err);
}
},
writeFile: function (path, contents) {
var file = this.createFile(path);
file.Write(contents);
file.Close();
},
fileExists: function (path) {
return fso.FileExists(path);
},
resolvePath: function (path) {
return fso.GetAbsolutePathName(path);
},
dirName: function (path) {
return fso.GetParentFolderName(path);
},
findFile: function (rootPath, partialFilePath) {
var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath;
while (true) {
if (fso.FileExists(path)) {
try {
var content = this.readFile(path);
return { content: content, path: path };
} catch (err) {
//Tools.CompilerDiagnostics.debugPrint("Could not find " + path + ", trying parent");
}
} else {
rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath));
if (rootPath == "") {
return null;
} else {
path = fso.BuildPath(rootPath, partialFilePath);
}
}
}
},
deleteFile: function (path) {
try {
if (fso.FileExists(path)) {
fso.DeleteFile(path, true);
}
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
createFile: function (path, useUTF8) {
try {
var streamObj = getStreamObject();
streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi';
streamObj.Open();
return {
Write: function (str) {
streamObj.WriteText(str, 0);
},
WriteLine: function (str) {
streamObj.WriteText(str, 1);
},
Close: function () {
try {
streamObj.SaveToFile(path, 2);
} catch (saveError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError);
} finally {
if (streamObj.State != 0) {
streamObj.Close();
}
releaseStreamObject(streamObj);
}
}
};
} catch (creationError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError);
}
},
directoryExists: function (path) {
return fso.FolderExists(path);
},
createDirectory: function (path) {
try {
if (!this.directoryExists(path)) {
fso.CreateFolder(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
dir: function (path, spec, options) {
options = options || {};
function filesInFolder(folder, root) {
var paths = [];
var fc;
if (options.recursive) {
fc = new Enumerator(folder.subfolders);
for (; !fc.atEnd(); fc.moveNext()) {
paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name));
}
}
fc = new Enumerator(folder.files);
for (; !fc.atEnd(); fc.moveNext()) {
if (!spec || fc.item().Name.match(spec)) {
paths.push(root + "/" + fc.item().Name);
}
}
return paths;
}
var folder = fso.GetFolder(path);
var paths = [];
return filesInFolder(folder, path);
},
print: function (str) {
WScript.StdOut.Write(str);
},
printLine: function (str) {
WScript.Echo(str);
},
arguments: args,
stderr: WScript.StdErr,
stdout: WScript.StdOut,
watchFile: null,
run: function (source, filename) {
try {
eval(source);
} catch (e) {
IOUtils.throwIOError("Error while executing file '" + filename + "'.", e);
}
},
getExecutingFilePath: function () {
return WScript.ScriptFullName;
},
quit: function (exitCode) {
if (typeof exitCode === "undefined") { exitCode = 0; }
try {
WScript.Quit(exitCode);
} catch (e) {
}
}
};
}
;
// Create an IO object for use inside Node.js hosts
// Depends on 'fs' and 'path' modules
function getNodeIO() {
var _fs = require('fs');
var _path = require('path');
var _module = require('module');
return {
readFile: function (file) {
try {
var buffer = _fs.readFileSync(file);
switch (buffer[0]) {
case 0xFE:
if (buffer[1] == 0xFF) {
// utf16-be. Reading the buffer as big endian is not supported, so convert it to
// Little Endian first
var i = 0;
while ((i + 1) < buffer.length) {
var temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
i += 2;
}
return buffer.toString("ucs2", 2);
}
break;
case 0xFF:
if (buffer[1] == 0xFE) {
// utf16-le
return buffer.toString("ucs2", 2);
}
break;
case 0xEF:
if (buffer[1] == 0xBB) {
// utf-8
return buffer.toString("utf8", 3);
}
}
// Default behaviour
return buffer.toString();
} catch (e) {
IOUtils.throwIOError("Error reading file \"" + file + "\".", e);
}
},
writeFile: _fs.writeFileSync,
deleteFile: function (path) {
try {
_fs.unlinkSync(path);
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
fileExists: function (path) {
return _fs.existsSync(path);
},
createFile: function (path, useUTF8) {
function mkdirRecursiveSync(path) {
var stats = _fs.statSync(path);
if (stats.isFile()) {
IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null);
} else if (stats.isDirectory()) {
return;
} else {
mkdirRecursiveSync(_path.dirname(path));
_fs.mkdirSync(path, 0775);
}
}
mkdirRecursiveSync(_path.dirname(path));
try {
var fd = _fs.openSync(path, 'w');
} catch (e) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e);
}
return {
Write: function (str) {
_fs.writeSync(fd, str);
},
WriteLine: function (str) {
_fs.writeSync(fd, str + '\r\n');
},
Close: function () {
_fs.closeSync(fd);
fd = null;
}
};
},
dir: function dir(path, spec, options) {
options = options || {};
function filesInFolder(folder, deep) {
var paths = [];
var files = _fs.readdirSync(folder);
for (var i = 0; i < files.length; i++) {
var stat = _fs.statSync(folder + "/" + files[i]);
if (options.recursive && stat.isDirectory()) {
if (deep < (options.deep || 100)) {
paths = paths.concat(filesInFolder(folder + "/" + files[i], 1));
}
} else if (stat.isFile() && (!spec || files[i].match(spec))) {
paths.push(folder + "/" + files[i]);
}
}
return paths;
}
return filesInFolder(path, 0);
},
createDirectory: function (path) {
try {
if (!this.directoryExists(path)) {
_fs.mkdirSync(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
directoryExists: function (path) {
return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory();
},
resolvePath: function (path) {
return _path.resolve(path);
},
dirName: function (path) {
return _path.dirname(path);
},
findFile: function (rootPath, partialFilePath) {
var path = rootPath + "/" + partialFilePath;
while (true) {
if (_fs.existsSync(path)) {
try {
var content = this.readFile(path);
return { content: content, path: path };
} catch (err) {
//Tools.CompilerDiagnostics.debugPrint(("Could not find " + path) + ", trying parent");
}
} else {
var parentPath = _path.resolve(rootPath, "..");
if (rootPath === parentPath) {
return null;
} else {
rootPath = parentPath;
path = _path.resolve(rootPath, partialFilePath);
}
}
}
},
print: function (str) {
process.stdout.write(str);
},
printLine: function (str) {
process.stdout.write(str + '\n');
},
arguments: process.argv.slice(2),
stderr: {
Write: function (str) {
process.stderr.write(str);
},
WriteLine: function (str) {
process.stderr.write(str + '\n');
},
Close: function () {
}
},
stdout: {
Write: function (str) {
process.stdout.write(str);
},
WriteLine: function (str) {
process.stdout.write(str + '\n');
},
Close: function () {
}
},
watchFile: function (filename, callback) {
var firstRun = true;
var processingChange = false;
var fileChanged = function (curr, prev) {
if (!firstRun) {
if (curr.mtime < prev.mtime) {
return;
}
_fs.unwatchFile(filename, fileChanged);
if (!processingChange) {
processingChange = true;
callback(filename);
setTimeout(function () {
processingChange = false;
}, 100);
}
}
firstRun = false;
_fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged);
};
fileChanged();
return {
filename: filename,
close: function () {
_fs.unwatchFile(filename, fileChanged);
}
};
},
run: function (source, filename) {
require.main.filename = filename;
require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename)));
require.main._compile(source, filename);
},
getExecutingFilePath: function () {
return process.mainModule.filename;
},
quit: process.exit
};
}
;
if (typeof ActiveXObject === "function")
return getWindowsScriptHostIO();
else if (typeof require === "function")
return getNodeIO();
else
return null;
})();
+14 -14
View File
@@ -25,11 +25,11 @@ interface IFileWatcher {
interface IIO {
readFile(path: string): string;
writeFile(path: string, contents: string): void;
createFile(path: string, useUTF8?: bool): ITextWriter;
createFile(path: string, useUTF8?: boolean): ITextWriter;
deleteFile(path: string): void;
dir(path: string, re?: RegExp, options?: { recursive?: bool; deep?: number; }): string[];
fileExists(path: string): bool;
directoryExists(path: string): bool;
dir(path: string, re?: RegExp, options?: { recursive?: boolean; deep?: number; }): string[];
fileExists(path: string): boolean;
directoryExists(path: string): boolean;
createDirectory(path: string): void;
resolvePath(path: string): string;
dirName(path: string): string;
@@ -60,7 +60,7 @@ module IOUtils {
}
// Creates a file including its directory structure if not already present
export function createFileAndFolderStructure(ioHost: IIO, fileName: string, useUTF8?: bool) {
export function createFileAndFolderStructure(ioHost: IIO, fileName: string, useUTF8?: boolean) {
var path = ioHost.resolvePath(fileName);
var dirName = ioHost.dirName(path);
createDirectoryStructure(ioHost, dirName);
@@ -78,13 +78,13 @@ module IOUtils {
// Declare dependencies needed for all supported hosts
declare class Enumerator {
public atEnd(): bool;
public atEnd(): boolean;
public moveNext();
public item(): any;
constructor (o: any);
}
declare function setTimeout(callback: () =>void , ms?: number);
declare var require: any;
//declare var require: any;
declare module process {
export var argv: string[];
export var platform: string;
@@ -160,7 +160,7 @@ var IO = (function() {
file.Close();
},
fileExists: function(path: string): bool {
fileExists: function(path: string): boolean {
return fso.FileExists(path);
},
@@ -236,7 +236,7 @@ var IO = (function() {
},
directoryExists: function(path) {
return <bool>fso.FolderExists(path);
return <boolean>fso.FolderExists(path);
},
createDirectory: function(path) {
@@ -250,7 +250,7 @@ var IO = (function() {
},
dir: function(path, spec?, options?) {
options = options || <{ recursive?: bool; deep?: number; }>{};
options = options || <{ recursive?: boolean; deep?: number; }>{};
function filesInFolder(folder, root): string[]{
var paths = [];
var fc: Enumerator;
@@ -302,7 +302,7 @@ var IO = (function() {
getExecutingFilePath: function () {
return WScript.ScriptFullName;
},
quit: function (exitCode? : number = 0) {
quit: function (exitCode : number = 0) {
try {
WScript.Quit(exitCode);
} catch (e) {
@@ -365,7 +365,7 @@ var IO = (function() {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
fileExists: function(path): bool {
fileExists: function(path): boolean {
return _fs.existsSync(path);
},
createFile: function(path, useUTF8?) {
@@ -395,7 +395,7 @@ var IO = (function() {
};
},
dir: function dir(path, spec?, options?) {
options = options || <{ recursive?: bool; deep?: number; }>{};
options = options || <{ recursive?: boolean; deep?: number; }>{};
function filesInFolder(folder: string, deep?: number): string[]{
var paths = [];
@@ -427,7 +427,7 @@ var IO = (function() {
}
},
directoryExists: function(path: string): bool {
directoryExists: function(path: string): boolean {
return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory();
},
resolvePath: function(path: string): string {
-619
View File
@@ -1,619 +0,0 @@
var ExecResult = (function () {
function ExecResult() {
this.stdout = "";
this.stderr = "";
}
return ExecResult;
})();
var WindowsScriptHostExec = (function () {
function WindowsScriptHostExec() { }
WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var result = new ExecResult();
var shell = new ActiveXObject('WScript.Shell');
try {
var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' '));
} catch (e) {
result.stderr = e.message;
result.exitCode = 1;
handleResult(result);
return;
}
while(process.Status != 0) {
}
result.exitCode = process.ExitCode;
if(!process.StdOut.AtEndOfStream) {
result.stdout = process.StdOut.ReadAll();
}
if(!process.StdErr.AtEndOfStream) {
result.stderr = process.StdErr.ReadAll();
}
handleResult(result);
};
return WindowsScriptHostExec;
})();
var NodeExec = (function () {
function NodeExec() { }
NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var nodeExec = require('child_process').exec;
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
var process = nodeExec(cmdLine, function (error, stdout, stderr) {
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
handleResult(result);
});
};
return NodeExec;
})();
var Exec = (function () {
var global = Function("return this;").call(null);
if(typeof global.ActiveXObject !== "undefined") {
return new WindowsScriptHostExec();
} else {
return new NodeExec();
}
})();
var IOUtils;
(function (IOUtils) {
function createDirectoryStructure(ioHost, dirName) {
if(ioHost.directoryExists(dirName)) {
return;
}
var parentDirectory = ioHost.dirName(dirName);
if(parentDirectory != "") {
createDirectoryStructure(ioHost, parentDirectory);
}
ioHost.createDirectory(dirName);
}
function createFileAndFolderStructure(ioHost, fileName, useUTF8) {
var path = ioHost.resolvePath(fileName);
var dirName = ioHost.dirName(path);
createDirectoryStructure(ioHost, dirName);
return ioHost.createFile(path, useUTF8);
}
IOUtils.createFileAndFolderStructure = createFileAndFolderStructure;
function throwIOError(message, error) {
var errorMessage = message;
if(error && error.message) {
errorMessage += (" " + error.message);
}
throw new Error(errorMessage);
}
IOUtils.throwIOError = throwIOError;
})(IOUtils || (IOUtils = {}));
var IO = (function () {
function getWindowsScriptHostIO() {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var streamObjectPool = [];
function getStreamObject() {
if(streamObjectPool.length > 0) {
return streamObjectPool.pop();
} else {
return new ActiveXObject("ADODB.Stream");
}
}
function releaseStreamObject(obj) {
streamObjectPool.push(obj);
}
var args = [];
for(var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
return {
readFile: function (path) {
try {
var streamObj = getStreamObject();
streamObj.Open();
streamObj.Type = 2;
streamObj.Charset = 'x-ansi';
streamObj.LoadFromFile(path);
var bomChar = streamObj.ReadText(2);
streamObj.Position = 0;
if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) {
streamObj.Charset = 'unicode';
} else if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) {
streamObj.Charset = 'utf-8';
}
var str = streamObj.ReadText(-1);
streamObj.Close();
releaseStreamObject(streamObj);
return str;
} catch (err) {
IOUtils.throwIOError("Error reading file \"" + path + "\".", err);
}
},
writeFile: function (path, contents) {
var file = this.createFile(path);
file.Write(contents);
file.Close();
},
fileExists: function (path) {
return fso.FileExists(path);
},
resolvePath: function (path) {
return fso.GetAbsolutePathName(path);
},
dirName: function (path) {
return fso.GetParentFolderName(path);
},
findFile: function (rootPath, partialFilePath) {
var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath;
while(true) {
if(fso.FileExists(path)) {
try {
var content = this.readFile(path);
return {
content: content,
path: path
};
} catch (err) {
}
} else {
rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath));
if(rootPath == "") {
return null;
} else {
path = fso.BuildPath(rootPath, partialFilePath);
}
}
}
},
deleteFile: function (path) {
try {
if(fso.FileExists(path)) {
fso.DeleteFile(path, true);
}
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
createFile: function (path, useUTF8) {
try {
var streamObj = getStreamObject();
streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi';
streamObj.Open();
return {
Write: function (str) {
streamObj.WriteText(str, 0);
},
WriteLine: function (str) {
streamObj.WriteText(str, 1);
},
Close: function () {
try {
streamObj.SaveToFile(path, 2);
} catch (saveError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError);
}finally {
if(streamObj.State != 0) {
streamObj.Close();
}
releaseStreamObject(streamObj);
}
}
};
} catch (creationError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError);
}
},
directoryExists: function (path) {
return fso.FolderExists(path);
},
createDirectory: function (path) {
try {
if(!this.directoryExists(path)) {
fso.CreateFolder(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
dir: function (path, spec, options) {
options = options || {
};
function filesInFolder(folder, root) {
var paths = [];
var fc;
if(options.recursive) {
fc = new Enumerator(folder.subfolders);
for(; !fc.atEnd(); fc.moveNext()) {
paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name));
}
}
fc = new Enumerator(folder.files);
for(; !fc.atEnd(); fc.moveNext()) {
if(!spec || fc.item().Name.match(spec)) {
paths.push(root + "/" + fc.item().Name);
}
}
return paths;
}
var folder = fso.GetFolder(path);
var paths = [];
return filesInFolder(folder, path);
},
print: function (str) {
WScript.StdOut.Write(str);
},
printLine: function (str) {
WScript.Echo(str);
},
arguments: args,
stderr: WScript.StdErr,
stdout: WScript.StdOut,
watchFile: null,
run: function (source, filename) {
try {
eval(source);
} catch (e) {
IOUtils.throwIOError("Error while executing file '" + filename + "'.", e);
}
},
getExecutingFilePath: function () {
return WScript.ScriptFullName;
},
quit: function (exitCode) {
if (typeof exitCode === "undefined") { exitCode = 0; }
try {
WScript.Quit(exitCode);
} catch (e) {
}
}
};
}
;
function getNodeIO() {
var _fs = require('fs');
var _path = require('path');
var _module = require('module');
return {
readFile: function (file) {
try {
var buffer = _fs.readFileSync(file);
switch(buffer[0]) {
case 254:
if(buffer[1] == 255) {
var i = 0;
while((i + 1) < buffer.length) {
var temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
i += 2;
}
return buffer.toString("ucs2", 2);
}
break;
case 255:
if(buffer[1] == 254) {
return buffer.toString("ucs2", 2);
}
break;
case 239:
if(buffer[1] == 187) {
return buffer.toString("utf8", 3);
}
}
return buffer.toString();
} catch (e) {
IOUtils.throwIOError("Error reading file \"" + file + "\".", e);
}
},
writeFile: _fs.writeFileSync,
deleteFile: function (path) {
try {
_fs.unlinkSync(path);
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
fileExists: function (path) {
return _fs.existsSync(path);
},
createFile: function (path, useUTF8) {
function mkdirRecursiveSync(path) {
var stats = _fs.statSync(path);
if(stats.isFile()) {
IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null);
} else if(stats.isDirectory()) {
return;
} else {
mkdirRecursiveSync(_path.dirname(path));
_fs.mkdirSync(path, 775);
}
}
mkdirRecursiveSync(_path.dirname(path));
try {
var fd = _fs.openSync(path, 'w');
} catch (e) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e);
}
return {
Write: function (str) {
_fs.writeSync(fd, str);
},
WriteLine: function (str) {
_fs.writeSync(fd, str + '\r\n');
},
Close: function () {
_fs.closeSync(fd);
fd = null;
}
};
},
dir: function dir(path, spec, options) {
options = options || {
};
function filesInFolder(folder, deep) {
var paths = [];
var files = _fs.readdirSync(folder);
for(var i = 0; i < files.length; i++) {
var stat = _fs.statSync(folder + "/" + files[i]);
if(options.recursive && stat.isDirectory()) {
if(deep < (options.deep || 100)) {
paths = paths.concat(filesInFolder(folder + "/" + files[i], 1));
}
} else if(stat.isFile() && (!spec || files[i].match(spec))) {
paths.push(folder + "/" + files[i]);
}
}
return paths;
}
return filesInFolder(path, 0);
},
createDirectory: function (path) {
try {
if(!this.directoryExists(path)) {
_fs.mkdirSync(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
directoryExists: function (path) {
return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory();
},
resolvePath: function (path) {
return _path.resolve(path);
},
dirName: function (path) {
return _path.dirname(path);
},
findFile: function (rootPath, partialFilePath) {
var path = rootPath + "/" + partialFilePath;
while(true) {
if(_fs.existsSync(path)) {
try {
var content = this.readFile(path);
return {
content: content,
path: path
};
} catch (err) {
}
} else {
var parentPath = _path.resolve(rootPath, "..");
if(rootPath === parentPath) {
return null;
} else {
rootPath = parentPath;
path = _path.resolve(rootPath, partialFilePath);
}
}
}
},
print: function (str) {
process.stdout.write(str);
},
printLine: function (str) {
process.stdout.write(str + '\n');
},
arguments: process.argv.slice(2),
stderr: {
Write: function (str) {
process.stderr.write(str);
},
WriteLine: function (str) {
process.stderr.write(str + '\n');
},
Close: function () {
}
},
stdout: {
Write: function (str) {
process.stdout.write(str);
},
WriteLine: function (str) {
process.stdout.write(str + '\n');
},
Close: function () {
}
},
watchFile: function (filename, callback) {
var firstRun = true;
var processingChange = false;
var fileChanged = function (curr, prev) {
if(!firstRun) {
if(curr.mtime < prev.mtime) {
return;
}
_fs.unwatchFile(filename, fileChanged);
if(!processingChange) {
processingChange = true;
callback(filename);
setTimeout(function () {
processingChange = false;
}, 100);
}
}
firstRun = false;
_fs.watchFile(filename, {
persistent: true,
interval: 500
}, fileChanged);
};
fileChanged();
return {
filename: filename,
close: function () {
_fs.unwatchFile(filename, fileChanged);
}
};
},
run: function (source, filename) {
require.main.filename = filename;
require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename)));
require.main._compile(source, filename);
},
getExecutingFilePath: function () {
return process.mainModule.filename;
},
quit: process.exit
};
}
;
if(typeof ActiveXObject === "function") {
return getWindowsScriptHostIO();
} else if(typeof require === "function") {
return getNodeIO();
} else {
return null;
}
})();
var cfg = {
root: '.',
pattern: /.\-tests\.ts/g,
tsc: 'node ./_infrastructure/tests/typescript_0.8.3/tsc.js ',
exclude: {
'.git': true,
'.gitignore': true,
'package.json': true,
'_infrastructure': true,
'.travis.yml': true,
'LICENSE': true,
'README.md': true,
'_ReSharper.DefinitelyTyped': true,
'obj': true,
'bin': true,
'Properties': true,
'DefinitelyTyped.csproj': true,
'DefinitelyTyped.csproj.user': true,
'DefinitelyTyped.sln': true,
'DefinitelyTyped.v11.suo': true
}
};
if(process.argv.length > 2) {
cfg.root = process.argv[2];
}
var TestFile = (function () {
function TestFile() {
this.errors = [];
}
return TestFile;
})();
var Test = (function () {
function Test(lib) {
this.lib = lib;
this.files = [];
}
return Test;
})();
var Tests = (function () {
function Tests() {
this.tests = [];
}
return Tests;
})();
function getLibDirectory(file) {
return file.substr(cfg.root.length).split('/')[1];
}
function getErrorList(out) {
var splitContentByNewlines = function (content) {
var lines = content.split('\r\n');
if(lines.length === 1) {
lines = content.split('\n');
}
return lines;
};
var result = [];
var lines = splitContentByNewlines(out);
for(var i = 0; i < lines.length; i++) {
if(lines[i]) {
result.push(lines[i]);
}
}
return result;
}
function runTests(testFiles) {
var tests = new Tests();
Exec.exec(cfg.tsc, [
testFiles[testIndex]
], function (ExecResult) {
var lib = getLibDirectory(testFiles[testIndex]);
cache_visited_libs[lib] = true;
var testFile = new TestFile();
testFile.name = testFiles[testIndex];
testFile.errors = getErrorList(ExecResult.stderr);
if(testFile.errors.length == 0) {
total_success++;
} else {
total_failure++;
}
console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length) + ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m'));
var test = new Test(lib);
test.files.push(testFile);
tests.tests.push(test);
testIndex++;
if(testIndex < totalTest) {
Exec.exec(cfg.tsc, [
testFiles[testIndex]
], arguments.callee);
} else {
var withoutTests = {
};
for(var k = 0; k < allFiles.length; k++) {
var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1];
if(!(rootFolder in cfg.exclude)) {
if(!(rootFolder in cache_visited_libs)) {
withoutTests[rootFolder] = true;
}
}
}
var withoutTestsCount = 0;
for(var attr in withoutTests) {
var test = new Test(attr);
tests.tests.push(test);
console.log(' [\033[36m' + attr + '\033[0m] without tests');
withoutTestsCount++;
}
console.log('\n> ' + (total_failure + total_success + withoutTestsCount) + ' tests. ' + '\033[32m' + total_success + ' tests success\033[0m, ' + '\033[31m' + total_failure + ' tests failed\033[0m and ' + withoutTestsCount + ' definitions without tests.\n');
if(total_failure > 0) {
process.exit(1);
}
}
});
}
var testFiles = IO.dir(cfg.root, cfg.pattern, {
recursive: true,
deep: 1
});
var allFiles = IO.dir(cfg.root, null, {
recursive: true
});
var totalTest = testFiles.length;
var testIndex = 0;
var cache_visited_libs = {
};
var total_failure = 0;
var total_success = 0;
var tscVersion = '?.?.?';
Exec.exec(cfg.tsc, [
'-version'
], function (ExecResult) {
tscVersion = ExecResult.stdout;
console.log('$ tsc -version');
console.log(tscVersion);
runTests(testFiles);
});
-168
View File
@@ -1,168 +0,0 @@
/// <reference path='src/exec.ts' />
/// <reference path='src/io.ts' />
var cfg = {
root: '.',
pattern: /.\-tests\.ts/g,
tsc: 'node ./_infrastructure/tests/typescript/tsc.js ',
exclude: {
'.git': true,
'.gitignore': true,
'package.json': true,
'_infrastructure': true,
'.travis.yml': true,
'LICENSE': true,
'README.md': true,
'_ReSharper.DefinitelyTyped': true,
'obj': true,
'bin': true,
'Properties': true,
'DefinitelyTyped.csproj': true,
'DefinitelyTyped.csproj.user': true,
'DefinitelyTyped.sln': true,
'DefinitelyTyped.v11.suo': true
}
};
if (process.argv.length > 2) {
cfg.root = process.argv[2];
}
class TestFile {
public name: string;
public errors: string[] = [];
}
class Test {
public files: TestFile[] = [];
constructor(public lib: string) { }
}
class Tests {
public tests: Test[] = [];
}
function getLibDirectory(file: string) {
return file.substr(cfg.root.length).split('/')[1];
}
function getErrorList(out): string[] {
var splitContentByNewlines = function (content: string) {
var lines = content.split('\r\n');
if (lines.length === 1) {
lines = content.split('\n');
}
return lines;
}
var result: string[] = [];
var lines = splitContentByNewlines(out);
for (var i = 0; i < lines.length; i++) {
if (lines[i]) {
result.push(lines[i]);
}
}
return result;
}
function runTests(testFiles) {
var tests = new Tests();
Exec.exec(
cfg.tsc,
[testFiles[testIndex]],
(ExecResult) => {
var lib = getLibDirectory(testFiles[testIndex]);
cache_visited_libs[lib] = true;
var testFile = new TestFile();
testFile.name = testFiles[testIndex];
testFile.errors = getErrorList(ExecResult.stderr);
if (testFile.errors.length == 0) {
total_success++;
} else {
total_failure++;
}
console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length)
+ ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m'));
var test = new Test(lib);
test.files.push(testFile);
tests.tests.push(test);
testIndex++;
if (testIndex < totalTest) {
Exec.exec(
cfg.tsc,
[testFiles[testIndex]],
<(ExecResult) => any>arguments.callee);
} else {
var withoutTests = {};
for (var k = 0; k < allFiles.length; k++) {
var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1];
if (!(rootFolder in cfg.exclude)) {
if (!(rootFolder in cache_visited_libs)) {
withoutTests[rootFolder] = true;
}
}
}
var withoutTestsCount = 0;
for (var attr in withoutTests) {
var test = new Test(attr);
tests.tests.push(test);
console.log(' [\033[36m' + attr + '\033[0m] without tests');
withoutTestsCount++;
}
console.log('\n> ' + (total_failure + total_success + withoutTestsCount)
+ ' tests. '
+ '\033[32m' + total_success + ' tests success\033[0m, '
+ '\033[31m' + total_failure + ' tests failed\033[0m and '
+ withoutTestsCount + ' definitions without tests.\n');
if (total_failure > 0) {
process.exit(1);
}
}
});
}
////// GLOBAL VARS
// get all files: "*-tests.ts"
var testFiles = IO.dir(cfg.root, cfg.pattern, { recursive: true, deep: 1 });
// get all proect files
var allFiles = IO.dir(cfg.root, null, { recursive: true });
var totalTest = testFiles.length;
var testIndex = 0;
var cache_visited_libs = {};
// total
var total_failure = 0;
var total_success = 0;
// var to have current typescript version
var tscVersion = '?.?.?';
////// END GLOBAL VARS
// entry point
Exec.exec(cfg.tsc, ['-version'], (ExecResult) => {
tscVersion = ExecResult.stdout;
console.log('$ tsc -version');
console.log(tscVersion);
runTests(testFiles);
});
+9178 -9074
View File
File diff suppressed because it is too large Load Diff
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+110 -110
View File
@@ -3,7 +3,7 @@
// Definitions by: Diullei Gomes <https://github.com/Diullei>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
module AceAjax {
declare module AceAjax {
export interface Delta {
action: string;
@@ -50,7 +50,7 @@ module AceAjax {
export interface TokenInfo {
value: string;
}
}
export interface Position {
@@ -67,7 +67,7 @@ module AceAjax {
addKeyboardHandler(kb, pos);
removeKeyboardHandler(kb): bool;
removeKeyboardHandler(kb): boolean;
getKeyboardHandler(): any;
@@ -75,7 +75,7 @@ module AceAjax {
onTextInput(text);
}
declare var KeyBinding: {
var KeyBinding: {
new(editor: Editor): KeyBinding;
}
@@ -87,7 +87,7 @@ module AceAjax {
getNextLineIndent (state, line, tab): string;
checkOutdent(state, line, input): bool;
checkOutdent(state, line, input): boolean;
autoOutdent(state, doc, row);
@@ -177,14 +177,14 @@ module AceAjax {
* @param column The column index to move the anchor to
* @param noClip Identifies if you want the position to be clipped
**/
setPosition(row: number, column: number, noClip: bool);
setPosition(row: number, column: number, noClip: boolean);
/**
* When called, the `'change'` event listener is removed.
**/
detach();
}
declare var Anchor: {
var Anchor: {
/**
* Creates a new `Anchor` and associates it with a document.
* @param doc The document to associate with the anchor
@@ -248,7 +248,7 @@ module AceAjax {
**/
getState(row: number): string;
}
declare var BackgroundTokenizer: {
var BackgroundTokenizer: {
/**
* Creates a new `BackgroundTokenizer` object.
* @param tokenizer The tokenizer to use
@@ -307,7 +307,7 @@ module AceAjax {
* Returns `true` if `text` is a newline character (either `\r\n`, `\r`, or `\n`).
* @param text The text to check
**/
isNewLine(text: string): bool;
isNewLine(text: string): boolean;
/**
* Returns a verbatim copy of the given line as it is in the document
@@ -435,7 +435,7 @@ module AceAjax {
**/
positionToIndex(pos: Position, startRow: number): number;
}
declare var Document: {
var Document: {
/**
* Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty.
* @param text The starting text
@@ -476,7 +476,7 @@ module AceAjax {
expandFold(arg: any);
unfold(arg1: any, arg2: bool);
unfold(arg1: any, arg2: boolean);
screenToDocumentColumn(row: number, column: number);
@@ -560,12 +560,12 @@ module AceAjax {
* Pass `true` to enable the use of soft tabs. Soft tabs means you're using spaces instead of the tab character (`'\t'`).
* @param useSoftTabs Value indicating whether or not to use soft tabs
**/
setUseSoftTabs(useSoftTabs: bool);
setUseSoftTabs(useSoftTabs: boolean);
/**
* Returns `true` if soft tabs are being used, `false` otherwise.
**/
getUseSoftTabs(): bool;
getUseSoftTabs(): boolean;
/**
* Set the number of spaces that define a soft tab; for example, passing in `4` transforms the soft tabs to be equivalent to four spaces. This function also emits the `changeTabSize` event.
@@ -582,19 +582,19 @@ module AceAjax {
* Returns `true` if the character at the position is a soft tab.
* @param position The position to check
**/
isTabStop(position: any): bool;
isTabStop(position: any): boolean;
/**
* Pass in `true` to enable overwrites in your session, or `false` to disable.
* If overwrites is enabled, any text you enter will type over any text after it. If the value of `overwrite` changes, this function also emites the `changeOverwrite` event.
* @param overwrite Defines wheter or not to set overwrites
**/
setOverwrite(overwrite: bool);
setOverwrite(overwrite: boolean);
/**
* Returns `true` if overwrites are enabled; `false` otherwise.
**/
getOverwrite(): bool;
getOverwrite(): boolean;
/**
* Sets the value of overwrite to the opposite of whatever it currently is.
@@ -651,7 +651,7 @@ module AceAjax {
* @param type Identify the type of the marker
* @param inFront Set to `true` to establish a front marker
**/
addMarker(range: Range, clazz: string, type: Function, inFront: bool);
addMarker(range: Range, clazz: string, type: Function, inFront: boolean);
/**
* Adds a new marker to the given `Range`. If `inFront` is `true`, a front marker is defined, and the `'changeFrontMarker'` event fires; otherwise, the `'changeBackMarker'` event fires.
@@ -660,14 +660,14 @@ module AceAjax {
* @param type Identify the type of the marker
* @param inFront Set to `true` to establish a front marker
**/
addMarker(range: Range, clazz: string, type: string, inFront: bool);
addMarker(range: Range, clazz: string, type: string, inFront: boolean);
/**
* Adds a dynamic marker to the session.
* @param marker object with update method
* @param inFront Set to `true` to establish a front marker
**/
addDynamicMarker(marker: any, inFront: bool);
addDynamicMarker(marker: any, inFront: boolean);
/**
* Removes the marker with the specified ID. If this marker was in front, the `'changeFrontMarker'` event is emitted. If the marker was in the back, the `'changeBackMarker'` event is emitted.
@@ -679,7 +679,7 @@ module AceAjax {
* Returns an array containing the IDs of all the markers, either front or back.
* @param inFront If `true`, indicates you only want front markers; `false` indicates only back markers
**/
getMarkers(inFront: bool): Array;
getMarkers(inFront: boolean): Array;
/**
* Sets annotations for the `EditSession`. This functions emits the `'changeAnnotation'` event.
@@ -732,12 +732,12 @@ module AceAjax {
* Identifies if you want to use a worker for the `EditSession`.
* @param useWorker Set to `true` to use a worker
**/
setUseWorker(useWorker: bool);
setUseWorker(useWorker: boolean);
/**
* Returns `true` if workers are being used.
**/
getUseWorker(): bool;
getUseWorker(): boolean;
/**
* Reloads all the tokens on the current session. This function calls [[BackgroundTokenizer.start `BackgroundTokenizer.start ()`]] to all the rows; it also emits the `'tokenizerUpdate'` event.
@@ -823,20 +823,20 @@ module AceAjax {
* @param deltas An array of previous changes
* @param dontSelect [If `true`, doesn't select the range of where the change occured]{: #dontSelect}
**/
undoChanges(deltas: Array, dontSelect: bool): Range;
undoChanges(deltas: Array, dontSelect: boolean): Range;
/**
* Re-implements a previously undone change to your document.
* @param deltas An array of previous changes
* @param dontSelect {:dontSelect}
**/
redoChanges(deltas: Array, dontSelect: bool): Range;
redoChanges(deltas: Array, dontSelect: boolean): Range;
/**
* Enables or disables highlighting of the range where an undo occured.
* @param enable If `true`, selects the range of the reinserted change
**/
setUndoSelect(enable: bool);
setUndoSelect(enable: boolean);
/**
* Replaces a range in the document with the new `text`.
@@ -895,12 +895,12 @@ module AceAjax {
* Sets whether or not line wrapping is enabled. If `useWrapMode` is different than the current value, the `'changeWrapMode'` event is emitted.
* @param useWrapMode Enable (or disable) wrap mode
**/
setUseWrapMode(useWrapMode: bool);
setUseWrapMode(useWrapMode: boolean);
/**
* Returns `true` if wrap mode is being used; `false` otherwise.
**/
getUseWrapMode(): bool;
getUseWrapMode(): boolean;
/**
* Sets the boundaries of wrap. Either value can be `null` to have an unconstrained wrap, or, they can be the same number to pin the limit. If the wrap limits for `min` or `max` are different, this method also emits the `'changeWrapMode'` event.
@@ -913,7 +913,7 @@ module AceAjax {
* This should generally only be called by the renderer when a resize is detected.
* @param desiredLimit The new wrap limit
**/
adjustWrapLimit(desiredLimit: number): bool;
adjustWrapLimit(desiredLimit: number): boolean;
/**
* Returns the value of wrap limit.
@@ -1011,7 +1011,7 @@ module AceAjax {
**/
getScreenLength(): number;
}
declare var EditSession: {
var EditSession: {
/**
* Sets up a new `EditSession` and associates it with the given `Document` and `TextMode`.
* @param text [If `text` is a `Document`, it associates the `EditSession` with it. Otherwise, a new `Document` is created, with the initial text]{: #textParam}
@@ -1023,7 +1023,7 @@ module AceAjax {
new (text: string[], mode?: string): IEditSession;
}
////////////////////////////////
/// Editor
////////////////////////////////
@@ -1035,12 +1035,12 @@ module AceAjax {
**/
export interface Editor {
inMultiSelectMode: bool;
inMultiSelectMode: boolean;
selectMoreLines(n: number);
onTextInput(text: string);
onCommandKey(e, hashId, keyCode);
commands: CommandManager;
@@ -1104,7 +1104,7 @@ module AceAjax {
* {:VirtualRenderer.onResize}
* @param force If `true`, recomputes the size, even if the height and width haven't changed
**/
resize(force?: bool);
resize(force?: boolean);
/**
* {:VirtualRenderer.setTheme}
@@ -1201,12 +1201,12 @@ module AceAjax {
* Pass in `true` to enable overwrites in your session, or `false` to disable. If overwrites is enabled, any text you enter will type over any text after it. If the value of `overwrite` changes, this function also emites the `changeOverwrite` event.
* @param overwrite Defines wheter or not to set overwrites
**/
setOverwrite(overwrite: bool);
setOverwrite(overwrite: boolean);
/**
* Returns `true` if overwrites are enabled; `false` otherwise.
**/
getOverwrite(): bool;
getOverwrite(): boolean;
/**
* Sets the value of overwrite to the opposite of whatever it currently is.
@@ -1253,7 +1253,7 @@ module AceAjax {
* Determines whether or not the current line should be highlighted.
* @param shouldHighlight Set to `true` to highlight the current line
**/
setHighlightActiveLine(shouldHighlight: bool);
setHighlightActiveLine(shouldHighlight: boolean);
/**
* Returns `true` if current lines are always highlighted.
@@ -1264,34 +1264,34 @@ module AceAjax {
* Determines if the currently selected word should be highlighted.
* @param shouldHighlight Set to `true` to highlight the currently selected word
**/
setHighlightSelectedWord(shouldHighlight: bool);
setHighlightSelectedWord(shouldHighlight: boolean);
/**
* Returns `true` if currently highlighted words are to be highlighted.
**/
getHighlightSelectedWord(): bool;
getHighlightSelectedWord(): boolean;
/**
* If `showInvisibiles` is set to `true`, invisible characters&mdash;like spaces or new lines&mdash;are show in the editor.
* @param showInvisibles Specifies whether or not to show invisible characters
**/
setShowInvisibles(showInvisibles: bool);
setShowInvisibles(showInvisibles: boolean);
/**
* Returns `true` if invisible characters are being shown.
**/
getShowInvisibles(): bool;
getShowInvisibles(): boolean;
/**
* If `showPrintMargin` is set to `true`, the print margin is shown in the editor.
* @param showPrintMargin Specifies whether or not to show the print margin
**/
setShowPrintMargin(showPrintMargin: bool);
setShowPrintMargin(showPrintMargin: boolean);
/**
* Returns `true` if the print margin is being shown.
**/
getShowPrintMargin(): bool;
getShowPrintMargin(): boolean;
/**
* Sets the column defining where the print margin should be.
@@ -1308,30 +1308,30 @@ module AceAjax {
* If `readOnly` is true, then the editor is set to read-only mode, and none of the content can change.
* @param readOnly Specifies whether the editor can be modified or not
**/
setReadOnly(readOnly: bool);
setReadOnly(readOnly: boolean);
/**
* Returns `true` if the editor is set to read-only mode.
**/
getReadOnly(): bool;
getReadOnly(): boolean;
/**
* Specifies whether to use behaviors or not. ["Behaviors" in this case is the auto-pairing of special characters, like quotation marks, parenthesis, or brackets.]{: #BehaviorsDef}
* @param enabled Enables or disables behaviors
**/
setBehavioursEnabled(enabled: bool);
setBehavioursEnabled(enabled: boolean);
/**
* Returns `true` if the behaviors are currently enabled. {:BehaviorsDef}
**/
getBehavioursEnabled(): bool;
getBehavioursEnabled(): boolean;
/**
* Specifies whether to use wrapping behaviors or not, i.e. automatically wrapping the selection with characters such as brackets
* when such a character is typed in.
* @param enabled Enables or disables wrapping behaviors
**/
setWrapBehavioursEnabled(enabled: bool);
setWrapBehavioursEnabled(enabled: boolean);
/**
* Returns `true` if the wrapping behaviors are currently enabled.
@@ -1342,7 +1342,7 @@ module AceAjax {
* Indicates whether the fold widgets are shown or not.
* @param show Specifies whether the fold widgets are shown
**/
setShowFoldWidgets(show: bool);
setShowFoldWidgets(show: boolean);
/**
* Returns `true` if the fold widgets are shown.
@@ -1475,13 +1475,13 @@ module AceAjax {
* Indicates if the row is currently visible on the screen.
* @param row The row to check
**/
isRowVisible(row: number): bool;
isRowVisible(row: number): boolean;
/**
* Indicates if the entire row is currently visible on the screen.
* @param row The row to check
**/
isRowFullyVisible(row: number): bool;
isRowFullyVisible(row: number): boolean;
/**
* Selects the text from the current position of the document until where a "page down" finishes.
@@ -1525,7 +1525,7 @@ module AceAjax {
* @param animate If `true` animates scrolling
* @param callback Function to be called when the animation has finished
**/
scrollToLine(line: number, center: bool, animate: bool, callback: Function);
scrollToLine(line: number, center: boolean, animate: boolean, callback: Function);
/**
* Attempts to center the current selection on the screen.
@@ -1562,7 +1562,7 @@ module AceAjax {
* @param row The new row number
* @param column The new column number
**/
moveCursorTo(row: number, column?: number, animate?:bool);
moveCursorTo(row: number, column?: number, animate?:boolean);
/**
* Moves the cursor to the position indicated by `pos.row` and `pos.column`.
@@ -1581,7 +1581,7 @@ module AceAjax {
* @param column A column number to go to
* @param animate If `true` animates scolling
**/
gotoLine(lineNumber: number, column?: number, animate?: bool);
gotoLine(lineNumber: number, column?: number, animate?: boolean);
/**
* Moves the cursor to the specified row and column. Note that this does de-select the current selection.
@@ -1669,21 +1669,21 @@ module AceAjax {
* @param options An object defining various search properties
* @param animate If `true` animate scrolling
**/
find(needle: string, options?: any, animate?: bool);
find(needle: string, options?: any, animate?: boolean);
/**
* Performs another search for `needle` in the document. For more information on `options`, see [[Search `Search`]].
* @param options search options
* @param animate If `true` animate scrolling
**/
findNext(options?: any, animate?: bool);
findNext(options?: any, animate?: boolean);
/**
* Performs a search for `needle` backwards. For more information on `options`, see [[Search `Search`]].
* @param options search options
* @param animate If `true` animate scrolling
**/
findPrevious(options?: any, animate?: bool);
findPrevious(options?: any, animate?: boolean);
/**
* {:UndoManager.undo}
@@ -1702,7 +1702,7 @@ module AceAjax {
}
declare var Editor: {
var Editor: {
/**
* Creates a new `Editor` object.
* @param renderer Associated `VirtualRenderer` that draws everything
@@ -1761,7 +1761,7 @@ module AceAjax {
**/
cancel();
}
declare var PlaceHolder: {
var PlaceHolder: {
/**
* - @param session (Document): The document to associate with the anchor
* - @param length (Number): The starting row position
@@ -1773,7 +1773,7 @@ module AceAjax {
new (session: Document, length: number, pos: number, others: string, mainClass: string, othersClass: string): PlaceHolder;
new (session: IEditSession, length: number, pos: Position, positions: Position[]): PlaceHolder;
}
}
////////////////
/// RangeList
@@ -1817,7 +1817,7 @@ module AceAjax {
end: Position;
isEmpty(): bool;
isEmpty(): boolean;
/**
* Returns `true` if and only if the starting row and column, and ending row and column, are equivalent to those given by `range`.
@@ -1842,7 +1842,7 @@ module AceAjax {
* @param row A row to check for
* @param column A column to check for
**/
contains(row: number, column: number): bool;
contains(row: number, column: number): boolean;
/**
* Compares `this` range (A) with another range (B).
@@ -1860,27 +1860,27 @@ module AceAjax {
* Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range.
* @param range A range to compare with
**/
containsRange(range: Range): bool;
containsRange(range: Range): boolean;
/**
* Returns `true` if passed in `range` intersects with the one calling this method.
* @param range A range to compare with
**/
intersects(range: Range): bool;
intersects(range: Range): boolean;
/**
* Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`.
* @param row A row point to compare with
* @param column A column point to compare with
**/
isEnd(row: number, column: number): bool;
isEnd(row: number, column: number): boolean;
/**
* Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`.
* @param row A row point to compare with
* @param column A column point to compare with
**/
isStart(row: number, column: number): bool;
isStart(row: number, column: number): boolean;
/**
* Sets the starting row and column for the range.
@@ -1901,21 +1901,21 @@ module AceAjax {
* @param row A row point to compare with
* @param column A column point to compare with
**/
inside(row: number, column: number): bool;
inside(row: number, column: number): boolean;
/**
* Returns `true` if the `row` and `column` are within the given range's starting points.
* @param row A row point to compare with
* @param column A column point to compare with
**/
insideStart(row: number, column: number): bool;
insideStart(row: number, column: number): boolean;
/**
* Returns `true` if the `row` and `column` are within the given range's ending points.
* @param row A row point to compare with
* @param column A column point to compare with
**/
insideEnd(row: number, column: number): bool;
insideEnd(row: number, column: number): boolean;
/**
* Checks the row and column points with the row and column points of the calling range.
@@ -1962,7 +1962,7 @@ module AceAjax {
/**
* Returns `true` if the range spans across multiple lines.
**/
isMultiLine(): bool;
isMultiLine(): boolean;
/**
* Returns a duplicate of the calling range.
@@ -1995,17 +1995,17 @@ module AceAjax {
* @param endRow The ending row
* @param endColumn The ending column
**/
declare var Range: {
var Range: {
fromPoints(pos1: Position, pos2: Position): Range;
new(startRow: number, startColumn: number, endRow: number, endColumn: number): Range;
}
}
////////////////
/// RenderLoop
////////////////
export interface RenderLoop { }
declare var RenderLoop: {
var RenderLoop: {
new(): RenderLoop;
}
@@ -2047,7 +2047,7 @@ module AceAjax {
**/
setScrollTop(scrollTop: number);
}
declare var ScrollBar: {
var ScrollBar: {
/**
* Creates a new `ScrollBar`. `parent` is the owner of the scroll bar.
* @param parent A DOM element
@@ -2102,7 +2102,7 @@ module AceAjax {
**/
replace(input: string, replacement: string): string;
}
declare var Search: {
var Search: {
/**
* Creates a new `Search` object. The following search options are avaliable:
* - `needle`: The string or regular expression you're looking for
@@ -2147,17 +2147,17 @@ module AceAjax {
/**
* Returns `true` if the selection is empty.
**/
isEmpty(): bool;
isEmpty(): boolean;
/**
* Returns `true` if the selection is a multi-line.
**/
isMultiLine(): bool;
isMultiLine(): boolean;
/**
* Gets the current position of the cursor.
**/
getCursor(): number;
getCursor(): Position;
/**
* Sets the row and column position of the anchor. This function also emits the `'changeSelection'` event.
@@ -2185,7 +2185,7 @@ module AceAjax {
/**
* Returns `true` if the selection is going backwards in the document.
**/
isBackwards(): bool;
isBackwards(): boolean;
/**
* [Returns the [[Range]] for the selected text.]{: #Selection.getRange}
@@ -2207,7 +2207,7 @@ module AceAjax {
* @param range The range of text to select
* @param reverse Indicates if the range should go backwards (`true`) or not
**/
setRange(range: Range, reverse: bool);
setRange(range: Range, reverse: boolean);
/**
* Moves the selection cursor to the indicated row and column.
@@ -2361,7 +2361,7 @@ module AceAjax {
* @param column The column to move to
* @param keepDesiredColumn [If `true`, the cursor move does not respect the previous column]{: #preventUpdateBool}
**/
moveCursorTo(row: number, column: number, keepDesiredColumn?: bool);
moveCursorTo(row: number, column: number, keepDesiredColumn?: boolean);
/**
* Moves the cursor to the screen position indicated by row and column. {:preventUpdateBoolDesc}
@@ -2369,15 +2369,15 @@ module AceAjax {
* @param column The column to move to
* @param keepDesiredColumn {:preventUpdateBool}
**/
moveCursorToScreen(row: number, column: number, keepDesiredColumn: bool);
moveCursorToScreen(row: number, column: number, keepDesiredColumn: boolean);
}
declare var Selection: {
var Selection: {
/**
* Creates a new `Selection` object.
* @param session The session to use
**/
new(session: IEditSession): Selection;
}
}
////////////////
/// Split
@@ -2459,7 +2459,7 @@ module AceAjax {
**/
resize();
}
declare var Split: {
var Split: {
new(): Split;
}
@@ -2497,7 +2497,7 @@ module AceAjax {
**/
getCurrentTokenColumn(): number;
}
declare var TokenIterator: {
var TokenIterator: {
/**
* Creates a new token iterator object. The inital token index is set to the provided row and column coordinates.
* @param session The session to associate with
@@ -2522,14 +2522,14 @@ module AceAjax {
**/
getLineTokens(): any;
}
declare var Tokenizer: {
var Tokenizer: {
/**
* Constructs a new tokenizer based on the given rules and flags.
* @param rules The highlighting rules
* @param flag Any additional regular expression flags to pass (like "i" for case insensitive)
**/
new(rules: any, flag: string): Tokenizer;
}
}
//////////////////
/// UndoManager
@@ -2552,13 +2552,13 @@ module AceAjax {
* [Perform an undo operation on the document, reverting the last change.]{: #UndoManager.undo}
* @param dontSelect {:dontSelect}
**/
undo(dontSelect?: bool): Range;
undo(dontSelect?: boolean): Range;
/**
* [Perform a redo operation on the document, reimplementing the last change.]{: #UndoManager.redo}
* @param dontSelect {:dontSelect}
**/
redo(dontSelect: bool);
redo(dontSelect: boolean);
/**
* Destroys the stack of undo and redo redo operations.
@@ -2568,15 +2568,15 @@ module AceAjax {
/**
* Returns `true` if there are undo operations left to perform.
**/
hasUndo(): bool;
hasUndo(): boolean;
/**
* Returns `true` if there are redo operations left to perform.
**/
hasRedo(): bool;
hasRedo(): boolean;
}
declare var UndoManager: {
var UndoManager: {
/**
* Resets the current undo state and creates a new `UndoManager`.
**/
@@ -2621,7 +2621,7 @@ module AceAjax {
* Triggers a full update of all the layers, for all the rows.
* @param force If `true`, forces the changes through
**/
updateFull(force: bool);
updateFull(force: boolean);
/**
* Updates the font size.
@@ -2635,7 +2635,7 @@ module AceAjax {
* @param width The width of the editor in pixels
* @param height The hiehgt of the editor, in pixels
**/
onResize(force: bool, gutterWidth: number, width: number, height: number);
onResize(force: boolean, gutterWidth: number, width: number, height: number);
/**
* Adjusts the wrap limit, which is the number of characters that can fit within the width of the edit area on screen.
@@ -2646,56 +2646,56 @@ module AceAjax {
* Identifies whether you want to have an animated scroll or not.
* @param shouldAnimate Set to `true` to show animated scrolls
**/
setAnimatedScroll(shouldAnimate: bool);
setAnimatedScroll(shouldAnimate: boolean);
/**
* Returns whether an animated scroll happens or not.
**/
getAnimatedScroll(): bool;
getAnimatedScroll(): boolean;
/**
* Identifies whether you want to show invisible characters or not.
* @param showInvisibles Set to `true` to show invisibles
**/
setShowInvisibles(showInvisibles: bool);
setShowInvisibles(showInvisibles: boolean);
/**
* Returns whether invisible characters are being shown or not.
**/
getShowInvisibles(): bool;
getShowInvisibles(): boolean;
/**
* Identifies whether you want to show the print margin or not.
* @param showPrintMargin Set to `true` to show the print margin
**/
setShowPrintMargin(showPrintMargin: bool);
setShowPrintMargin(showPrintMargin: boolean);
/**
* Returns whether the print margin is being shown or not.
**/
getShowPrintMargin(): bool;
getShowPrintMargin(): boolean;
/**
* Identifies whether you want to show the print margin column or not.
* @param showPrintMargin Set to `true` to show the print margin column
**/
setPrintMarginColumn(showPrintMargin: bool);
setPrintMarginColumn(showPrintMargin: boolean);
/**
* Returns whether the print margin column is being shown or not.
**/
getPrintMarginColumn(): bool;
getPrintMarginColumn(): boolean;
/**
* Returns `true` if the gutter is being shown.
**/
getShowGutter(): bool;
getShowGutter(): boolean;
/**
* Identifies whether you want to show the gutter or not.
* @param show Set to `true` to show the gutter
**/
setShowGutter(show: bool);
setShowGutter(show: boolean);
/**
* Returns the root element containing this renderer.
@@ -2741,13 +2741,13 @@ module AceAjax {
/**
* Returns whether the horizontal scrollbar is set to be always visible.
**/
getHScrollBarAlwaysVisible(): bool;
getHScrollBarAlwaysVisible(): boolean;
/**
* Identifies whether you want to show the horizontal scrollbar or not.
* @param alwaysVisible Set to `true` to make the horizontal scroll bar visible
**/
setHScrollBarAlwaysVisible(alwaysVisible: bool);
setHScrollBarAlwaysVisible(alwaysVisible: boolean);
/**
* Schedules an update to all the front markers in the document.
@@ -2833,7 +2833,7 @@ module AceAjax {
* @param animate If `true` animates scrolling
* @param callback Function to be called after the animation has finished
**/
scrollToLine(line: number, center: bool, animate: bool, callback: Function);
scrollToLine(line: number, center: boolean, animate: boolean, callback: Function);
/**
* Scrolls the editor to the y pixel indicated.
@@ -2859,7 +2859,7 @@ module AceAjax {
* @param deltaX The x value to scroll by
* @param deltaY The y value to scroll by
**/
isScrollableBy(deltaX: number, deltaY: number): bool;
isScrollableBy(deltaX: number, deltaY: number): boolean;
/**
* Returns an object containing the `pageX` and `pageY` coordinates of the document position.
@@ -2924,7 +2924,7 @@ module AceAjax {
destroy();
}
declare var VirtualRenderer: {
var VirtualRenderer: {
/**
* Constructs a new `VirtualRenderer` within the `container` specified, applying the given `theme`.
* @param container The root element of the editor
@@ -2934,4 +2934,4 @@ module AceAjax {
}
}
declare var ace: AceAjax.Ace;
declare var ace: AceAjax.Ace;
+2 -1
View File
@@ -1,6 +1,7 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var exports = {
"test create anchor" : function() {
var doc = new AceAjax.Document("juhu");
+3 -1
View File
@@ -1,5 +1,7 @@
/// <reference path="../ace.d.ts" />
var assert: any;
function forceTokenize(session) {
for (var i = 0, l = session.getLength(); i < l; i++)
session.getTokens(i)
@@ -11,7 +13,7 @@ function testStates(session, states) {
assert.ok(l == states.length)
}
exports = {
var exports = {
"test background tokenizer update on session change": function() {
var doc = new AceAjax.EditSession([
+1
View File
@@ -1,5 +1,6 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
+2 -1
View File
@@ -1,6 +1,7 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var exports = {
"test: insert text in line": function() {
var doc = new AceAjax.Document(["12", "34"]);
+2 -1
View File
@@ -1,6 +1,7 @@
/// <reference path="../ace.d.ts" />
var lang: any;
var assert: any;
function createFoldTestSession() {
var lines = [
@@ -26,7 +27,7 @@ function assertArray(a, b) {
}
}
exports = {
var exports = {
"test: find matching opening bracket in Text mode": function() {
var session = new AceAjax.EditSession(["(()(", "())))"]);
+2 -1
View File
@@ -1,6 +1,7 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var exports = {
setUp: function(next) {
this.session1 = new AceAjax.EditSession(["abc", "def"]);
@@ -27,10 +27,13 @@ function callHighlighterUpdate(session: AceAjax.IEditSession, firstRow: number,
return rangeCount;
}
exports = {
var assert: any;
var renderer: AceAjax.VirtualRenderer;
var exports = {
setUp: function(next) {
var session = new AceAjax.EditSession(lipsum);
editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
var selection = session.getSelection();
next();
} ,
@@ -38,7 +41,7 @@ exports = {
"test: highlight selected words by default": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
assert.equal(editor.getHighlightSelectedWord(), true);
} ,
@@ -46,7 +49,7 @@ exports = {
"test: highlight a word": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 9);
selection.selectWord();
@@ -63,7 +66,7 @@ exports = {
"test: highlight a word and clear highlight": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 8);
selection.selectWord();
@@ -79,7 +82,7 @@ exports = {
"test: highlight another word": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 14);
selection.selectWord();
@@ -92,7 +95,7 @@ exports = {
"test: no selection, no highlight": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
selection.clearSelection();
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
@@ -101,7 +104,7 @@ exports = {
"test: select a word, no highlight": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 14);
selection.selectWord();
@@ -116,7 +119,7 @@ exports = {
"test: select a word with no matches": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.setHighlightSelectedWord(true);
@@ -143,7 +146,7 @@ exports = {
"test: partial word selection 1": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 14);
selection.selectWord();
@@ -157,7 +160,7 @@ exports = {
"test: partial word selection 2": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 13);
selection.selectWord();
@@ -171,7 +174,7 @@ exports = {
"test: partial word selection 3": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 14);
selection.selectWord();
@@ -186,7 +189,7 @@ exports = {
"test: select last word": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 1);
+10 -8
View File
@@ -1,6 +1,8 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var renderer: AceAjax.VirtualRenderer;
var exports = {
createEditSession: function (rows, cols) {
var line = new Array(cols + 1).join("a");
var text = new Array(rows).join(line + "\n") + line;
@@ -9,7 +11,7 @@ exports = {
"test: navigate to end of file should scroll the last line into view": function () {
var doc = this.createEditSession(200, 10);
var editor = new AceAjax.Editor(new MockRenderer(), doc);
var editor = new AceAjax.Editor(renderer, doc);
editor.navigateFileEnd();
var cursor = editor.getCursorPosition();
@@ -20,7 +22,7 @@ exports = {
"test: navigate to start of file should scroll the first row into view": function () {
var doc = this.createEditSession(200, 10);
var editor = new AceAjax.Editor(new MockRenderer(), doc);
var editor = new AceAjax.Editor(renderer, doc);
editor.moveCursorTo(editor.getLastVisibleRow() + 20);
editor.navigateFileStart();
@@ -29,7 +31,7 @@ exports = {
},
"test: goto hidden line should scroll the line into the middle of the viewport": function () {
var editor = new AceAjax.Editor(new MockRenderer(), this.createEditSession(200, 5));
var editor = new AceAjax.Editor(renderer, this.createEditSession(200, 5));
editor.navigateTo(0, 0);
editor.gotoLine(101);
@@ -63,7 +65,7 @@ exports = {
},
"test: goto visible line should only move the cursor and not scroll": function () {
var editor = new AceAjax.Editor(new MockRenderer(), this.createEditSession(200, 5));
var editor = new AceAjax.Editor(renderer, this.createEditSession(200, 5));
editor.navigateTo(0, 0);
editor.gotoLine(12);
@@ -77,7 +79,7 @@ exports = {
},
"test: navigate from the end of a long line down to a short line and back should maintain the curser column": function () {
var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["123456", "1"]));
var editor = new AceAjax.Editor(renderer, new AceAjax.EditSession(["123456", "1"]));
editor.navigateTo(0, 6);
assert.position(editor.getCursorPosition(), 0, 6);
@@ -90,7 +92,7 @@ exports = {
},
"test: reset desired column on navigate left or right": function () {
var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["123456", "12"]));
var editor = new AceAjax.Editor(renderer, new AceAjax.EditSession(["123456", "12"]));
editor.navigateTo(0, 6);
assert.position(editor.getCursorPosition(), 0, 6);
@@ -106,7 +108,7 @@ exports = {
},
"test: typing text should update the desired column": function () {
var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["1234", "1234567890"]));
var editor = new AceAjax.Editor(renderer, new AceAjax.EditSession(["1234", "1234567890"]));
editor.navigateTo(0, 3);
editor.insert("juhu");
+46 -43
View File
@@ -1,9 +1,12 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var renderer: AceAjax.VirtualRenderer;
var mode: any;
var exports = {
"test: delete line from the middle": function () {
var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.removeLines();
@@ -29,7 +32,7 @@ exports = {
"test: delete multiple selected lines": function () {
var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
@@ -41,7 +44,7 @@ exports = {
"test: delete first line": function () {
var session = new AceAjax.EditSession(["a", "b", "c"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.removeLines();
@@ -51,7 +54,7 @@ exports = {
"test: delete last should also delete the new line of the previous line": function () {
var session = new AceAjax.EditSession(["a", "b", "c", ""].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(3, 0);
@@ -66,7 +69,7 @@ exports = {
"test: indent block": function () {
var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 3);
editor.getSelection().selectDown();
@@ -84,7 +87,7 @@ exports = {
"test: indent selected lines": function () {
var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectDown();
@@ -94,8 +97,8 @@ exports = {
},
"test: no auto indent if cursor is before the {": function () {
var session = new AceAjax.EditSession("{", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession("{",mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 0);
editor.onTextInput("\n");
@@ -104,7 +107,7 @@ exports = {
"test: outdent block": function () {
var session = new AceAjax.EditSession([" a12345", " b12345", " c12345"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 5);
editor.getSelection().selectDown();
@@ -129,7 +132,7 @@ exports = {
"test: outent without a selection should update cursor": function () {
var session = new AceAjax.EditSession(" 12");
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 3);
editor.blockOutdent(" ");
@@ -139,8 +142,8 @@ exports = {
},
"test: comment lines should perserve selection": function () {
var session = new AceAjax.EditSession([" abc", "cde"].join("\n"), new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession([" abc", "cde"].join("\n"),mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 2);
editor.getSelection().selectDown();
@@ -154,8 +157,8 @@ exports = {
},
"test: uncomment lines should perserve selection": function () {
var session = new AceAjax.EditSession(["// abc", "//cde"].join("\n"), new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession(["// abc", "//cde"].join("\n"),mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
@@ -169,8 +172,8 @@ exports = {
},
"test: toggle comment lines twice should return the original text": function () {
var session = new AceAjax.EditSession([" abc", "cde", "fg"], new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession([" abc", "cde", "fg"], mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
@@ -185,8 +188,8 @@ exports = {
"test: comment lines - if the selection end is at the line start it should stay there": function () {
//select down
var session = new AceAjax.EditSession(["abc", "cde"].join("\n"), new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession(["abc", "cde"].join("\n"),mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
@@ -195,8 +198,8 @@ exports = {
assert.range(editor.getSelectionRange(), 0, 2, 1, 0);
// select up
var session = new AceAjax.EditSession(["abc", "cde"].join("\n"), new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession(["abc", "cde"].join("\n"),mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectUp();
@@ -207,7 +210,7 @@ exports = {
"test: move lines down should select moved lines": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
@@ -234,7 +237,7 @@ exports = {
"test: move lines up should select moved lines": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(2, 1);
editor.getSelection().selectDown();
@@ -254,7 +257,7 @@ exports = {
"test: move line without active selection should not move cursor relative to the moved line": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.clearSelection();
@@ -272,7 +275,7 @@ exports = {
"test: copy lines down should select lines and place cursor at the selection start": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
@@ -287,7 +290,7 @@ exports = {
"test: copy lines up should select lines and place cursor at the selection start": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
@@ -302,7 +305,7 @@ exports = {
"test: input a tab with soft tab should convert it to spaces": function () {
var session = new AceAjax.EditSession("");
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
session.setTabSize(2);
session.setUseSoftTabs(true);
@@ -317,7 +320,7 @@ exports = {
"test: input tab without soft tabs should keep the tab character": function () {
var session = new AceAjax.EditSession("");
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
session.setUseSoftTabs(false);
@@ -331,7 +334,7 @@ exports = {
session.setUndoManager(undoManager);
var initialText = session.toString();
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.removeLines();
var step1 = session.toString();
@@ -361,7 +364,7 @@ exports = {
"test: remove left should remove character left of the cursor": function () {
var session = new AceAjax.EditSession(["123", "456"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.remove("left");
assert.equal(session.toString(), "123\n56");
@@ -370,7 +373,7 @@ exports = {
"test: remove left should remove line break if cursor is at line start": function () {
var session = new AceAjax.EditSession(["123", "456"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.remove("left");
assert.equal(session.toString(), "123456");
@@ -381,7 +384,7 @@ exports = {
session.setUseSoftTabs(true);
session.setTabSize(4);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 8);
editor.remove("left");
assert.equal(session.toString(), "123\n 456");
@@ -390,7 +393,7 @@ exports = {
"test: transpose at line start should be a noop": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.transposeLetters();
@@ -400,7 +403,7 @@ exports = {
"test: transpose in line should swap the charaters before and after the cursor": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 2);
editor.transposeLetters();
@@ -410,7 +413,7 @@ exports = {
"test: transpose at line end should swap the last two characters": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 4);
editor.transposeLetters();
@@ -420,7 +423,7 @@ exports = {
"test: transpose with non empty selection should be a noop": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectRight();
editor.transposeLetters();
@@ -431,7 +434,7 @@ exports = {
"test: transpose should move the cursor behind the last swapped character": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 2);
editor.transposeLetters();
assert.position(editor.getCursorPosition(), 1, 3);
@@ -440,7 +443,7 @@ exports = {
"test: remove to line end": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 2);
editor.removeToLineEnd();
assert.equal(session.getValue(), ["123", "45", "89"].join("\n"));
@@ -449,7 +452,7 @@ exports = {
"test: remove to line end at line end should remove the new line": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 4);
editor.removeToLineEnd();
assert.position(editor.getCursorPosition(), 1, 4);
@@ -459,7 +462,7 @@ exports = {
"test: transform selection to uppercase": function () {
var session = new AceAjax.EditSession(["ajax", "dot", "org"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toUpperCase()
@@ -469,7 +472,7 @@ exports = {
"test: transform word to uppercase": function () {
var session = new AceAjax.EditSession(["ajax", "dot", "org"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.toUpperCase()
assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n"));
@@ -479,7 +482,7 @@ exports = {
"test: transform selection to lowercase": function () {
var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toLowerCase()
@@ -489,7 +492,7 @@ exports = {
"test: transform word to lowercase": function () {
var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.toLowerCase()
assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n"));
+8 -5
View File
@@ -1,5 +1,8 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var editor: any;
var renderer: any;
var exec = function (name?, times?, args?) {
do {
editor.commands.exec(name, editor, args);
@@ -9,7 +12,7 @@ var testRanges = function (str) {
assert.equal(editor.selection.getAllRanges() + "", str + "");
}
exports = {
var exports = {
name: "ACE multi_select.js",
@@ -19,7 +22,7 @@ exports = {
" wtt.w",
" wtt.w"
]);
editor = new AceAjax.Editor(new MockRenderer(), doc);
editor = new AceAjax.Editor(renderer, doc);
editor.navigateFileEnd();
exec("selectMoreBefore", 3);
@@ -45,7 +48,7 @@ exports = {
" wtt.w",
" wtt.we"
]);
editor = new AceAjax.Editor(new MockRenderer(), doc);
editor = new AceAjax.Editor(renderer, doc);
editor.selectMoreLines(1);
testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]");
@@ -67,7 +70,7 @@ exports = {
" wtt.w",
" wtt.w"
]);
editor = new AceAjax.Editor(new MockRenderer(), doc);
editor = new AceAjax.Editor(renderer, doc);
editor.selectMoreLines(1)
testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]");
@@ -87,7 +90,7 @@ exports = {
" wtt.w",
" wtt.w"
]);
editor = new AceAjax.Editor(new MockRenderer(), doc);
editor = new AceAjax.Editor(renderer, doc);
var selection = editor.selection;
+16 -13
View File
@@ -1,10 +1,13 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var renderer: AceAjax.VirtualRenderer;
var mode: any;
var exports = {
"test: simple at the end appending of text": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
var editor = new AceAjax.Editor(renderer, session);
new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
@@ -20,8 +23,8 @@ exports = {
},
"test: inserting text outside placeholder": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);\n", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);\n", mode);
var editor = new AceAjax.Editor(renderer, session);
new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
@@ -31,8 +34,8 @@ exports = {
},
"test: insertion at the beginning": function (next) {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
var editor = new AceAjax.Editor(renderer, session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
@@ -49,8 +52,8 @@ exports = {
},
"test: detaching placeholder": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
var editor = new AceAjax.Editor(renderer, session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
@@ -63,8 +66,8 @@ exports = {
},
"test: events": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
var editor = new AceAjax.Editor(renderer, session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
var entered = false;
@@ -86,9 +89,9 @@ exports = {
},
"test: cancel": function (next) {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
session.setUndoManager(new AceAjax.UndoManager());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var editor = new AceAjax.Editor(renderer, session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(0, 5);
+2 -1
View File
@@ -1,6 +1,7 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var exports = {
name: "ACE range.js",
+2 -1
View File
@@ -1,5 +1,6 @@
/// <reference path="../ace.d.ts" />
var assert: any;
function flatten(rangeList) {
var points = [];
rangeList.ranges.forEach(function (r) {
@@ -11,7 +12,7 @@ function testRangeList(rangeList, points) {
assert.equal("" + flatten(rangeList), "" + points);
}
exports = {
var exports = {
name: "ACE range_list.js",
+2 -1
View File
@@ -1,6 +1,7 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var exports = {
"test: configure the search object": function () {
var search = new AceAjax.Search();
search.set({
+2 -1
View File
@@ -1,6 +1,7 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var exports = {
createSession: function (rows, cols) {
var line = new Array(cols + 1).join("a");
var text = new Array(rows).join(line + "\n") + line;
+7 -5
View File
@@ -1,6 +1,8 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var mode: any;
var exports = {
"test: token iterator initialization in JavaScript document": function () {
var lines = [
"function foo(items) {",
@@ -9,7 +11,7 @@ exports = {
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode());
var session = new AceAjax.EditSession(lines.join("\n"),mode);
var iterator = new AceAjax.TokenIterator(session, 0, 0);
assert.equal(iterator.getCurrentToken().value, "function");
@@ -96,7 +98,7 @@ exports = {
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode());
var session = new AceAjax.EditSession(lines.join("\n"),mode);
var tokens = [];
var len = session.getLength();
@@ -118,7 +120,7 @@ exports = {
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode());
var session = new AceAjax.EditSession(lines.join("\n"),mode);
var tokens = [];
var len = session.getLength();
@@ -140,7 +142,7 @@ exports = {
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode());
var session = new AceAjax.EditSession(lines.join("\n"),mode);
var iterator = new AceAjax.TokenIterator(session, 0, 0);
+2 -1
View File
@@ -1,6 +1,7 @@
/// <reference path="../ace.d.ts" />
exports = {
var assert: any;
var exports = {
"test: screen2text the column should be rounded to the next character edge": function () {
var el = document.createElement("div");
+162 -165
View File
File diff suppressed because it is too large Load Diff
+249
View File
@@ -0,0 +1,249 @@
/// <reference path="amplifyjs.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
// Copied examples directly from AmplifyJs site
// Subscribe and publish with no data
amplify.subscribe("nodataexample", function () {
alert("nodataexample topic published!");
});
// Subscribe and publish with data
amplify.publish("nodataexample");
amplify.subscribe("dataexample", function (data) {
alert(data.foo); // bar
});
amplify.publish("dataexample", { foo: "bar" });
amplify.subscribe("dataexample2", function (param1, param2) {
alert(param1 + param2); // barbaz
});
//...
amplify.publish("dataexample2", "bar", "baz");
// Subscribe and publish with context and data
amplify.subscribe("datacontextexample", $("p:first"), function (data) {
this.text(data.exampleText); // first p element would have "foo bar baz" as text
});
amplify.publish("datacontextexample", { exampleText: "foo bar baz" });
// Subscribe to a topic with high priority
amplify.subscribe("priorityexample", function (data) {
alert(data.foo);
});
amplify.subscribe("priorityexample", function (data) {
if (data.foo === "oops") {
return false;
}
}, 1);
// Store data with amplify storage picking the default storage technology:
amplify.publish("priorityexample", { foo: "bar" });
amplify.publish("priorityexample", { foo: "oops" });
amplify.store("storeExample1", { foo: "bar" });
amplify.store("storeExample2", "baz");
// retrieve the data later via the key
var myStoredValue = amplify.store("storeExample1"),
myStoredValue2 = amplify.store("storeExample2"),
myStoredValues = amplify.store();
myStoredValue.foo; // bar
myStoredValue2; // baz
myStoredValues.storeExample1.foo; // bar
myStoredValues.storeExample2; // baz
// Store data explicitly with session storage
amplify.store.sessionStorage("explicitExample", { foo2: "baz" });
// retrieve the data later via the key
var myStoredValue2 = amplify.store.sessionStorage("explicitExample");
myStoredValue2.foo2; // baz
// REQUEST
// Set up and use a request utilizing Ajax
amplify.request.define("ajaxExample1", "ajax", {
url: "/myApiUrl",
dataType: "json",
type: "GET"
});
// later in code
amplify.request("ajaxExample1", function (data) {
data.foo; // bar
});
// Set up and use a request utilizing Ajax and Caching
amplify.request.define("ajaxExample2", "ajax", {
url: "/myApiUrl",
dataType: "json",
type: "GET",
cache: "persist"
});
// later in code
amplify.request("ajaxExample2", function (data) {
data.foo; // bar
});
// a second call will result in pulling from the cache
amplify.request("ajaxExample2", function (data) {
data.baz; // qux
})
// Set up and use a RESTful request utilizing Ajax
amplify.request.define("ajaxRESTFulExample", "ajax", {
url: "/myRestFulApi/{type}/{id}",
type: "GET"
})
// later in code
amplify.request("ajaxRESTFulExample",
{
type: "foo",
id: "bar"
},
function (data) {
// /myRESTFulApi/foo/bar was the URL used
data.foo; // bar
}
);
// POST data with Ajax
amplify.request.define("ajaxPostExample", "ajax", {
url: "/myRestFulApi",
type: "POST"
})
// later in code
amplify.request("ajaxPostExample",
{
type: "foo",
id: "bar"
},
function (data) {
data.foo; // bar
}
);
// Using data maps
// When searching Twitter, the key for the search phrase is q.If we want a more descriptive name, such as term, we can use a data map:
amplify.request.define("twitter-search", "ajax", {
url: "http://search.twitter.com/search.json",
dataType: "jsonp",
dataMap: {
term: "q"
}
});
amplify.request("twitter-search", { term: "amplifyjs" } );
// Similarly, we can create a request that searches for mentions, by accepting a username:
amplify.request.define("twitter-mentions", "ajax", {
url: "http://search.twitter.com/search.json",
dataType: "jsonp",
dataMap: function (data) {
return {
q: "@" + data.user
};
}
});
amplify.request("twitter-mentions", { user: "amplifyjs" });
// Setting up and using decoders
//Example:
amplify.request.decoders.appEnvelope =
function (data, status, xhr, success, error) {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
error(data.message, data.status);
} else {
error(data.message, "fatal");
}
};
amplify.request.define("decoderExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",
decoder: "appEnvelope"
});
amplify.request({
resourceId: "decoderExample",
success: function (data) {
data.foo; // bar
},
error: function (message, level) {
alert("always handle errors with alerts.");
}
});
// POST with caching and single - use decoder
// Example:
amplify.request.define("decoderSingleExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",
decoder: function (data, status, xhr, success, error) {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
error(data.message, data.status);
} else {
error(data.message, "fatal");
}
}
});
amplify.request({
resourceId: "decoderSingleExample",
success: function (data) {
data.foo; // bar
},
error: function (message, level) {
alert("always handle errors with alerts.");
}
});
// Handling Status
// Status in Success and Error Callbacks
// amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition.
amplify.request.define("statusExample1", "ajax", {
//...
});
amplify.request({
resourceId: "statusExample1",
success: function (data, status) {
},
error: function (data, status) {
}
});
+159
View File
@@ -0,0 +1,159 @@
// Type definitions for AmplifyJs 1.1.0
// Project: http://amplifyjs.com/
// Definitions by: Jonas Eriksson <https://github.com/joeriks/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface amplifyRequestSettings {
resourceId: string;
data?: any;
success?: Function;
error?: Function;
}
interface amplifyRequest {
/***
* Request a resource.
* resourceId: Identifier string for the resource.
* data: A set of key/value pairs of data to be sent to the resource.
* callback: A function to invoke if the resource is retrieved successfully.
*/
(resourceId: string, hash?: any, callback?: Function): void;
/***
* Request a resource.
* settings: A set of key/value pairs of settings for the request.
* resourceId: Identifier string for the resource.
* data (optional): Data associated with the request.
* success (optional): Function to invoke on success.
* error (optional): Function to invoke on error.
*/
(settings: amplifyRequestSettings);
/***
* Define a resource.
* resourceId: Identifier string for the resource.
* requestType: The type of data retrieval method from the server. See the request types sections for more information.
* settings: A set of key/value pairs that relate to the server communication technology. The following settings are available:
* Any settings found in jQuery.ajax().
* 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 a custom request.
* resourceId: Identifier string for the resource.
* resource: Function to handle requests. Receives a hash with the following properties:
* resourceId: Identifier string for the resource.
* data: Data provided by the user.
* success: Callback to invoke on success.
* error: Callback to invoke on error.
*/
define(resourceId: string, resource: Function): void;
decoders: any;
cache: any;
}
interface amplifySubscribe {
/***
* Subscribe to a message.
* topic: Name of the message to subscribe to.
* callback: Function to invoke when the message is published.
*/
(topic: string, callback: Function): void;
/***
* Subscribe to a message.
* topic: Name of the message to subscribe to.
* context: What this will be when the callback is invoked.
* callback: Function to invoke when the message is published.
* [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10.
*/
(topic: string, context: any, callback: Function, priority?: number): void;
/***
* Subscribe to a message.
* topic: Name of the message to subscribe to.
* callback: Function to invoke when the message is published.
* [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10.
*/
(topic: string, callback: Function, priority?: number): void;
}
interface amplifyStorageTypeStore {
/***
* Stores a value for a given key using the default storage type.
*
* key: Identifier for the value being stored.
* value: The value to store. The value can be anything that can be serialized as JSON.
* [options]: A set of key/value pairs that relate to settings for storing the value.
*/
(key: string, value: any, options?: any): void;
/***
* Gets a stored value based on the key.
*/
(key: string): any;
/***
* Gets a hash of all stored values.
*/
(): any;
}
interface amplifyStore extends amplifyStorageTypeStore{
/***
* IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+
*/
localStorage: amplifyStorageTypeStore;
/***
* IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+
*/
sessionStorage: amplifyStorageTypeStore;
/***
* Firefox 2+
*/
globalStorage: amplifyStorageTypeStore;
/***
* IE 5 - 7
*/
userData: amplifyStorageTypeStore;
/***
* An in-memory store is provided as a fallback if none of the other storage types are available.
*/
memory: amplifyStorageTypeStore;
}
interface amplifyStatic {
subscribe: amplifySubscribe;
/***
* Remove a subscription.
* topic: The topic being unsubscribed from.
* callback: The callback that was originally subscribed.
*/
unsubscribe(topic: string, callback: Function): void;
/***
* Publish a message.
* topic: The name of the message to publish.
* Any additional parameters will be passed to the subscriptions.
* amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked.
*/
publish(topic: string, ...args: any[]): boolean;
store: amplifyStore;
request: amplifyRequest;
}
declare var amplify: amplifyStatic;
+2 -2
View File
@@ -96,7 +96,7 @@ Since you are augmenting the $scope object, you should let the compiler know wha
$scope.title = 'Yabadabadu';
}
## Exemples
## Examples
### Working with $resource
@@ -151,4 +151,4 @@ Since you are augmenting the $scope object, you should let the compiler know wha
article.$save();
article.$publish();
}
}
+1 -1
View File
@@ -9,7 +9,7 @@
///////////////////////////////////////////////////////////////////////////////
// ngCookies module (angular-cookies.js)
///////////////////////////////////////////////////////////////////////////////
module ng.cookies {
declare module ng.cookies {
///////////////////////////////////////////////////////////////////////////
// CookieService
+11 -21
View File
@@ -15,7 +15,7 @@ declare var inject: (...fns: Function[]) => any;
///////////////////////////////////////////////////////////////////////////////
// ngMock module (angular-mocks.js)
///////////////////////////////////////////////////////////////////////////////
module ng {
declare module ng {
///////////////////////////////////////////////////////////////////////////
// AngularStatic
@@ -82,14 +82,10 @@ module ng {
verifyNoOutstandingExpectation(): void;
verifyNoOutstandingRequest(): void;
expect(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler;
expect(method: string, url: string, data?: RegExp, headers?: any): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler;
expect(method: RegExp, url: string, data?: string, headers?: any): mock.IRequestHandler;
expect(method: RegExp, url: RegExp, data?: string, headers?: any): mock.IRequestHandler;
expect(method: RegExp, url: string, data?: RegExp, headers?: any): mock.IRequestHandler;
expect(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler;
expect(method: string, url: string, data?: any, headers?: any): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: any, headers?: any): mock.IRequestHandler;
expect(method: RegExp, url: string, data?: any, headers?: any): mock.IRequestHandler;
expect(method: RegExp, url: RegExp, data?: any, headers?: any): mock.IRequestHandler;
when(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler;
when(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler;
@@ -108,18 +104,12 @@ module ng {
expectHEAD(url: RegExp, headers?: any): mock.IRequestHandler;
expectJSONP(url: string): mock.IRequestHandler;
expectJSONP(url: RegExp): mock.IRequestHandler;
expectPATCH(url: string, data?: string, headers?: any): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: string, headers?: any): mock.IRequestHandler;
expectPATCH(url: string, data?: RegExp, headers?: any): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler;
expectPOST(url: string, data?: string, headers?: any): mock.IRequestHandler;
expectPOST(url: RegExp, data?: string, headers?: any): mock.IRequestHandler;
expectPOST(url: string, data?: RegExp, headers?: any): mock.IRequestHandler;
expectPOST(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler;
expectPUT(url: string, data?: string, headers?: any): mock.IRequestHandler;
expectPUT(url: RegExp, data?: string, headers?: any): mock.IRequestHandler;
expectPUT(url: string, data?: RegExp, headers?: any): mock.IRequestHandler;
expectPUT(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler;
expectPATCH(url: string, data?: any, headers?: any): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: any, headers?: any): mock.IRequestHandler;
expectPOST(url: string, data?: any, headers?: any): mock.IRequestHandler;
expectPOST(url: RegExp, data?: any, headers?: any): mock.IRequestHandler;
expectPUT(url: string, data?: any, headers?: any): mock.IRequestHandler;
expectPUT(url: RegExp, data?: any, headers?: any): mock.IRequestHandler;
whenDELETE(url: string, headers?: any): mock.IRequestHandler;
whenDELETE(url: RegExp, headers?: any): mock.IRequestHandler;
+3 -3
View File
@@ -9,7 +9,7 @@
///////////////////////////////////////////////////////////////////////////////
// ngResource module (angular-resource.js)
///////////////////////////////////////////////////////////////////////////////
module ng.resource {
declare module ng.resource {
///////////////////////////////////////////////////////////////////////////
// ResourceService
@@ -28,7 +28,7 @@ module ng.resource {
// Just a reference to facilitate describing new actions
interface IActionDescriptor {
method: string;
isArray?: bool;
isArray?: boolean;
params?: any;
headers?: any;
}
@@ -73,7 +73,7 @@ module ng.resource {
}
/** extensions to base ng based on using angular-resource */
module ng {
declare module ng {
interface IModule {
/** creating a resource service factory */
+1 -1
View File
@@ -9,7 +9,7 @@
///////////////////////////////////////////////////////////////////////////////
// ngSanitize module (angular-sanitize.js)
///////////////////////////////////////////////////////////////////////////////
module ng.sanitize {
declare module ng.sanitize {
///////////////////////////////////////////////////////////////////////////
// SanitizeService
+140 -39
View File
@@ -1,54 +1,155 @@
// Type definitions for Angular Scenario Testing
// Project: [http://angularjs.org]
// Definitions by: [RomanoLindano]
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module scenario
{
interface ISleep
{
(timeSeconds: number): void;
declare module angularScenario {
export interface AngularModel {
scenario: any;
}
interface IBrowser
{
(): IBrowser;
navigateTo(url: string);
navigateTo(url: string, delegate: (url: string) => string);
reload();
window(): IWindowApi;
location(): ILocationApi;
export interface RunFunction {
(functionToRun: any): any;
}
export interface RunFunctionWithDescription {
(description: string, functionToRun: any): any;
}
interface IWindowApi
{
href(): void;
path(): void;
search(): void;
hash(): void;
export interface PauseFunction {
(): any;
}
interface ILocationApi
{
url(): void;
path(): void;
search(): void;
hash(): void;
export interface SleepFunction {
(seconds: number): any;
}
interface IElement
{
(): IElement;
(selector: string): IElement;
count(): number;
click(): void;
export interface Future {
}
export interface testWindow {
href(): Future;
path(): Future;
search(): Future;
hash(): Future;
}
export interface testLocation {
url(): Future;
path(): Future;
search(): Future;
hash(): Future;
}
export interface Browser {
navigateTo(url: string): void;
navigateTo(urlDescription: string, urlFunction: () => string): void;
reload(): void;
window(): testWindow;
location(): testLocation;
}
export interface Matchers {
toEqual(value: any): void;
toBe(value: any): void;
toBeDefined(): void;
toBeTruthy(): void;
toBeFalsy(): void;
toMatch(regularExpression: any): void;
toBeNull(): void;
toContain(value: any): void;
toBeLessThan(value: any): void;
toBeGreaterThan(value: any): void;
}
export interface CustomMatchers extends Matchers{
}
export interface Expect extends CustomMatchers {
not(): angularScenario.CustomMatchers;
}
export interface UsingFunction {
(selector: string, selectorDescription?: string): void;
}
export interface BindingFunction {
(bracketBindingExpression: string): Future;
}
export interface Input {
enter(value: any);
check(): any;
select(radioButtonValue: any): any;
val(): Future;
}
export interface Repeater {
count(): Future;
row(index: number): Future;
column(ngBindingExpression: string): Future;
}
export interface Select {
option(value: any): any;
option(...listOfValues: any[]): any;
}
export interface Element {
count(): Future;
click(): any;
query(callback: (selectedDOMElements: any[], callbackWhenDone: (objNull: any, futureValue: any) => any) =>any): any;
val(): Future;
text(): Future;
html(): Future;
height(): Future;
innerHeight(): Future;
outerHeight(): Future;
width(): Future;
innerWidth(): Future;
outerWidth(): Future;
position(): Future;
scrollLeft(): Future;
scrollTop(): Future;
offset(): Future;
val(value: any): void;
text(value: any): void;
html(value: any): void;
height(value: any): void;
innerHeight(value: any): void;
outerHeight(value: any): void;
width(value: any): void;
innerWidth(value: any): void;
outerWidth(value: any): void;
position(value: any): void;
scrollLeft(value: any): void;
scrollTop(value: any): void;
offset(value: any): void;
attr(key: any): Future;
prop(key: any): Future;
css(key: any): Future;
attr(key: any, value: any): void;
prop(key: any, value: any): void;
css(key: any, value: any): void;
}
}
declare var browser: scenario.IBrowser;
declare var element: scenario.IElement;
declare var sleep: scenario.ISleep;
declare var describe: angularScenario.RunFunctionWithDescription;
declare var xdescribe: angularScenario.RunFunctionWithDescription;
declare var beforeEach: angularScenario.RunFunction;
declare var afterEach: angularScenario.RunFunction;
declare var it: angularScenario.RunFunctionWithDescription;
declare var xit: angularScenario.RunFunctionWithDescription;
declare var pause: angularScenario.PauseFunction;
declare var sleep: angularScenario.SleepFunction;
declare function browser(): angularScenario.Browser;
declare function expect(expectation: angularScenario.Future): angularScenario.Expect;
declare var using: angularScenario.UsingFunction;
declare var binding: angularScenario.BindingFunction;
declare function input(ngModelBinding: string): angularScenario.Input;
declare function repeater(selector: string, repeaterDescription?: string): angularScenario.Repeater;
declare function select(ngModelBinding: string): angularScenario.Select;
declare function element(selector: string, elementDescription?: string): angularScenario.Element;
declare var angular: angularScenario.AngularModel;
+164 -118
View File
@@ -9,161 +9,171 @@ https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.
*/
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 = [];
.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 = [];
/**
* 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) {
buffer.push({
config: config,
deferred: deferred
});
}
/**
* 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) {
buffer.push({
config: config,
deferred: deferred
});
}
this.$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) {
$http = $http || $injector.get('$http');
$http(config).then(function (response) {
deferred.resolve(response);
});
}
function retryAll() {
for (var i = 0; i < buffer.length; ++i) {
retry(buffer[i].config, buffer[i].deferred);
}
buffer = [];
}
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');
$http(config).then(function (response) {
deferred.resolve(response);
});
}
function retryAll() {
for (var i = 0; i < buffer.length; ++i) {
retry(buffer[i].config, buffer[i].deferred);
}
buffer = [];
}
return {
loginConfirmed: function () {
$rootScope.$broadcast('event:auth-loginConfirmed');
retryAll();
}
}
loginConfirmed: function () {
$rootScope.$broadcast('event:auth-loginConfirmed');
retryAll();
}
}
}]
})
/**
* $http interceptor.
* On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'.
*/
.config(['$httpProvider', 'authServiceProvider', <any>function ($httpProvider: ng.IHttpProvider, authServiceProvider) {
/**
* $http interceptor.
* On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'.
*/
.config(['$httpProvider', 'authServiceProvider', <any>function ($httpProvider: ng.IHttpProvider, authServiceProvider) {
var interceptor = ['$rootScope', '$q', <any>function ($rootScope: ng.IScope, $q: ng.IQService) {
function success(response: ng.IHttpPromiseCallbackArg) {
return response;
}
var interceptor = ['$rootScope', '$q', <any>function ($rootScope: ng.IScope, $q: ng.IQService) {
function success(response: ng.IHttpPromiseCallbackArg<any>) {
return response;
}
function error(response: ng.IHttpPromiseCallbackArg) {
if (response.status === 401) {
var deferred = $q.defer();
authServiceProvider.pushToBuffer(response.config, deferred);
$rootScope.$broadcast('event:auth-loginRequired');
return deferred.promise;
}
// otherwise
return $q.reject(response);
}
function error(response: ng.IHttpPromiseCallbackArg<any>) {
if (response.status === 401) {
var deferred = $q.defer();
authServiceProvider.pushToBuffer(response.config, deferred);
$rootScope.$broadcast('event:auth-loginRequired');
return deferred.promise;
}
// otherwise
return $q.reject(response);
}
return function (promise: ng.IHttpPromise) {
return promise.then(success, error);
}
return function (promise: ng.IHttpPromise<any>) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
}]);
$httpProvider.responseInterceptors.push(interceptor);
}]);
module HttpAndRegularPromiseTests {
interface Person {
firstName: string;
lastName: string;
}
interface Person {
firstName: string;
lastName: string;
}
interface ExpectedResponse extends Person {}
interface ExpectedResponse extends Person { }
interface SomeControllerScope extends ng.IScope {
person: Person;
theAnswer: number;
letters: string[];
}
interface SomeControllerScope extends ng.IScope {
person: Person;
theAnswer: number;
letters: string[];
}
interface OurApiPromiseCallbackArg extends ng.IHttpPromiseCallbackArg {
data?: ExpectedResponse;
}
var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => {
$http.get("http://somewhere/some/resource")
.success((data: ExpectedResponse) => {
$scope.person = data;
});
var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => {
$http.get("http://somewhere/some/resource")
.success((data: ExpectedResponse) => {
$scope.person = data;
});
$http.get("http://somewhere/some/resource")
.then((response: ng.IHttpPromiseCallbackArg<ExpectedResponse>) => {
// typing lost, so something like
// var i: number = response.data
// would type check
$scope.person = response.data;
});
$http.get("http://somewhere/some/resource")
.then((response: ng.IHttpPromiseCallbackArg) => {
// typing lost, so something like
// var i: number = response.data
// would type check
$scope.person = response.data;
});
$http.get("http://somewhere/some/resource")
.then((response: ng.IHttpPromiseCallbackArg<ExpectedResponse>) => {
// typing lost, so something like
// var i: number = response.data
// would NOT type check
$scope.person = response.data;
});
$http.get("http://somewhere/some/resource")
.then((response: OurApiPromiseCallbackArg) => {
// typing lost, so something like
// var i: number = response.data
// would NOT type check
$scope.person = response.data;
});
var aPromise: ng.IPromise<Person> = $q.when({ firstName: "Jack", lastName: "Sparrow" });
aPromise.then((person: Person) => {
$scope.person = person;
});
var aPromise: ng.IPromise = $q.when({firstName: "Jack", lastName: "Sparrow"});
aPromise.then((person: Person) => {
$scope.person = person;
});
var bPromise: ng.IPromise<number> = $q.when(42);
bPromise.then((answer: number) => {
$scope.theAnswer = answer;
});
var bPromise: ng.IPromise = $q.when(42);
bPromise.then((answer: number) => {
$scope.theAnswer = answer;
});
var cPromise: ng.IPromise<string[]> = $q.when(["a", "b", "c"]);
cPromise.then((letters: string[]) => {
$scope.letters = letters;
});
}
var cPromise: ng.IPromise = $q.when(["a", "b", "c"]);
cPromise.then((letters: string[]) => {
$scope.letters = letters;
});
}
// Test that we can pass around a type-checked success/error Promise Callback
var anotherController: Function = ($scope: SomeControllerScope, $http:
ng.IHttpService, $q: ng.IQService) => {
var buildFooData: Function = () => 42;
var doFoo: Function = (callback: ng.IHttpPromiseCallback<ExpectedResponse>) => {
$http.get('/foo', buildFooData())
.success(callback);
}
doFoo((data) => console.log(data));
}
}
// Test for AngularJS Syntac
// Test for AngularJS Syntax
module My.Namespace {
export var x; // need to export something for module to kick in
}
// IModule Registering Test
var mod = angular.module('tests',[]);
mod.controller('name', function($scope : ng.IScope) {})
mod.controller('name', ['$scope', <any>function($scope : ng.IScope) {}])
var mod = angular.module('tests', []);
mod.controller('name', function ($scope: ng.IScope) { })
mod.controller('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.controller(My.Namespace);
mod.directive('name', function($scope : ng.IScope) {})
mod.directive('name', ['$scope', <any>function($scope : ng.IScope) {}])
mod.directive('name', <any>function ($scope: ng.IScope) { })
mod.directive('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.directive(My.Namespace);
mod.factory('name', function($scope : ng.IScope) {})
mod.factory('name', ['$scope', <any>function($scope : ng.IScope) {}])
mod.factory('name', function ($scope: ng.IScope) { })
mod.factory('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.factory(My.Namespace);
mod.filter('name', function($scope : ng.IScope) {})
mod.filter('name', ['$scope', <any>function($scope : ng.IScope) {}])
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', ['$scope', <any>function($scope : ng.IScope) {}])
mod.provider('name', function ($scope: ng.IScope) { })
mod.provider('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.provider(My.Namespace);
mod.service('name', function($scope : ng.IScope) {})
mod.service('name', ['$scope', <any>function($scope : ng.IScope) {}])
mod.service('name', function ($scope: ng.IScope) { })
mod.service('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.service(My.Namespace);
mod.constant('name', 23);
mod.constant('name', "23");
@@ -171,3 +181,39 @@ mod.constant(My.Namespace);
mod.value('name', 23);
mod.value('name', "23");
mod.value(My.Namespace);
// Promise signature tests
var foo: ng.IPromise<number>;
foo.then((x) => {
// x is inferred to be a number
return "asdf";
}).then((x) => {
// x is inferred to be string
x.length;
return 123;
}).then((x) => {
// x is infered to be a number
x.toFixed();
return;
}).then((x) => {
// x is infered to be void
// Typescript will prevent you to actually use x as a local variable
// Try object:
return { a: 123 };
}).then((x) => {
// Object is inferred here
x.a = 123;
//Try a promise
var y: ng.IPromise<number>;
return y;
}).then((x) => {
// x is infered to be a number, which is the resolved value of a promise
x.toFixed();
});
// angular.element() tests
var element = angular.element("div.myApp");
var scope: ng.IScope = element.scope();
Vendored Regular → Executable
+135 -67
View File
@@ -8,6 +8,11 @@
declare var angular: ng.IAngularStatic;
// Support for painless dependency injection
interface Function {
$inject:string[];
}
///////////////////////////////////////////////////////////////////////////////
// ng module (angular.js)
///////////////////////////////////////////////////////////////////////////////
@@ -27,23 +32,24 @@ declare module ng {
bootstrap(element: string, modules?: any[]): auto.IInjectorService;
bootstrap(element: JQuery, modules?: any[]): auto.IInjectorService;
bootstrap(element: Element, modules?: any[]): auto.IInjectorService;
bootstrap(element: Document, modules?: any[]): auto.IInjectorService;
copy(source: any, destination?: any): any;
element: JQueryStatic;
equals(value1: any, value2: any): bool;
element: IAugmentedJQueryStatic;
equals(value1: any, value2: any): boolean;
extend(destination: any, ...sources: any[]): any;
forEach(obj: any, iterator: (value, key) => any, context?: any): any;
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;
isArray(value: any): bool;
isDate(value: any): bool;
isDefined(value: any): bool;
isElement(value: any): bool;
isFunction(value: any): bool;
isNumber(value: any): bool;
isObject(value: any): bool;
isString(value: any): bool;
isUndefined(value: any): bool;
isArray(value: any): boolean;
isDate(value: any): boolean;
isDefined(value: any): boolean;
isElement(value: any): boolean;
isFunction(value: any): boolean;
isNumber(value: any): boolean;
isObject(value: any): boolean;
isString(value: any): boolean;
isUndefined(value: any): boolean;
lowercase(str: string): string;
/** construct your angular application
official docs: Interface for configuring angular modules.
@@ -54,9 +60,9 @@ declare module ng {
name: string,
/** name of modules yours depends on */
requires?: string[],
configFunction?: Function): IModule;
configFunction?: any): IModule;
noop(...args: any[]): void;
toJson(obj: any, pretty?: bool): string;
toJson(obj: any, pretty?: boolean): string;
uppercase(str: string): string;
version: {
full: string;
@@ -119,6 +125,7 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
interface IAttributes {
$set(name: string, value: any): void;
$observe(name: string, fn:(value?:any)=>any):void;
$attr: any;
}
@@ -127,11 +134,13 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.directive:form.FormController
///////////////////////////////////////////////////////////////////////////
interface IFormController {
$pristine: bool;
$dirty: bool;
$valid: bool;
$invalid: bool;
$pristine: boolean;
$dirty: boolean;
$valid: boolean;
$invalid: boolean;
$error: any;
$setDirty(): void;
$setPristine(): void;
}
///////////////////////////////////////////////////////////////////////////
@@ -140,7 +149,7 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
interface INgModelController {
$render(): void;
$setValidity(validationErrorKey: string, isValid: bool): void;
$setValidity(validationErrorKey: string, isValid: boolean): void;
$setViewValue(value: string): void;
// XXX Not sure about the types here. Documentation states it's a string, but
@@ -154,10 +163,10 @@ declare module ng {
$parsers: IModelParser[];
$formatters: IModelFormatter[];
$error: any;
$pristine: bool;
$dirty: bool;
$valid: bool;
$invalid: bool;
$pristine: boolean;
$dirty: boolean;
$valid: boolean;
$invalid: boolean;
}
interface IModelParser {
@@ -173,7 +182,7 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.$rootScope.Scope
///////////////////////////////////////////////////////////////////////////
interface IScope {
// Documentation says exp is optional, but actual implementaton counts on it
$apply(): any;
$apply(exp: string): any;
$apply(exp: (scope: IScope) => any): any;
@@ -191,16 +200,25 @@ declare module ng {
$evalAsync(expression: (scope: IScope) => any): void;
// Defaults to false by the implementation checking strategy
$new(isolate?: bool): IScope;
$new(isolate?: boolean): IScope;
$on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function;
$watch(watchExpression: string, listener?: string, objectEquality?: bool): Function;
$watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function;
$watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: bool): Function;
$watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function;
$watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function;
$watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function;
$watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): Function;
$watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function;
$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;
$parent: IScope;
$id: number;
// Hidden members
$$isolateBindings: any;
$$phase: any;
}
interface IAngularEvent {
@@ -208,7 +226,7 @@ declare module ng {
currentScope: IScope;
name: string;
preventDefault: Function;
defaultPrevented: bool;
defaultPrevented: boolean;
// Available only events that were $emit-ted
stopPropagation?: Function;
@@ -231,8 +249,8 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.$timeout
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
(func: Function, delay?: number, invokeApply?: bool): IPromise;
cancel(promise: IPromise): bool;
(func: Function, delay?: number, invokeApply?: boolean): IPromise<any>;
cancel(promise: IPromise<any>): boolean;
}
///////////////////////////////////////////////////////////////////////////
@@ -302,6 +320,7 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.$log
///////////////////////////////////////////////////////////////////////////
interface ILogService {
debug: ILogCall;
error: ILogCall;
info: ILogCall;
log: ILogCall;
@@ -347,7 +366,7 @@ declare module ng {
port(): number;
protocol(): string;
replace(): ILocationService;
search(): string;
search(): any;
search(parametersMap: any): ILocationService;
search(parameter: string, parameterValue: any): ILocationService;
url(): string;
@@ -357,12 +376,12 @@ declare module ng {
interface ILocationProvider extends IServiceProvider {
hashPrefix(): string;
hashPrefix(prefix: string): ILocationProvider;
html5Mode(): bool;
html5Mode(): boolean;
// Documentation states that parameter is string, but
// implementation tests it as boolean, which makes more sense
// since this is a toggler
html5Mode(active: bool): ILocationProvider;
html5Mode(active: boolean): ILocationProvider;
}
///////////////////////////////////////////////////////////////////////////
@@ -390,20 +409,22 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.$q
///////////////////////////////////////////////////////////////////////////
interface IQService {
all(promises: IPromise[]): IPromise;
defer(): IDeferred;
reject(reason?: any): IPromise;
when(value: any): IPromise;
all(promises: IPromise<any>[]): IPromise<any[]>;
defer<T>(): IDeferred<T>;
reject(reason?: any): IPromise<void>;
when<T>(value: T): IPromise<T>;
}
interface IPromise {
then(successCallback: (promiseValue: any) => any, errorCallback?: (reason: any) => any): IPromise;
interface IPromise<T> {
then<TResult>(successCallback: (promiseValue: T) => IHttpPromise<TResult>, errorCallback?: (reason: any) => any): IPromise<TResult>;
then<TResult>(successCallback: (promiseValue: T) => IPromise<TResult>, errorCallback?: (reason: any) => any): IPromise<TResult>;
then<TResult>(successCallback: (promiseValue: T) => TResult, errorCallback?: (reason: any) => TResult): IPromise<TResult>;
}
interface IDeferred {
resolve(value?: any): void;
interface IDeferred<T> {
resolve(value?: T): void;
reject(reason?: any): void;
promise: IPromise;
promise: IPromise<T>;
}
///////////////////////////////////////////////////////////////////////////
@@ -483,7 +504,7 @@ declare module ng {
(controllerName: string, locals?: any): any;
}
interface IControlerProvider extends IServiceProvider {
interface IControllerProvider extends IServiceProvider {
register(name: string, controllerConstructor: Function): void;
register(name: string, dependencyAnnotadedConstructor: any[]): void;
}
@@ -494,21 +515,21 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
interface IHttpService {
// At least moethod and url must be provided...
(config: IRequestConfig): IHttpPromise;
get (url: string, RequestConfig?: any): IHttpPromise;
delete (url: string, RequestConfig?: any): IHttpPromise;
head(url: string, RequestConfig?: any): IHttpPromise;
jsonp(url: string, RequestConfig?: any): IHttpPromise;
post(url: string, data: any, RequestConfig?: any): IHttpPromise;
put(url: string, data: any, RequestConfig?: any): IHttpPromise;
(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>;
defaults: IRequestConfig;
// For debugging, BUT it is documented as public, so...
pendingRequests: any[];
}
// This is just for hinting.
// Some opetions might not be available depending on the request.
// 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;
@@ -520,7 +541,7 @@ declare module ng {
cache?: any;
timeout?: number;
withCredentials?: bool;
withCredentials?: boolean;
// These accept multiple types, so let's defile them as any
data?: any;
@@ -528,21 +549,27 @@ declare module ng {
transformResponse?: any;
}
interface IHttpPromiseCallbackArg {
data?: any;
interface IHttpPromiseCallback<T> {
(data: T, status: number, headers: (headerName: string) => string, config: IRequestConfig): void;
}
interface IHttpPromiseCallbackArg<T> {
data?: T;
status?: number;
headers?: (headerName: string) => string;
config?: IRequestConfig;
}
interface IHttpPromise extends IPromise {
success(callback: (data: any, status: number, headers: (headerName: string) => string, config: IRequestConfig) => any): IHttpPromise;
error(callback: (data: any, status: number, headers: (headerName: string) => string, config: IRequestConfig) => any): IHttpPromise;
then(successCallback: (response: IHttpPromiseCallbackArg) => any, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise;
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>;
}
interface IHttpProvider extends IServiceProvider {
defaults: IRequestConfig;
interceptors: any[];
responseInterceptors: any[];
}
@@ -553,7 +580,7 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
// XXX Perhaps define callback signature in the future
(method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: bool): void;
(method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean): void;
}
///////////////////////////////////////////////////////////////////////////
@@ -562,7 +589,7 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.$interpolateProvider
///////////////////////////////////////////////////////////////////////////
interface IInterpolateService {
(text: string, mustHaveExpression?: bool): IInterpolationFunction;
(text: string, mustHaveExpression?: boolean): IInterpolationFunction;
endSymbol(): string;
startSymbol(): string;
}
@@ -613,11 +640,12 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.$routeProvider#when for options explanations
interface IRoute {
controller?: any;
name?: string;
template?: string;
templateUrl?: string;
templateUrl?: any;
resolve?: any;
redirectTo?: any;
reloadOnSearch?: bool;
reloadOnSearch?: boolean;
}
// see http://docs.angularjs.org/api/ng.$route#current
@@ -626,6 +654,8 @@ declare module ng {
$scope: IScope;
$template: string;
};
params: any;
}
interface IRouteProvider extends IServiceProvider {
@@ -643,12 +673,49 @@ declare module ng {
priority?: number;
template?: string;
templateUrl?: string;
replace?: bool;
transclude?: bool;
replace?: boolean;
transclude?: any;
restrict?: string;
scope?: any;
link?: Function;
compile?: Function;
controller?: Function;
}
///////////////////////////////////////////////////////////////////////////
// angular.element
// when calling angular.element, angular returns a jQuery object,
// augmented with additional methods like e.g. scope.
// see: http://docs.angularjs.org/api/angular.element
///////////////////////////////////////////////////////////////////////////
interface IAugmentedJQueryStatic extends JQueryStatic {
(selector: string, context?: any): IAugmentedJQuery;
(element: Element): IAugmentedJQuery;
(object: {}): IAugmentedJQuery;
(elementArray: Element[]): IAugmentedJQuery;
(object: JQuery): IAugmentedJQuery;
(func: Function): IAugmentedJQuery;
(array: any[]): IAugmentedJQuery;
(): IAugmentedJQuery;
}
interface IAugmentedJQuery extends JQuery {
// TODO: events, how to define?
//$destroy
find(selector: string): IAugmentedJQuery;
find(element: any): IAugmentedJQuery;
find(obj: JQuery): IAugmentedJQuery;
controller(name: string): any;
injector(): any;
scope(): IScope;
inheritedData(key: string, value: any): JQuery;
inheritedData(obj: { [key: string]: any; }): JQuery;
inheritedData(key?: string): any;
}
@@ -680,6 +747,7 @@ declare module ng {
constant(name: string, value: any): void;
decorator(name: string, decorator: Function): void;
decorator(name: string, decoratorInline: any[]): void;
factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider;
provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider;
provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider;
+630
View File
@@ -0,0 +1,630 @@
/// <reference path="appframework.d.ts" />
af(($: appFrameworkStatic) => {});
((): appFrameworkCollection => {
return $('div'); //=> all DIV elements on the page
})();
((): appFrameworkCollection => {
return $("<p />", {}); // context
})();
((): appFrameworkCollection => {
return $($('')); // appFrameworkCollection
})();
((): appFrameworkCollection => {
return $(document.createElement('div')); // HTMLElement
})();
((): appFrameworkCollection => {
return $({}); // Object(any)
})();
((): boolean => {
return $.is$($(''));
})();
((): boolean[] => {
return $.map([], (item: any, index: number): boolean => {
return true;
});
})();
$.each([], (index: number, item: any) => { });
$.each({}, (key: string, value: any) => { });
((): Object => {
return $.extend({ one: 'patridge' }, { two: 'turtle doves' });
})();
((): boolean => {
return $.isArray({});
})();
((): boolean => {
return $.isFunction({});
})();
((): boolean => {
return $.isObject({});
})();
((): Object => {
return $.fn;
})();
((): Object => {
return $.ajaxSettings;
})();
$.jsonP({});
((): XMLHttpRequest => {
return $.ajax({});
})();
((): XMLHttpRequest => {
return $.get('', (data: any, status?: string, xhr?: XMLHttpRequest) => {});
})();
((): XMLHttpRequest => {
return $.post('', (data: any, status?: string, xhr?: XMLHttpRequest) => {});
})();
((): XMLHttpRequest => {
return $.post('', {}, (data: any, status?: string, xhr?: XMLHttpRequest) => {});
})();
((): XMLHttpRequest => {
return $.getJSON('', (data: any, status?: string, xhr?: XMLHttpRequest) => {});
})();
((): XMLHttpRequest => {
return $.getJSON('', {}, (data: any, status?: string, xhr?: XMLHttpRequest) => {});
})();
((): string => {
return $.param({});
})();
((): string => {
return $.param({}, '');
})();
((): Object => {
return $.parseJSON('');
})();
((): Object => {
return $.parseXML('');
})();
((): string => {
return $.uuid();
})();
((): Object => {
return $.getCssMatrix(document.createElement('div'));
})();
((): Object => {
return $.getCssMatrix($(''));
})();
((): appFrameworkCollection => {
return $.create('');
})();
((): appFrameworkCollection => {
return $.create('', {});
})();
((): appFrameworkCollection => {
return $.query('');
})();
((): appFrameworkCollection => {
return $.query('', {});
})();
((): Object => {
return $.Event('', {});
})();
((): void => {
return $.bind({}, '', () => {});
})();
((): void => {
return $.trigger({}, '');
})();
((): void => {
return $.trigger({}, '', []);
})();
((): void => {
return $.unbind({}, '', () => {});
})();
((): void => {
return $.proxy(() => {}, {});
})();
((): void => {
return $.cleanUpContent(document.createElement('div'), false, false);
})();
((): void => {
return $.asap(() => {});
})();
((): void => {
return $.asap(() => {}, {});
})();
((): void => {
return $.asap(() => {}, {}, []);
})();
((): void => {
return $.parseJS('');
})();
((): void => {
return $.parseJS(document.createElement('div'));
})();
$.os.webkit;
$.os.android;
$.os.androidICS;
$.os.ipad;
$.os.iphone;
$.os.ios7;
$.os.webos;
$.os.touchpad;
$.os.ios;
$.os.playbook;
$.os.blackberry;
$.os.blackberry10;
$.os.chrome;
$.os.opera;
$.os.fennec;
$.os.ie;
$.os.ieTouch;
$.os.supportsTouch;
$.feat.nativeTouchScroll;
$.feat.cssPrefix;
$.feat.cssTransformStart;
$.feat.cssTransformEnd;
((): appFrameworkCollection => {
return $('').reduce((hoge) => { return hoge; });
})();
((): number => {
return $('').push($(''));
})();
((): number => {
return $('').indexOf($(''));
})();
((): appFrameworkCollection[] => {
return $('').concat($(''));
})();
((): appFrameworkCollection[] => {
return $('').slice(0);
})();
((): number => {
return $('').length;
})();
((): appFrameworkCollection => {
return $('').map(() => {});
})();
((): appFrameworkCollection => {
return $('').each(() => {});
})();
((): void => {
return $('').forEach(() => {});
})();
((): appFrameworkStatic => {
return $('').ready(() => {});
})();
((): appFrameworkCollection => {
return $('').find('');
})();
((): string => {
return $('').html();
})();
((): appFrameworkCollection => {
return $('').html('');
})();
((): appFrameworkCollection => {
return $('').html('', false);
})();
((): string => {
return $('').text();
})();
((): appFrameworkCollection => {
return $('').text('');
})();
(() => {
return $('').css('');
})();
((): appFrameworkCollection => {
return $('').css('', '');
})();
((): appFrameworkCollection => {
return $('').css({});
})();
((): appFrameworkCollection => {
return $('').vendorCss('');
})();
((): appFrameworkCollection => {
return $('').computedStyle('');
})();
((): appFrameworkCollection => {
return $('').empty();
})();
((): appFrameworkCollection => {
return $('').hide();
})();
((): appFrameworkCollection => {
return $('').show();
})();
((): appFrameworkCollection => {
return $('').toggle();
})();
((): string => {
return $('').val();
})();
((): appFrameworkCollection => {
return $('').val('');
})();
((): string => {
return $('').attr('');
})();
((): appFrameworkCollection => {
return $('').attr({});
})();
((): appFrameworkCollection => {
return $('').attr('', '');
})();
((): appFrameworkCollection => {
return $('').attr('', {});
})();
((): appFrameworkCollection => {
return $('').removeAttr('');
})();
((): string => {
return $('').prop('');
})();
((): appFrameworkCollection => {
return $('').prop({});
})();
((): appFrameworkCollection => {
return $('').prop('', '');
})();
((): appFrameworkCollection => {
return $('').prop('', {});
})();
((): appFrameworkCollection => {
return $('').removeProp('');
})();
((): appFrameworkCollection => {
return $('').remove();
})();
((): appFrameworkCollection => {
return $('').remove('');
})();
((): appFrameworkCollection => {
return $('').remove(document.createElement('div'));
})();
((): appFrameworkCollection => {
return $('').remove($(''));
})();
((): appFrameworkCollection => {
return $('').addClass('');
})();
((): appFrameworkCollection => {
return $('').removeClass('');
})();
((): appFrameworkCollection => {
return $('').toggleClass('');
})();
((): appFrameworkCollection => {
return $('').replaceClass('', '');
})();
((): boolean => {
return $('').hasClass('', document.createElement('div'));
})();
((): appFrameworkCollection => {
return $('').append('');
})();
((): appFrameworkCollection => {
return $('').appendTo('');
})();
((): appFrameworkCollection => {
return $('').prependTo('');
})();
((): appFrameworkCollection => {
return $('').prepend('');
})();
((): appFrameworkCollection => {
return $('').insertBefore('');
})();
((): void => {
return $('').insertAfter('');
})();
((): HTMLElement[] => {
return $('').get();
})();
((): HTMLElement => {
return $('').get(0);
})();
((): {
left: number;
top: number;
right: number;
bottom: number;
width: number;
height: number;
} => {
return $('').offset();
})();
((): string => {
return $('').height();
})();
((): string => {
return $('').width();
})();
((): appFrameworkCollection => {
return $('').parent();
})();
((): appFrameworkCollection => {
return $('').parents();
})();
((): appFrameworkCollection => {
return $('').children();
})();
((): appFrameworkCollection => {
return $('').siblings();
})();
((): appFrameworkCollection => {
return $('').closest();
})();
((): appFrameworkCollection => {
return $('').filter();
})();
((): appFrameworkCollection => {
return $('').not();
})();
((): any => {
return $('').data('');
})();
((): appFrameworkCollection => {
return $('').data('', '');
})();
((): appFrameworkCollection => {
return $('').data('', {});
})();
((): appFrameworkCollection => {
return $('').end();
})();
((): appFrameworkCollection => {
return $('').clone();
})();
((): number => {
return $('').size();
})();
((): string => {
return $('').serialize();
})();
((): appFrameworkCollection => {
return $('').eq(0);
})();
((): number => {
return $('').index();
})();
((): number => {
return $('').index('');
})();
((): number => {
return $('').is('');
})();
((): appFrameworkCollection => {
return $('').bind({});
})();
((): appFrameworkCollection => {
return $('').bind('', () => {});
})();
((): appFrameworkCollection => {
return $('').unbind({});
})();
((): appFrameworkCollection => {
return $('').unbind();
})();
((): appFrameworkCollection => {
return $('').unbind('', () => {});
})();
((): appFrameworkCollection => {
return $('').one({});
})();
((): appFrameworkCollection => {
return $('').one('', () => {});
})();
((): appFrameworkCollection => {
return $('').delegate('', {});
})();
((): appFrameworkCollection => {
return $('').delegate('', '', () => {});
})();
((): appFrameworkCollection => {
return $('').undelegate('', {});
})();
((): appFrameworkCollection => {
return $('').undelegate('', '', () => {});
})();
((): appFrameworkCollection => {
return $('').on({});
})();
((): appFrameworkCollection => {
return $('').on('', () => {});
})();
((): appFrameworkCollection => {
return $('').on('', '', () => {});
})();
((): appFrameworkCollection => {
return $('').off({});
})();
((): appFrameworkCollection => {
return $('').off('', () => {});
})();
((): appFrameworkCollection => {
return $('').off('', '', () => {});
})();
((): appFrameworkCollection => {
return $('').trigger('');
})();
((): appFrameworkCollection => {
return $('').trigger({});
})();
((): appFrameworkCollection => {
return $('').click();
})();
((): appFrameworkCollection => {
return $('').click(() => {});
})();
((): appFrameworkCollection => {
return $('').keydown();
})();
((): appFrameworkCollection => {
return $('').keydown(() => {});
})();
((): appFrameworkCollection => {
return $('').keyup();
})();
((): appFrameworkCollection => {
return $('').keyup(() => {});
})();
((): appFrameworkCollection => {
return $('').keypress();
})();
((): appFrameworkCollection => {
return $('').keypress(() => {});
})();
((): appFrameworkCollection => {
return $('').submit();
})();
((): appFrameworkCollection => {
return $('').submit(() => {});
})();
((): appFrameworkCollection => {
return $('').load();
})();
((): appFrameworkCollection => {
return $('').load(() => {});
})();
((): appFrameworkCollection => {
return $('').resize();
})();
((): appFrameworkCollection => {
return $('').resize(() => {});
})();
((): appFrameworkCollection => {
return $('').change();
})();
((): appFrameworkCollection => {
return $('').change(() => {});
})();
((): appFrameworkCollection => {
return $('').select();
})();
((): appFrameworkCollection => {
return $('').select(() => {});
})();
((): appFrameworkCollection => {
return $('').error();
})();
((): appFrameworkCollection => {
return $('').error(() => {});
})();
((): appFrameworkCollection => {
return $('').focus();
})();
((): appFrameworkCollection => {
return $('').focus(() => {});
})();
((): appFrameworkCollection => {
return $('').blur();
})();
((): appFrameworkCollection => {
return $('').blur(() => {});
})();
+1318
View File
File diff suppressed because it is too large Load Diff
+6 -6
View File
@@ -20,13 +20,13 @@ declare module ArbiterDef {
/**
* A subscriber can be set to execute asynchronously, even if the message wasn't published as async.
*/
async?: bool;
async?: boolean;
/**
* If your subscriber is not interested in any past messages that may have been
* persisted, you can force them to be ignored.
*/
persist?: bool;
persist?: boolean;
}
export interface PublishOptions {
@@ -35,19 +35,19 @@ declare module ArbiterDef {
* receiving the message. By passing cancelable:false in the options, the publisher
* can prevent canceling.
*/
cancelable?: bool;
cancelable?: boolean;
/**
* If the publishers wants subscribers to be notified even if they subscribe later,
* setting the persist flag will do that.
*/
persist?: bool;
persist?: boolean;
/**
* If you wish to notify the subscribers but return from the publish() call before
* the subscriber functions execute, use asynchronous mode
*/
async?: bool;
async?: boolean;
}
export interface ArbiterStatic {
@@ -67,7 +67,7 @@ declare module ArbiterDef {
* @param msg Message may be in any format, but may not contain [ ,*]. A structure like a/b/c is recommended by convention, to allow messages to be categorized.
* @param data Pass data to subscribers that contains details about the message.
*/
publish(msg: string, data?: any, options?: PublishOptions): bool;
publish(msg: string, data?: any, options?: PublishOptions): boolean;
/**
+3 -3
View File
@@ -18,10 +18,10 @@ async.series([
function () { }
]);
var data;
function asyncProcess() { }
var data = [];
function asyncProcess(item, callback) { }
async.map(data, asyncProcess, function (err, results) {
alert(results);
console.log(results);
});
var openFiles = ['file1', 'file2'];
+58 -50
View File
@@ -1,67 +1,71 @@
// Type definitions for Async 0.1
// Type definitions for Async 0.1.23
// Project: https://github.com/caolan/async
// 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): any; }
interface AsyncTimesCallback<T> { (n: number, callback: AsyncMultipleResultsCallback<T>): void; }
interface AsyncIterator<T> { (item: T, callback: AsyncMultipleResultsCallback<T>): void; }
interface AsyncMemoIterator<T> { (memo: T, item: T, callback: AsyncSingleResultCallback<T>): void; }
interface AsyncWorker<T> { (task: T, callback: Function): void; }
interface AsyncCallback { (err: string, results: any): any; }
interface AsyncIterator { (item, callback: AsyncCallback): void; }
interface AsyncMemoIterator { (memo: any, item: any, callback: AsyncCallback): void; }
interface AsyncWorker { (task: any, callback: Function): void; }
interface AsyncQueue {
interface AsyncQueue<T> {
length(): number;
concurrency: number;
push(task: any, callback: AsyncCallback): void;
saturated: AsyncCallback;
empty: AsyncCallback;
drain: AsyncCallback;
push(task: T, callback: AsyncMultipleResultsCallback<T>): void;
saturated: AsyncMultipleResultsCallback<T>;
empty: AsyncMultipleResultsCallback<T>;
drain: AsyncMultipleResultsCallback<T>;
}
interface Async {
// Collections
forEach(arr: any[], iterator: AsyncIterator, callback: AsyncCallback): void;
forEachSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback): void;
forEachLimit(arr: any[], limit: number, iterator: AsyncIterator, callback: AsyncCallback): void;
map(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
mapSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
filter(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
select(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
filterSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
selectSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
reject(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
rejectSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
reduce(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback);
inject(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback);
foldl(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback);
reduceRight(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback);
foldr(arr: any[], memo: any, iterator: AsyncMemoIterator, callback: AsyncCallback);
detect(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
detectSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
sortBy(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
some(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
any(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
every(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
all(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
concat(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
concatSeries(arr: any[], iterator: AsyncIterator, callback: AsyncCallback);
forEach<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>): void;
forEachSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>): void;
forEachLimit<T>(arr: T[], limit: number, iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>): void;
map<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
mapSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
filter<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
select<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
filterSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
selectSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
reject<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
rejectSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
reduce<T>(arr: T[], memo: T, iterator: AsyncMemoIterator<T>, callback: AsyncSingleResultCallback<T>);
inject<T>(arr: T[], memo: T, iterator: AsyncMemoIterator<T>, callback: AsyncSingleResultCallback<T>);
foldl<T>(arr: T[], memo: T, iterator: AsyncMemoIterator<T>, callback: AsyncSingleResultCallback<T>);
reduceRight<T>(arr: T[], memo: T, iterator: AsyncMemoIterator<T>, callback: AsyncSingleResultCallback<T>);
foldr<T, U>(arr: T[], memo: T, iterator: AsyncMemoIterator<T>, callback: AsyncSingleResultCallback<T>);
detect<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
detectSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
sortBy<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
some<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
any<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
every<T>(arr: T[], iterator: AsyncIterator<T>, callback: (result: boolean) => any);
all<T>(arr: T[], iterator: AsyncIterator<T>, callback: (result: boolean) => any);
concat<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
concatSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: AsyncMultipleResultsCallback<T>);
// Control Flow
series(tasks: any[], callback?: AsyncCallback): void;
series(tasks: any, callback?: AsyncCallback): void;
parallel(tasks: any[], callback?: AsyncCallback): void;
parallel(tasks: any, callback?: AsyncCallback): void;
whilst(test: Function, fn: Function, callback: AsyncCallback): void;
until(test: Function, fn: Function, callback: AsyncCallback): void;
waterfall(tasks: any[], callback?: AsyncCallback): void;
waterfall(tasks: any, callback?: AsyncCallback): void;
queue(worker: AsyncWorker, concurrency: number): AsyncQueue;
//auto(tasks: any[], callback?: AsyncCallback): void;
auto(tasks: any, callback?: AsyncCallback): void;
iterator(tasks): Function;
series<T>(tasks: T[], callback?: AsyncMultipleResultsCallback<T>): void;
series<T>(tasks: T, callback?: AsyncMultipleResultsCallback<T>): void;
parallel<T>(tasks: T[], callback?: AsyncMultipleResultsCallback<T>): void;
parallel<T>(tasks: T, callback?: AsyncMultipleResultsCallback<T>): void;
whilst(test: Function, fn: Function, callback: Function): void;
until(test: Function, fn: Function, callback: Function): void;
waterfall<T>(tasks: T[], callback?: AsyncMultipleResultsCallback<T>): void;
waterfall<T>(tasks: T, callback?: AsyncMultipleResultsCallback<T>): void;
queue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncQueue<T>;
// auto(tasks: any[], callback?: AsyncMultipleResultsCallback<T>): void;
auto(tasks: any, callback?: AsyncMultipleResultsCallback<any>): void;
iterator(tasks: Function[]): Function;
apply(fn: Function, ...arguments: any[]): void;
nextTick(callback: AsyncCallback): void;
nextTick<T>(callback: Function): void;
times<T> (n: number, callback: AsyncTimesCallback<T>): void;
timesSeries<T> (n: number, callback: AsyncTimesCallback<T>): void;
// Utils
memoize(fn: Function, hasher?: Function): Function;
@@ -71,4 +75,8 @@ interface Async {
noConflict(): Async;
}
declare var async: Async;
declare var async: Async;
declare module "async" {
export = async;
}
+3
View File
@@ -0,0 +1,3 @@
import async = require("async");
async.map(["a", "b", "c"], (item, cb) => cb(null, [item.toUpperCase()]), (err, results) => { });
@@ -17,7 +17,7 @@ if (client.currentUser === null) {
//define an interface that map to server side Table data
interface TodoItem { id?: number; text?: string; complete?: bool; }
interface TodoItem { id?: number; text?: string; complete?: boolean; }
var data: TodoItem[];
var tableTodoItems = client.getTable('todoitem');
@@ -32,8 +32,8 @@ tableTodoItems.read()
//define simple handler used in callback calls for insert/update and delete
function handlerInsUpd(e, i) => { if (!e) data.push(<TodoItem> i); };
function handlerDelErr(e) => { if (e) alert("ERROR: " + e); }
function handlerInsUpd(e, i) { if (!e) data.push(<TodoItem> i); };
function handlerDelErr(e) { if (e) alert("ERROR: " + e); }
//insert one data passing info in POST + custom data in QueryString + simple callback handler
@@ -3,7 +3,7 @@
// Definitions by: Morosinotto Daniele <https://github.com/dmorosinotto/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
module Microsoft.WindowsAzure {
declare module Microsoft.WindowsAzure {
// MobileServiceClient object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554219.aspx
interface MobileServiceClient {
@@ -75,7 +75,7 @@ module Microsoft.WindowsAzure {
select(...propNameSelected: string[]): IQuery;
select(funcProjectionFromThis: () => any): IQuery;
where(mapObjFilterCriteria: any): IQuery;
where(funcPredicateOnThis: (...qParams: any[]) => bool, ...qValues: any[]): IQuery;
where(funcPredicateOnThis: (...qParams: any[]) => boolean, ...qValues: any[]): IQuery;
skip(n: number): IQuery;
take(n: number): IQuery;
includeTotalCount(): IQuery;
+4 -4
View File
@@ -28,7 +28,7 @@ declare module Backbone {
getRelations():Relation[];
fetchRelated(key:string, options?:any, update?:bool):any;
fetchRelated(key:string, options?:any, update?:boolean):any;
toJSON():any;
@@ -54,7 +54,7 @@ declare module Backbone {
reverseRelation:any;
related:any;
checkPreconditions():bool;
checkPreconditions():boolean;
setRelated(related:Model):void;
@@ -135,9 +135,9 @@ declare module Backbone {
processOrphanRelations():void;
retroFitRelation(relation:RelationalModel, create:bool):Collection;
retroFitRelation(relation:RelationalModel, create:boolean):Collection;
getCollection(type:RelationalModel, create:bool):Collection;
getCollection(type:RelationalModel, create:boolean):Collection;
getObjectByName(name:string):any;
-2
View File
@@ -1,8 +1,6 @@
/// <reference path="backbone.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
declare var _, $;
function test_events() {
var object = new Backbone.Events();
+128 -83
View File
@@ -1,6 +1,7 @@
// Type definitions for Backbone 0.9.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: https://github.com/borisyankov/DefinitelyTyped
@@ -8,75 +9,69 @@
declare module Backbone {
export interface AddOptions extends Silenceable {
interface AddOptions extends Silenceable {
at: number;
}
export interface HistoryOptions extends Silenceable {
pushState?: bool;
interface HistoryOptions extends Silenceable {
pushState?: boolean;
root?: string;
}
export interface NavigateOptions {
trigger: bool;
interface NavigateOptions {
trigger: boolean;
}
export interface RouterOptions {
interface RouterOptions {
routes: any;
}
export interface Silenceable {
silent?: bool;
interface Silenceable {
silent?: boolean;
}
interface Validable {
validate?: bool;
validate?: boolean;
}
interface Waitable {
wait?: bool;
wait?: boolean;
}
interface Parseable {
parse?: any;
}
export interface PersistenceOptions {
interface PersistenceOptions {
url?: string;
beforeSend?: (jqxhr: JQueryXHR) => void;
success?: (modelOrCollection?: any, response?: any, options?: any) => void;
error?: (modelOrCollection?: any, jqxhr?: JQueryXHR, options?: any) => void;
}
export interface ModelSetOptions extends Silenceable extends Validable {
interface ModelSetOptions extends Silenceable, Validable {
}
export interface ModelFetchOptions extends PersistenceOptions extends ModelSetOptions extends Parseable {
interface ModelFetchOptions extends PersistenceOptions, ModelSetOptions, Parseable {
}
export interface ModelSaveOptions extends Silenceable extends Waitable extends Validable extends Parseable extends PersistenceOptions {
patch?: bool;
interface ModelSaveOptions extends Silenceable, Waitable, Validable, Parseable, PersistenceOptions {
patch?: boolean;
}
export interface ModelDestroyOptions extends Waitable extends PersistenceOptions {
interface ModelDestroyOptions extends Waitable, PersistenceOptions {
}
export interface CollectionFetchOptions extends PersistenceOptions extends Parseable {
reset?: bool;
interface CollectionFetchOptions extends PersistenceOptions, Parseable {
reset?: boolean;
}
interface on { (eventName: string, callback: (...args: any[]) => void, context?: any): any; }
interface off { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; }
interface trigger { (eventName: string, ...args: any[]): any; }
interface bind { (eventName: string, callback: (...args: any[]) => void, context?: any): any; }
interface unbind { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; }
declare class Events {
on(eventName: string, callback: (...args:any[]) => void, context?: any): any;
off(eventName?: string, callback?: (...args:any[]) => void, context?: any): any;
class Events {
on(eventName: any, callback?: (...args: any[]) => void , context?: any): any;
off(eventName?: string, callback?: (...args: any[]) => void , context?: any): any;
trigger(eventName: string, ...args: any[]): any;
bind(eventName: string, callback: (...args:any[]) => void, context?: any): any;
unbind(eventName?: string, callback?: (...args:any[]) => void, context?: any): any;
bind(eventName: string, callback: (...args: any[]) => void , context?: any): any;
unbind(eventName?: string, callback?: (...args: any[]) => void , context?: any): any;
once(events: string, callback: (...args: any[]) => void , context?: any): any;
listenTo(object: any, events: string, callback: (...args: any[]) => void ): any;
@@ -84,15 +79,18 @@ declare module Backbone {
stopListening(object?: any, events?: string, callback?: (...args: any[]) => void ): any;
}
export class ModelBase extends Events {
class ModelBase extends Events {
url: any;
parse(response, options?: any);
toJSON(options?: any): any;
sync(...arg: any[]): JQueryXHR;
}
interface OptionalDefaults {
defaults?(): any;
}
export 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
@@ -102,9 +100,9 @@ declare module Backbone {
id: any;
idAttribute: string;
validationError: any;
urlRoot(): string;
urlRoot: any;
constructor (attributes?: any, options?: any);
constructor(attributes?: any, options?: any);
initialize(attributes?: any);
fetch(options?: ModelFetchOptions): JQueryXHR;
@@ -117,21 +115,33 @@ declare module Backbone {
changedAttributes(attributes?: any): any[];
clear(options?: Silenceable);
clone(): Model;
defaults(): any;
destroy(options?: ModelDestroyOptions);
escape(attribute: string);
has(attribute: string): bool;
hasChanged(attribute?: string): bool;
isNew(): bool;
isValid(): bool;
has(attribute: string): boolean;
hasChanged(attribute?: string): boolean;
isNew(): boolean;
isValid(): boolean;
previous(attribute: string): any;
previousAttributes(): any[];
save(attributes?: any, options?: ModelSaveOptions);
unset(attribute: string, options?: Silenceable);
validate(attributes: any, options?: any): any;
_validate(attrs: any, options: any): boolean;
// mixins from underscore
keys(): string[];
values(): any[];
pairs(): any[];
invert(): any;
pick(keys: string[]): any;
pick(...keys: string[]): any;
omit(keys: string[]): any;
omit(...keys: string[]): any;
}
export class Collection extends ModelBase {
class Collection extends ModelBase {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
@@ -140,13 +150,12 @@ declare module Backbone {
collection: Model;
length: number;
constructor (models?: any, options?: any);
constructor(models?: any, options?: any);
fetch(options?: CollectionFetchOptions): JQueryXHR;
comparator(element: Model): number;
comparator(element: Model): string;
comparator(compare: Model, to?: Model): number;
comparator(element: Model): any;
comparator(compare: Model, to?: Model): any;
add(model: Model, options?: AddOptions);
add(models: Model[], options?: AddOptions);
@@ -164,34 +173,40 @@ declare module Backbone {
unshift(model: Model, options?: AddOptions);
where(properies: any): Model[];
all(iterator: (element: Model, index: number) => bool, context?: any): bool;
any(iterator: (element: Model, index: number) => bool, context?: any): bool;
_prepareModel(attrs?: any, options?: any): any;
_removeReference(model: Model): void;
_onModelEvent(event: string, model: Model, collection: Collection, 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[];
chain(): any;
compact(): Model[];
contains(value: any): bool;
contains(value: any): boolean;
countBy(iterator: (element: Model, index: number) => any): any[];
countBy(attribute: string): any[];
detect(iterator: (item: any) => bool, context?: any): any; // ???
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);
every(iterator: (element: Model, index: number) => bool, context?: any): bool;
filter(iterator: (element: Model, index: number) => bool, context?: any): Model[];
find(iterator: (element: Model, index: number) => bool, context?: any): Model;
each(iterator: (element: Model, index: number, list?: any) => void , context?: 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?: bool): 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);
include(value: any): bool;
indexOf(element: Model, isSorted?: bool): number;
forEach(iterator: (element: Model, index: number, list?: any) => void , context?: any);
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[];
isEmpty(object: any): bool;
isEmpty(object: any): boolean;
invoke(methodName: string, arguments?: any[]);
last(): Model;
last(n: number): Model[];
@@ -204,49 +219,66 @@ declare module Backbone {
select(iterator: any, context?: any): any[];
size(): number;
shuffle(): any[];
some(iterator: (element: Model, index: number) => bool, context?: any): bool;
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;
range(stop: number, step?: number);
range(start: number, stop: number, step?: number);
reduceRight(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any[];
reject(iterator: (element: Model, index: number) => bool, context?: any): Model[];
reject(iterator: (element: Model, index: number) => boolean, context?: any): Model[];
rest(): Model;
rest(n: number): Model[];
tail(): Model;
tail(n: number): Model[];
toArray(): any[];
union(...model: Model[]): Model[];
uniq(isSorted?: bool, iterator?: (element: Model, index: number) => bool): Model[];
uniq(isSorted?: boolean, iterator?: (element: Model, index: number) => boolean): Model[];
without(...values: any[]): Model[];
zip(...model: Model[]): Model[];
}
export class Router extends Events {
interface OptionalRoutes {
routes?(): any;
}
class Router extends Events implements OptionalRoutes {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
routes: any;
constructor (options?: RouterOptions);
initialize (options?: RouterOptions);
route(route: string, name: string, callback?: (...parameter: any[]) => void);
constructor(options?: RouterOptions);
initialize(options?: RouterOptions);
route(route: string, name: string, callback?: (...parameter: any[]) => void );
navigate(fragment: string, options?: NavigateOptions);
navigate(fragment: string, trigger?: bool);
navigate(fragment: string, trigger?: boolean);
_bindRoutes(): void;
_routeToRegExp(route: string): RegExp;
_extractParameters(route: RegExp, fragment: string): string[];
}
export var history: History;
export class History {
var history: History;
class History extends Events {
handlers: any[];
interval: number;
start(options?: HistoryOptions);
navigate(fragment: string, options: any);
pushSate();
getFragment(fragment?: string, forcePushState?: bool): string;
getHash(window?: Window): string;
started: bool;
getFragment(fragment?: string, forcePushState?: boolean): string;
stop(): void;
route(route: string, callback: (...args: any[]) => void );
checkUrl(e?: any): void;
loadUrl(fragmentOverride: string): boolean;
navigate(fragment: string, options?: any);
started: boolean;
_updateHash(location: Location, fragment: string, replace: boolean);
}
export interface ViewOptions {
interface ViewOptions {
model?: Backbone.Model;
collection?: Backbone.Collection;
el?: any;
@@ -256,22 +288,27 @@ declare module Backbone {
attributes?: any[];
}
export class View extends Events {
interface OptionalEvents {
events?(): any;
}
class View extends Events implements OptionalEvents {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
constructor (options?: ViewOptions);
constructor(options?: ViewOptions);
$(selector: string): JQuery;
model: Model;
collection: Collection;
template: (data?: any) => string;
make(tagName: string, attrs?, opts?): View;
setElement(element: HTMLElement, delegate?: bool);
setElement(element: HTMLElement, delegate?: boolean);
setElement(element: JQuery, delegate?: boolean);
id: string;
cid: string;
className: string;
tagName: string;
events: any;
options: any;
el: any;
$el: JQuery;
@@ -281,17 +318,25 @@ declare module Backbone {
render(): View;
remove(): View;
make(tagName, attributes?, content?);
//delegateEvents: any;
delegateEvents(events?: any): any;
undelegateEvents();
_ensureElement(): void;
}
// SYNC
function sync(method, model, options?: JQueryAjaxSettings);
var emulateHTTP: bool;
var emulateJSONBackbone: bool;
var emulateHTTP: boolean;
var emulateJSONBackbone: boolean;
// Utility
function noConflict(): Backbone;
// 0.9 cannot return modules anymore, and "typeof <Module>" is not compiling for some reason
// returning "any" until this is fixed
//function noConflict(): typeof Backbone;
function noConflict(): any;
function setDomLibrary(jQueryNew);
}
+78
View File
@@ -0,0 +1,78 @@
/// <reference path="backgrid.d.ts" />
/// <reference path="../backbone/backbone.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
/*
Uses getters and setters and requires ES >= 5
$ tsc --target ES5 backgrid-tests.ts
*/
class TestModel extends Backbone.Model {
get Id(): number { return this.get('id'); }
set Id(value: number) { this.set('id', value); }
get FirstName(): string { return this.get('FirstName'); }
set FirstName(value: string) { this.set('FirstName', value); }
set LastName(value: string) { this.set('LastName', value); }
get LastName(): string { return this.get('LastName'); }
set EMail(value: string) { this.set('EMail', value); }
get EMail(): string { return this.get('EMail'); }
}
class TestCollection extends Backbone.Collection {
constructor(models?: any, options?: any) {
this.model = TestModel;
super(models, options);
}
initialize() {
this.on("change", this.modelChanged, this)
}
modelChanged(model: Backbone.Model, val: any, options: any){
model.save();
}
}
class TestView extends Backbone.View {
gridView: Backgrid.Grid;
testCollection: TestCollection;
constructor(viewOptions?: Backbone.ViewOptions) {
this.testCollection = new TestCollection();
this.gridView = new Backgrid.Grid({
columns: [new Backgrid.Column({name: "FirstName", cell: "string", label: "First Name"}),
new Backgrid.Column({name: "LastName", cell: "string", label: "Last Name"}),
new Backgrid.Column({name: "EMail", cell: "string", label: "E-Mail"})],
collection:this.testCollection,
});
super(viewOptions);
}
initialize() {
}
render() {
this.$el.empty();
this.$el.append(this.gridView.render().$el);
//this.testCollection.fetch();
return this;
}
}
function test_grid() {
var view = new TestView();
view.render();
}
+1
View File
@@ -0,0 +1 @@
--target ES5
+85
View File
@@ -0,0 +1,85 @@
// Type definitions for Backgrid 0.2.6
// Project: http://backgridjs.com/
// Definitions by: Jeremy Lujan <https://github.com/jlujan/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../backbone/backbone.d.ts" />
declare module Backgrid {
interface GridOptions {
columns: Column[];
collection: Backbone.Collection;
header: Header;
body: Body;
row: Row;
footer: Footer;
}
class Header extends Backbone.View {
}
class Footer extends Backbone.View {
}
class Row extends Backbone.View {
}
class Command {
cancel();
moveDown();
moveLeft();
moveRight();
moveUp();
passThru();
save();
}
interface ColumnAttr {
name: string;
cell: string;
headerCell: string;
label: string;
sortable: boolean;
editable: boolean;
renderable: boolean;
formater: string;
}
class Column extends Backbone.Model {
initialize(options?: any);
}
class Body extends Backbone.View {
tagName: string;
initialize(options?: any);
insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any);
moveToNextCell(model: Backbone.Model, cell: Column, command: Command);
refresh(): Body;
remove(): Body;
removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any);
render(): Body;
}
class Grid extends Backbone.View {
body: Backgrid.Body;
className: string;
footer: any;
header: any;
tagName: string;
initialize(options: any);
getSelectedModels(): Backbone.Model[];
insertColumn(...options: any[]): Grid;
insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any);
remove():Grid;
removeColumn(...options: any[]): Grid;
removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any);
render():Grid;
}
}
+3 -3
View File
@@ -12,15 +12,15 @@
* Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
*/
module BgiFrame {
declare module BgiFrame {
interface ISettings {
top: string;
left: string;
width: string;
height: string;
opacity: bool;
opacity: boolean;
src: string;
conditional: bool;
conditional: boolean;
}
interface IBgiframe {
+4 -4
View File
@@ -23,21 +23,21 @@ interface BootboxHandler {
interface BootboxOption {
header: string;
headerCloseButton: bool;
headerCloseButton: boolean;
}
interface BootboxStatic {
alert(message: string, callback: () => void): void;
alert(message: string, customButtonText?: string, callback?: () => void): void;
confirm(message: string, callback: (result: bool) => void): void;
confirm(message: string, cancelButtonText?: string, confirmButtonText?: string, callback?: (result: bool) => void): void;
confirm(message: string, callback: (result: boolean) => void): void;
confirm(message: string, cancelButtonText?: string, confirmButtonText?: string, callback?: (result: boolean) => void): void;
prompt(message: string, callback: (result: string) => void, defaultValue?: string): void;
prompt(message: string, cancelButtonText?: string, confirmButtonText?: string, callback?: (result: string) => void, defaultValue?: string): void;
dialog(message: string, handlers: BootboxHandler[], options?: any): void;
dialog(message: string, handler: BootboxHandler): void;
dialog(message: string): void;
hideAll(): void;
animate(shouldAnimate: bool): void;
animate(shouldAnimate: boolean): void;
backdrop(backdropValue: string): void;
classes(customCssClasses: string): void;
setIcons(icons: BootboxIcons): void;
+3 -3
View File
@@ -13,9 +13,9 @@ interface NotifyOptions {
type?: string;
/**
Allow alert to be closable through a close icon.
@param {bool} closable
@param {boolean} closable
*/
closable?: bool;
closable?: boolean;
/**
Alert transition, pretty sure only fade is supported, you can try others if you wish.
@param {string} transition
@@ -44,7 +44,7 @@ interface NotifyOptions {
}
interface NotifyFadeOutSettings {
enabled?: bool;
enabled?: boolean;
delay?: number;
}
+4 -4
View File
@@ -11,11 +11,11 @@ interface DatepickerOptions {
weekStart?: number;
startDate?: Date;
endDate?: Date;
autoclose?: bool;
autoclose?: boolean;
startView?: number;
todayBtn?: bool;
todayHighlight?: bool;
keyboardNavigation?: bool;
todayBtn?: boolean;
todayHighlight?: boolean;
keyboardNavigation?: boolean;
language?: string;
}
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="../jquery/jquery.d.ts"/>
interface PaginatorOptions{
alignment?: string;
size?: string;
itemContainerClass?: (type, page, current) => string;
currentPage?: number;
numberOfPages?: number;
totalPages?: number;
pageUrl?: (type, page, current) => string;
shouldShowPage?: boolean;
itemText?: (type, page, current) => any;
tooltipTitles?: (type, page, current) => string;
useBootstrapTooltip?: boolean;
bootstrapTooltipOptions?: {};
onPageClicked?: (event, originalEvent, type, page) => void;
onPageChanged?: (event, originalEvent, type, page) => void;
}
interface JQuery {
bootstrapPaginator(): JQuery;
bootstrapPaginator(options: PaginatorOptions): JQuery;
}
+24
View File
@@ -0,0 +1,24 @@
/// <reference path="../jquery/jquery.d.ts"/>
interface TimeickerOptions {
defaultTime?: string;
disableFocus?: boolean;
isOpen?: boolean;
minuteStep?: number;
modalBackdrop?: boolean;
secondStep?: number;
showSeconds?: boolean;
showInputs?: boolean;
showMeridian?: boolean;
template?: string;
appendWidgetTo?: string;
}
interface JQuery {
timepicker(): JQuery;
timepicker(methodName: string): JQuery;
timepicker(methodName: string, params: any): JQuery;
timepicker(options: TimeickerOptions): JQuery;
}
+6 -1
View File
@@ -35,6 +35,11 @@ $('#myCollapsible').collapse({ toggle: false });
$('.carousel').carousel();
$('.carousel').carousel({ interval: 2000 });
$('.typeahead').typeahead();
$('.typeahead').typeahead({
matcher: item => true,
sorter: (items: any[]) => items,
updater: item => item,
highlighter: item => ""
});
$('#navbar').affix();
+17 -14
View File
@@ -7,16 +7,16 @@
/// <reference path="../jquery/jquery.d.ts"/>
interface ModalOptions {
backdrop?: bool;
keyboard?: bool;
show?: bool;
backdrop?: boolean;
keyboard?: boolean;
show?: boolean;
remote?: string;
}
interface ModalOptionsBackdropString {
backdrop?: string; // for "static"
keyboard?: bool;
show?: bool;
keyboard?: boolean;
show?: boolean;
remote?: string;
}
@@ -25,29 +25,31 @@ interface ScrollSpyOptions {
}
interface TooltipOptions {
animation?: bool;
html?: bool;
animation?: boolean;
html?: boolean;
placement?: any;
selector?: string;
title?: any;
trigger?: string;
delay?: any;
container?: any;
}
interface PopoverOptions {
animation?: bool;
html?: bool;
animation?: boolean;
html?: boolean;
placement?: any;
selector?: string;
trigger?: string;
title?: any;
content?: any;
delay?: any;
delay?: any;
container?: any;
}
interface CollapseOptions {
parent?: any;
toggle?: bool;
toggle?: boolean;
}
interface CarouselOptions {
@@ -59,9 +61,10 @@ interface TypeaheadOptions {
source?: any;
items?: number;
minLength?: number;
matcher?: () => any;
sorter?: () => any;
highlighter?: () => any;
matcher?: (item: any) => boolean;
sorter?: (items: any[]) => any[];
updater?: (item: any) => any;
highlighter?: (item: any) => string;
}
interface AffixOptions {
+95
View File
@@ -0,0 +1,95 @@
box2dweb.d.ts
===========
This is a derived work of the original Box2D C++ located here: http://box2d.org/
This is a typescript definitions file for box2dweb.js located here: http://code.google.com/p/box2dweb/
There are a few ports of Box2D to javascript, I have specifically picked box2dweb.js since it has zero dependencies and can be linked to your project via a single file. It also appears to be the most up to date with box2d and is a direct automated port from Box2DFlash (http://www.box2dflash.org/)
Basic Usage
==========
Import Statements
-----------------
Reference the box2dweb.d.ts file in your project and in an appropriate location include the following import statements to reduce the amount of typing you will need to do to acccess deeply nested modules.
```typescript
/// <reference path="box2dweb.d.ts" />
// Include the following imports, or add more/less, to reduce the module nesting.
import b2Common = Box2D.Common;
import b2Math = Box2D.Common.Math;
import b2Collision = Box2D.Collision;
import b2Shapes = Box2D.Collision.Shapes;
import b2Dynamics = Box2D.Dynamics;
import b2Contacts = Box2D.Dynamics.Contacts;
import b2Controllers = Box2D.Dynamics.Controllers;
import b2Joints = Box2D.Dynamics.Joints;
```
Debug Drawing
-------------
Notes from Box2DWeb
Although Box2D is a physics engine and therefore has nothing to do with drawing, Box2dFlash provides such methods for debugging which are defined in the b2DebugDraw class. In Box2dWeb, a b2DebugDraw takes a canvas-context instead of a Sprite:
```typescript
var debugDraw = new Box2D.Dynamics.b2DebugDraw();
debugDraw.SetSprite(document.getElementsByTagName("canvas")[0].getContext("2d"));
```
Events
------
Notes from Box2DWeb
You have to implement event-interfaces in Box2dFlash. Since Javascript doesn't support classical inheritance natively, I show you how to deal with events in Box2dWeb:
```typescript
var world = new Box2D.Dynamics.b2World(new Box2D.Common.Math.b2Vec2(0, 10), true);
/* ... add bodies, etc. ... */
var myListener = new Box2D.Dynamics.b2DestructionListener;
myListener.SayGoodbyeFixture = function(fixture) {
alert("goodbye fixture ...");
}
world.SetDestructionListener(myListener);
```
Change Log
==========
2.1a 2013/06/28
---------------
* Upgraded to TypeScript v0.9
* Removed import statements so the user can now declare the smaller namespaces in their code. Before the import statements were not 'exported', so they appeared as 'any' objects.
License
=======
Box2DWeb-2.1.d.ts Copyright (c) 2012 Josh Baldwin http://github.com/jbaldwin/box2dweb.d.ts
There are a few competing javascript Box2D ports.
This definitions file is for Box2dWeb.js ->
http://code.google.com/p/box2dweb/
Box2D C++ Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="box2dweb.d.ts" />
import b2Common = Box2D.Common;
import b2Math = Box2D.Common.Math;
import b2Collision = Box2D.Collision;
import b2Shapes = Box2D.Collision.Shapes;
import b2Dynamics = Box2D.Dynamics;
import b2Contacts = Box2D.Dynamics.Contacts;
import b2Controllers = Box2D.Dynamics.Controllers;
import b2Joints = Box2D.Dynamics.Joints;
var w1 = new Box2D.Dynamics.b2World(new Box2D.Common.Math.b2Vec2(0, 10), true);
var w2 = new b2Dynamics.b2World(new b2Math.b2Vec2(0, 10), true);
var debugDraw = new Box2D.Dynamics.b2DebugDraw();
debugDraw.SetSprite((<HTMLCanvasElement>document.getElementsByTagName("canvas")[0]).getContext("2d"));
+356 -367
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1,7 +1,7 @@
/// <reference path="breeze-1.0.d.ts" />
import breeze = module(Breeze);
import core = module(BreezeCore);
import breeze = Breeze;
import core = BreezeCore;
function test_dataType() {
var typ = breeze.DataType.DateTime;
+72 -72
View File
@@ -13,7 +13,7 @@ declare module BreezeCore {
}
interface IEnum {
contains(object: any): bool;
contains(object: any): boolean;
fromName(name: string): EnumSymbol;
getNames(): string[];
getSymbols(): EnumSymbol[];
@@ -23,11 +23,11 @@ declare module BreezeCore {
constructor (name: string, methodObj?: any);
addSymbol(propertiesObj?: any): EnumSymbol;
contains(object: any): bool;
contains(object: any): boolean;
fromName(name: string): EnumSymbol;
getNames(): string[];
getSymbols(): EnumSymbol[];
static isSymbol(object: any): bool;
static isSymbol(object: any): boolean;
seal(): void;
}
@@ -42,14 +42,14 @@ declare module BreezeCore {
constructor (name: string, publisher: any, defaultErrorCallback?: ErrorCallback);
static enable(eventName: string, target: any): void;
static enable(eventName: string, target: any, isEnabled: bool): void;
static enable(eventName: string, target: any, isEnabled: boolean): void;
static enable(eventName: string, target: any, isEnabled: Function): void;
static isEnabled(eventName: string, target: any): bool;
publish(data: any, publishAsync?: bool, errorCallback?: ErrorCallback): void;
static isEnabled(eventName: string, target: any): boolean;
publish(data: any, publishAsync?: boolean, errorCallback?: ErrorCallback): void;
publishAsync(data: any, errorCallback?: ErrorCallback): void;
subscribe(callback?: (data: any) => void ): number;
unsubscribe(unsubKey: number): bool;
unsubscribe(unsubKey: number): boolean;
}
}
@@ -69,8 +69,8 @@ declare module Breeze {
name: string;
parentEntityType: EntityType;
validators: Validator[];
isDataProperty: bool;
isNavigationProperty: bool;
isDataProperty: boolean;
isNavigationProperty: boolean;
}
interface IStructuralType {
@@ -115,13 +115,13 @@ declare module Breeze {
concurrencyMode: string;
dataType: DataTypeSymbol;
defaultValue: any;
fixedLength: bool;
isComplexProperty: bool;
isDataProperty: bool;
isNavigationProperty: bool;
isNullable: bool;
isPartOfKey: bool;
isUnmapped: bool;
fixedLength: boolean;
isComplexProperty: boolean;
isDataProperty: boolean;
isNavigationProperty: boolean;
isNullable: boolean;
isPartOfKey: boolean;
isUnmapped: boolean;
maxLength: number;
name: string;
@@ -137,10 +137,10 @@ declare module Breeze {
concurrencyMode?: string;
dataType?: DataTypeSymbol;
defaultValue?: any;
fixedLength?: bool;
isNullable?: bool;
isPartOfKey?: bool;
isUnmapped?: bool;
fixedLength?: boolean;
isNullable?: boolean;
isPartOfKey?: boolean;
isUnmapped?: boolean;
maxLength?: number;
name?: string;
nameOnServer?: string;
@@ -149,20 +149,20 @@ declare module Breeze {
class DataService {
adapterName: string;
hasServerMetadata: bool;
hasServerMetadata: boolean;
serviceName: string;
constructor(config: DataServiceOptions);
}
interface DataServiceOptions {
adapterName?: string;
hasServerMetadata?: bool;
hasServerMetadata?: boolean;
serviceName?: string;
}
class DataTypeSymbol extends BreezeCore.EnumSymbol {
defaultValue: any;
isNumeric: bool;
isNumeric: boolean;
}
interface DataType extends BreezeCore.IEnum {
Binary: DataTypeSymbol;
@@ -183,7 +183,7 @@ declare module Breeze {
parseDateFromServer(date: any): Date;
}
declare var DataType: DataType;
var DataType: DataType;
class EntityActionSymbol extends BreezeCore.EnumSymbol {
}
@@ -207,7 +207,7 @@ declare module Breeze {
entity: Entity;
entityManager: EntityManager;
entityState: EntityStateSymbol;
isBeingSaved: bool;
isBeingSaved: boolean;
originalValues: any;
propertyChanged: PropertyChangedEvent;
@@ -216,7 +216,7 @@ declare module Breeze {
acceptChanges(): void;
addValidationError(validationError: ValidationError): void;
clearValidationErrors(): void;
getKey(forceRefresh?: bool): EntityKey;
getKey(forceRefresh?: boolean): EntityKey;
getValidationErrors(): ValidationError[];
getValidationErrors(property: string): ValidationError[];
@@ -234,11 +234,11 @@ declare module Breeze {
setDeleted(): void;
setModified(): void;
setUnchanged(): void;
validateEntity(): bool;
validateEntity(): boolean;
validateProperty(property: string, context?: any): bool;
validateProperty(property: DataProperty, context?: any): bool;
validateProperty(property: NavigationProperty, context?: any): bool;
validateProperty(property: string, context?: any): boolean;
validateProperty(property: DataProperty, context?: any): boolean;
validateProperty(property: NavigationProperty, context?: any): boolean;
}
class PropertyChangedEventArgs {
@@ -266,8 +266,8 @@ declare module Breeze {
constructor (entityType: EntityType, keyValue: any);
constructor (entityType: EntityType, keyValues: any[]);
equals(entityKey: EntityKey): bool;
static equals(k1: EntityKey, k2: EntityKey): bool;
equals(entityKey: EntityKey): boolean;
static equals(k1: EntityKey, k2: EntityKey): boolean;
}
class EntityManager {
@@ -289,7 +289,7 @@ declare module Breeze {
attachEntity(entity: Entity, entityState?: EntityStateSymbol): Entity;
clear(): void;
createEmptyCopy(): EntityManager;
detachEntity(entity: Entity): bool;
detachEntity(entity: Entity): boolean;
createEntity(entityTypeName: string, propertyInitializer: {}): Entity;
executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise;
@@ -297,8 +297,8 @@ declare module Breeze {
executeQueryLocally(query: EntityQuery): Entity[];
exportEntities(entities?: Entity[]): string;
fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: bool): Entity;
fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: bool): Entity;
fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: boolean): Entity;
fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: boolean): Entity;
fetchEntityByKey(entityKey: EntityKey): Entity;
fetchMetadata(callback?: (schema: any) => void , errorCallback?: BreezeCore.ErrorCallback): Promise;
generateTempKeyValue(entity: Entity): any;
@@ -322,11 +322,11 @@ declare module Breeze {
getEntityByKey(typeName: string, keyValues: any[]): Entity;
getEntityByKey(entityKey: EntityKey): Entity;
hasChanges(): bool;
hasChanges(entityTypeName: string): bool;
hasChanges(entityTypeNames: string[]): bool;
hasChanges(entityType: EntityType): bool;
hasChanges(entityTypes: EntityType[]): bool;
hasChanges(): boolean;
hasChanges(entityTypeName: string): boolean;
hasChanges(entityTypeNames: string[]): boolean;
hasChanges(entityType: EntityType): boolean;
hasChanges(entityTypes: EntityType[]): boolean;
static importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; }): EntityManager;
importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; }): EntityManager;
@@ -403,7 +403,7 @@ declare module Breeze {
static fromEntities(entities: Entity[]): EntityQuery;
static fromEntityKey(entityKey: EntityKey): EntityQuery;
static fromEntityNavigation(entity: Entity, navigationProperty: NavigationProperty): EntityQuery;
inlineCount(enabled?: bool): EntityQuery;
inlineCount(enabled?: boolean): EntityQuery;
orderBy(propertyPaths: string): EntityQuery;
orderBy(propertyPaths: string[]): EntityQuery;
orderByDesc(propertyPaths: string): EntityQuery;
@@ -429,13 +429,13 @@ declare module Breeze {
}
class EntityStateSymbol extends BreezeCore.EnumSymbol {
isAdded(): bool;
isAddedModifiedOrDeleted(): bool;
isDeleted(): bool;
isDetached(): bool;
isModified(): bool;
isUnchanged(): bool;
isUnchangedOrModified(): bool;
isAdded(): boolean;
isAddedModifiedOrDeleted(): boolean;
isDeleted(): boolean;
isDetached(): boolean;
isModified(): boolean;
isUnchanged(): boolean;
isUnchangedOrModified(): boolean;
}
interface EntityState extends BreezeCore.IEnum {
Added: EntityStateSymbol;
@@ -472,7 +472,7 @@ declare module Breeze {
getEntityCtor(): Function;
getNavigationProperty(propertyName: string): NavigationProperty;
getProperties(): IProperty[];
getProperty(propertyPath: string, throwIfNotFound?: bool): IProperty;
getProperty(propertyPath: string, throwIfNotFound?: boolean): IProperty;
getPropertyNames(): string[];
setProperties(config: EntityTypeProperties): void;
toString(): string;
@@ -517,7 +517,7 @@ declare module Breeze {
static caseInsensitiveSQL: LocalQueryComparisonOptions;
static defaultInstance: LocalQueryComparisonOptions;
constructor (config: { name?: string; isCaseSensitive?: bool; usesSql92CompliantStringComparison?: bool; });
constructor (config: { name?: string; isCaseSensitive?: boolean; usesSql92CompliantStringComparison?: boolean; });
setAsDefault(): void;
}
@@ -540,12 +540,12 @@ declare module Breeze {
fetchMetadata(dataService: string, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise;
fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise;
getDataService(serviceName: string): DataService;
getEntityType(entityTypeName: string, okIfNotFound?: bool): IStructuralType;
getEntityType(entityTypeName: string, okIfNotFound?: boolean): IStructuralType;
getEntityTypes(): IStructuralType[];
hasMetadataFor(serviceName: string): bool;
hasMetadataFor(serviceName: string): boolean;
static importMetadata(exportedString: string): MetadataStore;
importMetadata(exportedString: string): MetadataStore;
isEmpty(): bool;
isEmpty(): boolean;
registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) =>void ): void;
trackUnmappedType(entityCtor: Function, interceptor?: Function);
}
@@ -581,9 +581,9 @@ declare module Breeze {
entityType: EntityType;
foreignKeyNames: string[];
inverse: NavigationProperty;
isDataProperty: bool;
isNavigationProperty: bool;
isScalar: bool;
isDataProperty: boolean;
isNavigationProperty: boolean;
isScalar: boolean;
name: string;
parentEntityType: EntityType;
relatedDataProperties: DataProperty[];
@@ -596,7 +596,7 @@ declare module Breeze {
name?: string;
nameOnServer?: string;
entityTypeName: string;
isScalar?: bool;
isScalar?: boolean;
associationName?: string;
foreignKeyNames?: string[];
foreignKeyNamesOnServer?: string[];
@@ -604,15 +604,15 @@ declare module Breeze {
}
class Predicate {
constructor (property: string, operator: string, value: any, valueIsLiteral?: bool);
constructor (property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: bool);
constructor (property: string, operator: string, value: any, valueIsLiteral?: boolean);
constructor (property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: boolean);
and: PredicateMethod;
static and: PredicateMethod;
static create: PredicateMethod;
static isPredicate(o: any): bool;
static isPredicate(o: any): boolean;
static not(predicate: Predicate): Predicate;
not(): Predicate;
@@ -628,8 +628,8 @@ declare module Breeze {
interface PredicateMethod {
(predicates: Predicate[]): Predicate;
(...predicates: Predicate[]): Predicate;
(property: string, operator: string, value: any, valueIsLiteral?: bool): Predicate;
(property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: bool): Predicate;
(property: string, operator: string, value: any, valueIsLiteral?: boolean): Predicate;
(property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: boolean): Predicate;
}
class Promise {
@@ -657,10 +657,10 @@ declare module Breeze {
}
class SaveOptions {
allowConcurrentSaves: bool;
allowConcurrentSaves: boolean;
static defaultInstance: SaveOptions;
constructor (config?: { allowConcurrentSaves?: bool; });
constructor (config?: { allowConcurrentSaves?: boolean; });
setAsDefault(): SaveOptions;
}
@@ -677,10 +677,10 @@ declare module Breeze {
class ValidationOptions {
static defaultInstance: ValidationOptions;
validateOnAttach: bool;
validateOnPropertyChange: bool;
validateOnQuery: bool;
validateOnSave: bool;
validateOnAttach: boolean;
validateOnPropertyChange: boolean;
validateOnQuery: boolean;
validateOnSave: boolean;
constructor (config?: ValidationOptionsConfiguration);
@@ -689,10 +689,10 @@ declare module Breeze {
}
interface ValidationOptionsConfiguration {
validateOnAttach?: bool;
validateOnSave?: bool;
validateOnQuery?: bool;
validateOnPropertyChange?: bool;
validateOnAttach?: boolean;
validateOnSave?: boolean;
validateOnQuery?: boolean;
validateOnPropertyChange?: boolean;
}
class Validator {
+797
View File
@@ -0,0 +1,797 @@
/// <reference path="breeze-1.2.d.ts" />
import core = breezeCore;
function test_dataType() {
var typ = breeze.DataType.DateTime;
var nm = typ.getName();
var isNumber = typ.isNumeric;
var dv = typ.defaultValue;
var symbs = breeze.DataType.getSymbols();
var x = typ.parentEnum === <breezeCore.IEnum> breeze.DataType;
var isFalse = breeze.DataType.contains(breeze.DataType.Double);
var dt = breeze.DataType.fromName("Decimal");
}
function test_dataProperty() {
var lastNameProp = new breeze.DataProperty({
name: "lastName",
dataType: breeze.DataType.String,
isNullable: true,
maxLength: 20
});
var personEntityType: breeze.EntityType;
personEntityType.addProperty(lastNameProp);
}
function test_dataService() {
var ds = new breeze.DataService({
serviceName: "api/NorthwindIBModel",
hasServerMetadata: true
});
var em = new breeze.EntityManager({
dataService: ds
});
}
function test_entityAspect() {
var order: breeze.Entity;
order.entityAspect.acceptChanges();
var entityKey = order.entityAspect.getKey();
var valErrors = order.entityAspect.getValidationErrors();
var orderDateErrors = order.entityAspect.getValidationErrors("OrderDate");
var orderDateProperty = order.entityType.getProperty("OrderDate");
var orderDateErrors = order.entityAspect.getValidationErrors(orderDateProperty);
order.entityAspect.loadNavigationProperty("Orders").then(function (data) {
var orders = data.results;
}).fail(function (exception) { });
order.entityAspect.rejectChanges();
order.entityAspect.setDeleted();
order.entityAspect.setModified();
order.entityAspect.setUnchanged();
var isOk = order.entityAspect.validateEntity();
if (!isOk) {
var errors = order.entityAspect.getValidationErrors();
}
var isOk = order.entityAspect.validateProperty("Order");
var orderDateProperty = order.entityType.getProperty("OrderDate");
//var isOk = order.entityAspect.validateProperty(OrderDateProperty);
order.entityAspect.propertyChanged.subscribe(function (propertyChangedArgs) {
var entity = propertyChangedArgs.entity;
var propertyNameChanged = propertyChangedArgs.propertyName;
var oldValue = propertyChangedArgs.oldValue;
var newValue = propertyChangedArgs.newValue;
});
order.entityAspect.validationErrorsChanged.subscribe(function (validationChangeArgs) {
var entity = validationChangeArgs.entity;
var errorsAdded = validationChangeArgs.added;
var errorsCleared = validationChangeArgs.removed;
});
}
function test_entityKey() {
var em1: breeze.EntityManager;
var employee1: breeze.Entity;
var empType = em1.metadataStore.getEntityType("Employee");
var entityKey = new breeze.EntityKey(<breeze.EntityType> empType, 1);
var empKey = employee1.entityAspect.getKey();
var empTerrType = em1.metadataStore.getEntityType("EmployeeTerritory");
var empTerrKey = new breeze.EntityKey(<breeze.EntityType> empTerrType, [1, 77]);
var empType = em1.metadataStore.getEntityType("Employee");
var empKey1 = new breeze.EntityKey(<breeze.EntityType> empType, 1);
var empKey2 = employee1.entityAspect.getKey();
if (empKey1.equals(empKey2)) { }
if (breeze.EntityKey.equals(empKey1, empKey2)) { }
}
function test_metadataStore() {
var ms = new breeze.MetadataStore();
var entityManager = new breeze.EntityManager({
serviceName: "api/NorthwindIBModel",
metadataStore: ms
});
var em1: breeze.EntityManager;
em1.setProperties({ metadataStore: ms });
var metadataAsString = ms.exportMetadata();
window.localStorage.setItem("metadata", metadataAsString);
var metadataFromStorage = window.localStorage.getItem("metadata");
var newMetadataStore = new breeze.MetadataStore();
newMetadataStore.importMetadata(metadataFromStorage);
var ms = new breeze.MetadataStore();
ms.fetchMetadata("api/NorthwindIBModel")
.then(function (rawMetadata) { })
.fail(function (exception) { });
var odType = em1.metadataStore.getEntityType("OrderDetail");
var badType = em1.metadataStore.getEntityType("Foo", false);
var allTypes = em1.metadataStore.getEntityTypes();
if (!em1.metadataStore.hasMetadataFor("api/NorthwindIBModel")) { }
var metadataAsString = ms.exportMetadata();
window.localStorage.setItem("metadata", metadataAsString);
var metadataFromStorage = window.localStorage.getItem("metadata");
var newMetadataStore = breeze.MetadataStore.importMetadata(metadataFromStorage);
var metadataAsString = ms.exportMetadata();
window.localStorage.setItem("metadata", metadataAsString);
var metadataFromStorage = window.localStorage.getItem("metadata");
var newMetadataStore = new breeze.MetadataStore();
newMetadataStore.importMetadata(metadataFromStorage);
if (em1.metadataStore.isEmpty()) { }
var Customer = function () {
this.miscData = "asdf";
}
em1.metadataStore.registerEntityTypeCtor("Customer", Customer);
}
function test_entityManager() {
var entityManager = new breeze.EntityManager("api/NorthwindIBModel");
var em1 = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" });
var metadataStore = new breeze.MetadataStore();
var entityManager = new breeze.EntityManager({
serviceName: "api/NorthwindIBModel",
metadataStore: metadataStore
});
return new breeze.QueryOptions({
mergeStrategy: null,
fetchStrategy: this.fetchStrategy
});
var queryOptions = new breeze.QueryOptions({
mergeStrategy: breeze.MergeStrategy.OverwriteChanges,
fetchStrategy: breeze.FetchStrategy.FromServer
});
var validationOptions = new breeze.ValidationOptions({
validateOnAttach: true,
validateOnSave: true,
validateOnQuery: false
});
var entityManager = new breeze.EntityManager({
serviceName: "api/NorthwindIBModel",
queryOptions: queryOptions,
validationOptions: validationOptions
});
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var cust1 = custType.createEntity();
em1.addEntity(cust1);
var cust2 = em1.createEntity("Customer", { companyName: "foo" });
var cust3 = em1.createEntity("foo", { xxx: 3 }, breeze.EntityState.Added);
em1.attachEntity(cust1, breeze.EntityState.Added);
em1.clear();
var em2 = em1.createEmptyCopy();
em1.detachEntity(cust1);
var serviceName: string;
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
em.executeQuery(query)
.then(function (data) {
var orders = data.results;
}).fail(function (err) {
});
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
em.executeQuery(query,
function (data) {
var orders = data.results;
},
function (err) {
});
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(em);
query.execute()
.then(function (data) {
var orders = data.results;
}).fail(function (err) {
});
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
var orders = em.executeQueryLocally(query);
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(breeze.FetchStrategy.FromLocalCache);
em.executeQuery(query)
.then(function (data) {
var orders = data.results;
}).fail(function (err) {
});
var bundle = em1.exportEntities();
window.localStorage.setItem("myEntityManager", bundle);
var bundleFromStorage = window.localStorage.getItem("myEntityManager");
var em2 = new breeze.EntityManager({
serviceName: em1.serviceName,
metadataStore: em1.metadataStore
});
em2.importEntities(bundleFromStorage);
var entitiesToExport: breeze.Entity[];
var bundle = em1.exportEntities(entitiesToExport);
em2.importEntities(bundle, { mergeStrategy: breeze.MergeStrategy.PreserveChanges });
var em1 = new breeze.EntityManager("api/NorthwindIBModel");
em1.fetchMetadata()
.then(function () {
var metadataStore = em1.metadataStore;
})
.fail(function (exception) {
});
var employeeType = em1.metadataStore.getEntityType("Employee");
var employeeKey = new breeze.EntityKey(<breeze.EntityType> employeeType, 1);
var employee = em1.fetchEntityByKey(employeeKey);
var emp2 = em1.fetchEntityByKey("Employee", 6);
var emp3 = em1.fetchEntityByKey("Entityee", [6]);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var custumer = custType.createEntity();
var customerId = em.generateTempKeyValue(custumer);
em1.saveChanges()
.then(function (data) {
var sameCust1 = data.results[0];
});
var changedEntities = em1.getChanges();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var changedCustomers = em1.getChanges(custType);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var changedCustomersAndOrders = em1.getChanges([custType, orderType]);
var entities = em1.getEntities();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var customers = em1.getEntities(custType);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var customersAndOrders = em1.getChanges([custType, orderType]);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var addedCustomersAndOrders = em1.getEntities([custType, orderType], breeze.EntityState.Added);
if (em1.hasChanges()) { }
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
if (em1.hasChanges(custType)) { }
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
if (em1.hasChanges([custType, orderType])) { };
var bundle = em1.exportEntities();
window.localStorage.setItem("myEntityManager", bundle);
var bundleFromStorage = window.localStorage.getItem("myEntityManager");
var em2 = breeze.EntityManager.importEntities(bundleFromStorage);
var bundle = em1.exportEntities();
var em2 = new breeze.EntityManager({
serviceName: em1.serviceName,
metadataStore: em1.metadataStore
});
em2.importEntities(bundle);
var bundle = em1.exportEntities();
em2.importEntities(bundle, { mergeStrategy: breeze.MergeStrategy.PreserveChanges });
em.saveChanges().then(function (saveResult) {
var savedEntities = saveResult.entities;
var keyMappings = saveResult.keyMappings;
}).fail(function (e) {
});
var saveOptions = new breeze.SaveOptions({ allowConcurrentSaves: true });
var entitiesToSave: breeze.Entity[];
em.saveChanges(entitiesToSave, saveOptions).then(function (saveResult) {
var savedEntities = saveResult.entities;
var keyMappings = saveResult.keyMappings;
}).fail(function (e) {
});
em.saveChanges(entitiesToSave, null,
function (saveResult) {
var savedEntities = saveResult.entities;
var keyMappings = saveResult.keyMappings;
}, function (e) { }
);
em1.setProperties({
serviceName: "api/foo",
});
var em = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" });
em.entityChanged.subscribe(function (changeArgs) {
var action = changeArgs.entityAction;
var entity = changeArgs.entity;
});
var em = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" });
em.hasChangesChanged.subscribe(function (args) {
var hasChanges = args.hasChanges;
var entityManager = args.entityManager;
});
}
function test_entityQuery() {
var query = new breeze.EntityQuery("Customers");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.orderBy("Region");
var serviceName: string;
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(em);
query.execute()
.then(function (data) { })
.fail(function (err) { });
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(em);
query.execute(
function (data) {
var orders = data.results;
},
function (err) { });
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
em.executeQuery(query)
.then(function (data) {
var orders = data.results;
}).fail(function (err) {
});
var query = new breeze.EntityQuery("Orders").using(em);
var orders = query.executeLocally();
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.expand("Orders");
var query = new breeze.EntityQuery("Orders")
.expand("Customer, Employee");
var query = new breeze.EntityQuery("Orders")
.expand("Customer, OrderDetails, OrderDetails.Product");
var query = breeze.EntityQuery.from("Customers");
var query = new breeze.EntityQuery("Customers");
var query = new breeze.EntityQuery().from("Customers");
var customer: breeze.Entity;
var customers: breeze.Entity[];
var customersQuery = breeze.EntityQuery.fromEntities(customers);
var customersQuery = breeze.EntityQuery.fromEntities(customers)
.where("Region", breeze.FilterQueryOp.NotEquals, null);
var customerQuery = breeze.EntityQuery.fromEntities(customer);
var metadataStore: breeze.MetadataStore;
var empType = metadataStore.getEntityType("Employee");
var entityKey = new breeze.EntityKey(<breeze.EntityType> empType, 1);
var query = breeze.EntityQuery.fromEntityKey(entityKey);
var employee: breeze.Entity;
var entityKey = employee.entityAspect.getKey();
var query = breeze.EntityQuery.fromEntityKey(entityKey);
var ordersNavProp = employee.entityType.getProperty("Orders");
var query = breeze.EntityQuery.fromEntityNavigation(employee, <breeze.NavigationProperty> ordersNavProp);
var query = new breeze.EntityQuery("Customers")
.orderBy("CompanyName");
var query = new breeze.EntityQuery("Customers")
.orderBy("Region, CompanyName");
var query = new breeze.EntityQuery("Products")
.orderBy("Category.CategoryName");
var query = new breeze.EntityQuery("Customers")
.orderBy("CompanyName desc");
var query = new breeze.EntityQuery("Customers")
.orderBy("Region desc, CompanyName desc");
var query = new breeze.EntityQuery("Customers")
.orderByDesc("CompanyName");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.select("CompanyName");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.select("Orders");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.select("CompanyName, Orders");
var query = new breeze.EntityQuery("Orders")
.where("Customer.CompanyName", "startsWith", "C")
.select("Customer.CompanyName, Customer, OrderDate");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.skip(5);
var query = new breeze.EntityQuery("Customers")
.take(5);
var query = new breeze.EntityQuery("Customers")
.top(5);
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders")
.using(em);
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders")
.using(breeze.MergeStrategy.PreserveChanges);
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders")
.using(breeze.FetchStrategy.FromLocalCache);
var adapter = new breeze.JsonResultsAdapter({ name: "foo", visitNode: function (x) { return x; } });
var q2 = query.using(adapter);
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", breeze.FilterQueryOp.StartsWith, "C");
var pred = new breeze.Predicate("CompanyName", breeze.FilterQueryOp.StartsWith, "C");
var query = new breeze.EntityQuery("Customers")
.where(pred);
var pred = breeze.Predicate.create("CompanyName", "startswith", "C").and("Region", breeze.FilterQueryOp.Equals, null);
var query = new breeze.EntityQuery("Customers")
.where(pred);
var query = new breeze.EntityQuery("Products")
.where("Category.CategoryName", "startswith", "S");
var query = new breeze.EntityQuery("Customers")
.where("toLower(CompanyName)", "startsWith", "c");
var query = new breeze.EntityQuery("Customers")
.where("toUpper(substring(CompanyName, 1, 2))", breeze.FilterQueryOp.Equals, "OM");
var q2 = query.toType("foo").orderBy("foo2");
}
function test_entityState() {
var anEntity: breeze.Entity;
var es = anEntity.entityAspect.entityState;
return es.isAdded();
return es === breeze.EntityState.Added;
var es = anEntity.entityAspect.entityState;
return es.isAddedModifiedOrDeleted();
return es === breeze.EntityState.Added || es === breeze.EntityState.Modified || es === breeze.EntityState.Deleted;
var es = anEntity.entityAspect.entityState;
return es.isDeleted();
return es === breeze.EntityState.Deleted;
var es = anEntity.entityAspect.entityState;
return es.isDetached();
return es === breeze.EntityState.Detached;
var es = anEntity.entityAspect.entityState;
return es.isModified();
return es === breeze.EntityState.Modified;
var es = anEntity.entityAspect.entityState;
return es.isUnchanged();
return es === breeze.EntityState.Unchanged;
var es = anEntity.entityAspect.entityState;
return es.isUnchangedOrModified();
return es === breeze.EntityState.Unchanged || es === breeze.EntityState.Modified;
}
function test_entityType() {
var myMetadataStore: breeze.MetadataStore;
var myEntityType: breeze.EntityType;
var dataProperty1, dataProperty2, navigationProperty1: breeze.DataProperty;
var em1: breeze.EntityManager;
var entityManager = new breeze.EntityType({
metadataStore: myMetadataStore,
serviceName: "api/NorthwindIBModel",
name: "person",
namespace: "myAppNamespace"
});
myEntityType.addProperty(dataProperty1);
myEntityType.addProperty(dataProperty2);
myEntityType.addProperty(navigationProperty1);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var countryProp = custType.getProperty("Country");
var valFn = function (v) {
if (v == null) return true;
return (v.substring(0,2) === "US");
};
var countryValidator = new breeze.Validator("countryIsUS", valFn,
{ displayName: "Country", messageTemplate: "'%displayName%' must start with 'US'" });
custType.addValidator(countryValidator, countryProp);
countryProp.validators.push(countryValidator);
var someEntityLevelValidator: breeze.Validator;
custType.addValidator(someEntityLevelValidator);
custType.validators.push(someEntityLevelValidator);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var cust1 = custType.createEntity();
em1.addEntity(cust1);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var customerNameDataProp = custType.getDataProperty("CustomerName");
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var customerOrdersNavProp = custType.getDataProperty("Orders");
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var arrayOfProps = custType.getProperties();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var companyNameProp = custType.getProperty("CompanyName");
var orderDetailType = <breeze.EntityType> em1.metadataStore.getEntityType("OrderDetail");
var companyNameProp2 = orderDetailType.getProperty("Order.Customer.CompanyName");
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var arrayOfPropNames = custType.getPropertyNames();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
custType.setProperties({
autoGeneratedKeyType: breeze.AutoGeneratedKeyType.Identity,
defaultResourceName: "CustomersAndIncludedOrders"
});
}
//function test_enum() {
// var prototype = {
// nextDay: function () {
// var nextIndex = (this.dayIndex + 1) % 7;
// return DayOfWeek.getSymbols()[nextIndex];
// }
// };
// var DayOfWeek = new core.Enum("DayOfWeek", prototype);
// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 });
// var symbol = DayOfWeek.Friday;
// if (DayOfWeek.contains(symbol)) { }
// var dayOfWeek = DayOfWeek.from("Thursday");
// var symbols = DayOfWeek.getNames();
// var symbols = DayOfWeek.getSymbols();
// if (core.Enum.isSymbol(DayOfWeek.Wednesday)) { };
// DayOfWeek.seal();
// var name = DayOfWeek.Monday.getName();
// var name = DayOfWeek.Monday.toString();
// var prototype = {
// nextDay: function () {
// var nextIndex = (this.dayIndex + 1) % 7;
// return DayOfWeek.getSymbols()[nextIndex];
// }
// };
// var DayOfWeek = new core.Enum("DayOfWeek", prototype);
// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 });
// DayOfWeek.Tuesday = DayOfWeek.addSymbol({ dayIndex: 1 });
// DayOfWeek.Wednesday = DayOfWeek.addSymbol({ dayIndex: 2 });
// DayOfWeek.Thursday = DayOfWeek.addSymbol({ dayIndex: 3 });
// DayOfWeek.Friday = DayOfWeek.addSymbol({ dayIndex: 4 });
// DayOfWeek.Saturday = DayOfWeek.addSymbol({ dayIndex: 5, isWeekend: true });
// DayOfWeek.Sunday = DayOfWeek.addSymbol({ dayIndex: 6, isWeekend: true });
// DayOfWeek.seal();
// DayOfWeek.Monday.nextDay() === DayOfWeek.Tuesday;
// DayOfWeek.Sunday.nextDay() === DayOfWeek.Monday;
// DayOfWeek.Tuesday.isWeekend === undefined;
// DayOfWeek.Saturday.isWeekend == true;
// DayOfWeek instanceof core.Enum;
// core.Enum.isSymbol(DayOfWeek.Wednesday);
// DayOfWeek.contains(DayOfWeek.Thursday);
// DayOfWeek.Tuesday.parentEnum == DayOfWeek;
// DayOfWeek.getSymbols().length === 7;
// DayOfWeek.Friday.toString() === "Friday";
//}
function test_event() {
var myEntityManager: breeze.EntityManager;
var myEntity, person: breeze.Entity;
var salaryEvent = new core.Event("salaryEvent", person);
core.Event.enable("propertyChanged", myEntityManager, false);
core.Event.enable("propertyChanged", myEntityManager, true);
core.Event.enable("propertyChanged", myEntity.entityAspect, false);
core.Event.enable("propertyChanged", myEntity.entityAspect, <Function> null);
core.Event.enable("validationErrorsChanged", myEntityManager, function (em) {
return em.customTag === "blue";
});
core.Event.isEnabled("propertyChanged", myEntityManager);
salaryEvent.publish({ eventType: "payRaise", amount: 100 });
salaryEvent.publish({ eventType: "payRaise", amount: 100 }, true);
salaryEvent.publish({ eventType: "payRaise", amount: 100 }, true, function (error) { });
salaryEvent.publishAsync({ eventType: "payRaise", amount: 100 });
salaryEvent.publishAsync({ eventType: "payRaise", amount: 100 }, function (error) { });
salaryEvent.subscribe(function (eventArgs) {
if (eventArgs.eventType === "payRaise") { }
});
var order: breeze.Entity;
order.entityAspect.propertyChanged.subscribe(function (pcEvent) {
if (pcEvent.propertyName === "OrderDate") { }
});
var token = order.entityAspect.propertyChanged.subscribe(function (pcEvent) { });
order.entityAspect.propertyChanged.unsubscribe(token);
}
function test_localQueryComparisonOptions() {
var lqco = new breeze.LocalQueryComparisonOptions({
name: "caseSensitive-nonSQL",
isCaseSensitive: true,
usesSql92CompliantStringComparison: false
});
lqco.setAsDefault();
var ms = new breeze.MetadataStore({ localQueryComparisonOptions: lqco });
var em = new breeze.EntityManager({ metadataStore: ms });
var lqco = new breeze.LocalQueryComparisonOptions({
isCaseSensitive: false,
usesSql92CompliantStringComparison: true
});
lqco.setAsDefault();
}
function test_namingConventions() {
var namingConv = new breeze.NamingConvention({
serverPropertyNameToClient: function (serverPropertyName) {
return serverPropertyName.substr(0, 1).toLowerCase() + serverPropertyName.substr(1);
},
clientPropertyNameToServer: function (clientPropertyName) {
return clientPropertyName.substr(0, 1).toUpperCase() + clientPropertyName.substr(1);
}
});
var nc = new breeze.NamingConvention({
serverPropertyNameToClient: function (x) {
return "xxx";
}
});
var ms = new breeze.MetadataStore({ namingConvention: namingConv });
var em = new breeze.EntityManager({ metadataStore: ms });
var namingConv = new breeze.NamingConvention({
serverPropertyNameToClient: function (serverPropertyName) {
return serverPropertyName.substr(0, 1).toLowerCase() + serverPropertyName.substr(1);
},
clientPropertyNameToServer: function (clientPropertyName) {
return clientPropertyName.substr(0, 1).toUpperCase() + clientPropertyName.substr(1);
}
});
namingConv.setAsDefault();
}
function test_navigationProperty() {
var homeAddressProp = new breeze.NavigationProperty({
name: "homeAddress",
entityTypeName: "Address:#myNamespace",
isScalar: true,
associationName: "address_person",
foreignKeyNames: ["homeAddressId"]
});
var homeAddressIdProp = new breeze.DataProperty({
name: "homeAddressId",
dataType: breeze.DataType.Int32
});
var personEntityType: breeze.EntityType;
personEntityType.addProperty(homeAddressProp);
personEntityType.addProperty(homeAddressIdProp);
}
function test_predicate() {
var p1 = new breeze.Predicate("CompanyName", "StartsWith", "B");
var p1a = breeze.Predicate.create("CompanyName", "==", "City");
var p2a = p1a.and(p1a.not());
var query = new breeze.EntityQuery("Customers").where(p1);
var p2 = new breeze.Predicate("Region", breeze.FilterQueryOp.Equals, null);
var query = new breeze.EntityQuery("Customers").where(p2);
var dt = new Date(88, 9, 12);
var p1 = breeze.Predicate.create("OrderDate", "ne", dt);
var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C");
var p3 = breeze.Predicate.create("Freight", ">", 100);
var newPred = p1.and(p2, p3);
var preds = [p2, p3];
var newPred = p1.and(preds);
var p4 = breeze.Predicate.create("ShipCity", "startswith", "F")
.and("Size", "gt", 2000);
var dt = new Date(88, 9, 12);
var p1 = breeze.Predicate.create("OrderDate", "ne", dt);
var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C");
var p3 = breeze.Predicate.create("Freight", ">", 100);
var newPred = breeze.Predicate.and(p1, p2, p3);
var preds = [p1, p2, p3];
var newPred = breeze.Predicate.and(preds);
var p1 = breeze.Predicate.create("Freight", "gt", 100);
var predArgs: any[] = ["Freight", "gt", 100];
var p1 = breeze.Predicate.create(predArgs);
var p1 = new breeze.Predicate("Freight", "gt", 100);
var p1 = new breeze.Predicate("CompanyName", "StartsWith", "B");
if (breeze.Predicate.isPredicate(p1)) { }
var p1 = breeze.Predicate.create("Freight", "gt", 100);
var not_p1 = breeze.Predicate.not(p1);
var not_p1 = p1.not();
var not_p1 = breeze.Predicate.create("Freight", "le", 100);
var dt = new Date(88, 9, 12);
var p1 = breeze.Predicate.create("OrderDate", "ne", dt);
var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C");
var p3 = breeze.Predicate.create("Freight", ">", 100);
var newPred = breeze.Predicate.or(p1, p2, p3);
var preds = [p1, p2, p3];
var newPred = breeze.Predicate.or(preds);
var dt = new Date(88, 9, 12);
var p1 = breeze.Predicate.create("OrderDate", "ne", dt);
var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C");
var p3 = breeze.Predicate.create("Freight", ">", 100);
var newPred = p1.and(p2, p3);
var preds = [p2, p3];
var newPred = p1.and(preds);
var p4 = breeze.Predicate.create("ShipCity", "startswith", "F")
.or("Size", "gt", 2000);
}
function test_queryOptions() {
var em1: breeze.EntityManager;
var newQo = new breeze.QueryOptions({ mergeStrategy: breeze.MergeStrategy.OverwriteChanges });
em1.setProperties({ queryOptions: newQo });
var newQo = new breeze.QueryOptions({ mergeStrategy: breeze.MergeStrategy.OverwriteChanges });
newQo.setAsDefault();
var queryOptions = em1.queryOptions.using(breeze.MergeStrategy.PreserveChanges);
var queryOptions = em1.queryOptions.using(breeze.FetchStrategy.FromLocalCache);
var queryOptions = em1.queryOptions.using({ mergeStrategy: breeze.MergeStrategy.OverwriteChanges });
}
function test_validationOptions() {
var newVo = new breeze.ValidationOptions({ validateOnSave: false, validateOnAttach: false });
var em1: breeze.EntityManager;
em1.setProperties({ validationOptions: newVo });
var validationOptions = new breeze.ValidationOptions()
var newOptions = validationOptions.using({ validateOnQuery: true, validateOnSave: false });
newOptions.setAsDefault();
var validationOptions = new breeze.ValidationOptions();
var newOptions = validationOptions.using({ validateOnQuery: true, validateOnSave: false });
}
function test_validator() {
var valFn = function (v) {
if (v == null) return true;
return ( v.substr(0,2)=== "US");
};
var countryValidator = new breeze.Validator("countryIsUS", valFn, {
displayName: "Country",
messageTemplate: "'%displayName%' must start with 'US'"
});
var metadataStore: breeze.MetadataStore;
var custType = <breeze.EntityType> metadataStore.getEntityType("Customer");
var countryProp = custType.getProperty("Country");
countryProp.validators.push(countryValidator);
function isValidZipCode(value) {
var re = /^\d{5}([\-]\d{4})?$/;
return (re.test(value));
}
var valFn = function (v) {
if (v.getProperty("Country") === "USA") {
var postalCode = v.getProperty("PostalCode");
return isValidZipCode(postalCode);
}
return true;
};
var zipCodeValidator = new breeze.Validator("zipCodeValidator", valFn,
{ messageTemplate: "For the US, this is not a valid PostalCode" });
var em1: breeze.EntityManager;
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
custType.validators.push(zipCodeValidator);
var numericRangeValidator = function (context) {
var valFn = function (v, ctx) {
if (v == null) return true;
if (typeof (v) !== "number") return false;
if (ctx.min != null && v < ctx.min) return false;
if (ctx.max != null && v > ctx.max) return false;
return true;
};
return new breeze.Validator("numericRange", valFn, {
messageTemplate: "'%displayName%' must be an integer between the values of %min% and %max%",
min: context.min,
max: context.max
});
};
freightProperty.validators.push(numericRangeValidator({ min: 100, max: 500 }));
var productType = <breeze.EntityType> em1.metadataStore.getEntityType("Product");
var discontinuedProperty = productType.getProperty("Discontinued");
discontinuedProperty.validators.push(breeze.Validator.bool());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
regionProperty.validators.push(breeze.Validator.byte());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var orderDateProperty = orderType.getProperty("OrderDate");
orderDateProperty.validators.push(breeze.Validator.date());
var v0 = breeze.Validator.maxLength({ maxLength: 5, displayName: "City" });
v0.validate("adasdfasdf");
var errMessage = v0.getMessage();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var customerIdProperty = custType.getProperty("CustomerID");
customerIdProperty.validators.push(breeze.Validator.guid());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
freightProperty.validators.push(breeze.Validator.int16());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
freightProperty.validators.push(breeze.Validator.int32());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
freightProperty.validators.push(breeze.Validator.int64());
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var regionProperty = custType.getProperty("Region");
regionProperty.validators.push(breeze.Validator.maxLength({ maxLength: 5 }));
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
freightProperty.validators.push(breeze.Validator.number());
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var regionProperty = custType.getProperty("Region");
regionProperty.validators.push(breeze.Validator.required());
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var regionProperty = custType.getProperty("Region");
regionProperty.validators.push(breeze.Validator.string());
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var regionProperty = custType.getProperty("Region");
regionProperty.validators.push(breeze.Validator.stringLength({ minLength: 2, maxLength: 5 }));
var validator = breeze.Validator.maxLength({ maxLength: 5, displayName: "City" });
var result = validator.validate("asdf");
var ok = result === null;
result = validator.validate("adasdfasdf");
var errMsg = result.errorMessage;
var context = result.context;
var sameValidator = result.validator;
var valFn = function (v) {
if (v == null) return true;
return (v.substr(0,2) === "US");
};
var countryValidator = new breeze.Validator("countryIsUS", valFn, { displayName: "Country" });
breeze.Validator.messageTemplates["countryIsUS"] = "'%displayName%' must start with 'US'";
}
function test_demo() {
var manager = new breeze.EntityManager('api/northwind');
var query = new breeze.EntityQuery()
.from("Employees");
manager.executeQuery(query).then(function (data) { });
}
+779
View File
@@ -0,0 +1,779 @@
// Type definitions for Breeze 1.2.7
// Project: http://www.breezejs.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>,
// IdeaBlade <https://github.com/IdeaBlade/Breeze/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Updated March 27 2013 - John Lantz (www.ideablade.com)
declare module breezeCore {
interface ErrorCallback {
(error: Error): void;
}
interface IEnum {
contains(object: any): boolean;
fromName(name: string): EnumSymbol;
getNames(): string[];
getSymbols(): EnumSymbol[];
}
class Enum implements IEnum {
constructor (name: string, methodObj?: any);
addSymbol(propertiesObj?: any): EnumSymbol;
contains(object: any): boolean;
fromName(name: string): EnumSymbol;
getNames(): string[];
getSymbols(): EnumSymbol[];
static isSymbol(object: any): boolean;
seal(): void;
}
class EnumSymbol {
parentEnum: IEnum;
getName(): string;
toString(): string;
}
class Event {
constructor (name: string, publisher: any, defaultErrorCallback?: ErrorCallback);
static enable(eventName: string, target: any): void;
static enable(eventName: string, target: any, isEnabled: boolean): void;
static enable(eventName: string, target: any, isEnabled: Function): void;
static isEnabled(eventName: string, target: any): boolean;
publish(data: any, publishAsync?: boolean, errorCallback?: ErrorCallback): void;
publishAsync(data: any, errorCallback?: ErrorCallback): void;
subscribe(callback?: (data: any) => void ): number;
unsubscribe(unsubKey: number): boolean;
}
}
declare module breeze {
interface Entity {
entityAspect: EntityAspect;
entityType: EntityType;
}
interface ComplexObject {
complexAspect: ComplexAspect;
complexType: ComplexType;
}
interface IProperty {
name: string;
parentEntityType: EntityType;
validators: Validator[];
isDataProperty: boolean;
isNavigationProperty: boolean;
}
interface IStructuralType {
complexProperties: DataProperty[];
dataProperties: DataProperty[];
name: string;
namespace: string;
shortName: string;
unmappedProperties: DataProperty[];
validators: Validator[];
}
class AutoGeneratedKeyType {
static Identity: AutoGeneratedKeyType;
static KeyGenerator: AutoGeneratedKeyType;
static None: AutoGeneratedKeyType;
}
class ComplexAspect {
complexObject: ComplexObject;
entityAspect: EntityAspect;
parent: Object;
parentProperty: DataProperty;
propertyPath: string;
originalValues: Object;
}
class ComplexType implements IStructuralType {
complexProperties: DataProperty[];
dataProperties: DataProperty[];
name: string;
namespace: string;
shortName: string;
unmappedProperties: DataProperty[];
validators: Validator[];
addProperty(dataProperty: DataProperty);
getProperties(): DataProperty[];
}
class DataProperty implements IProperty {
complexTypeName: string;
concurrencyMode: string;
dataType: DataTypeSymbol;
defaultValue: any;
fixedLength: boolean;
isComplexProperty: boolean;
isDataProperty: boolean;
isNavigationProperty: boolean;
isNullable: boolean;
isPartOfKey: boolean;
isUnmapped: boolean;
maxLength: number;
name: string;
nameOnServer: string;
parentEntityType: EntityType;
relatedNavigationProperty: NavigationProperty;
validators: Validator[];
constructor (config: DataPropertyOptions);
}
interface DataPropertyOptions {
complexTypeName?: string;
concurrencyMode?: string;
dataType?: DataTypeSymbol;
defaultValue?: any;
fixedLength?: boolean;
isNullable?: boolean;
isPartOfKey?: boolean;
isUnmapped?: boolean;
maxLength?: number;
name?: string;
nameOnServer?: string;
validators?: Validator[];
}
class DataService {
adapterName: string;
hasServerMetadata: boolean;
serviceName: string;
jsonResultsAdapter: JsonResultsAdapter;
constructor(config: DataServiceOptions);
}
interface DataServiceOptions {
adapterName?: string;
hasServerMetadata?: boolean;
serviceName?: string;
jsonResultsAdapter?: JsonResultsAdapter;
}
class JsonResultsAdapter {
name: string;
extractResults: (data: {}) => {};
visitNode: (node: {}, queryContext: QueryContext, nodeContext: NodeContext) => { entityType?: EntityType; nodeId?: any; nodeRefId?: any; ignore?: boolean; };
constructor(config: {
name: string;
extractResults?: (data: {}) => {};
visitNode: (node: {}, queryContext: QueryContext, nodeContext: NodeContext) => { entityType?: EntityType; nodeId?: any; nodeRefId?: any; ignore?: boolean; };
});
}
interface QueryContext {
query: any; // how to also say it could be an EntityQuery or a string
entityManager: EntityManager;
jsonResultsAdapter: JsonResultsAdapter;
mergeStrategy: MergeStrategy;
}
interface NodeContext {
nodeType: string;
}
class DataTypeSymbol extends breezeCore.EnumSymbol {
defaultValue: any;
isNumeric: boolean;
}
interface DataType extends breezeCore.IEnum {
Binary: DataTypeSymbol;
Boolean: DataTypeSymbol;
Byte: DataTypeSymbol;
DateTime: DataTypeSymbol;
Decimal: DataTypeSymbol;
Double: DataTypeSymbol;
Guid: DataTypeSymbol;
Int16: DataTypeSymbol;
Int32: DataTypeSymbol;
Int64: DataTypeSymbol;
Single: DataTypeSymbol;
String: DataTypeSymbol;
Time: DataTypeSymbol;
Undefined: DataTypeSymbol;
toDataType(typeName: string): DataTypeSymbol;
parseDateFromServer(date: any): Date;
}
var DataType: DataType;
class EntityActionSymbol extends breezeCore.EnumSymbol {
}
interface EntityAction extends breezeCore.IEnum {
AcceptChanges: EntityActionSymbol;
Attach: EntityActionSymbol;
AttachOnImport: EntityActionSymbol;
AttachOnQuery: EntityActionSymbol;
Clear: EntityActionSymbol;
Detach: EntityActionSymbol;
EntityStateChange: EntityActionSymbol;
MergeOnImport: EntityActionSymbol;
MergeOnSave: EntityActionSymbol;
MergeOnQuery: EntityActionSymbol;
PropertyChange: EntityActionSymbol;
RejectChanges: EntityActionSymbol;
}
var EntityAction: EntityAction;
class EntityAspect {
entity: Entity;
entityManager: EntityManager;
entityState: EntityStateSymbol;
isBeingSaved: boolean;
originalValues: any;
propertyChanged: PropertyChangedEvent;
validationErrorsChanged: ValidationErrorsChangedEvent;
acceptChanges(): void;
addValidationError(validationError: ValidationError): void;
clearValidationErrors(): void;
getKey(forceRefresh?: boolean): EntityKey;
getValidationErrors(): ValidationError[];
getValidationErrors(property: string): ValidationError[];
getValidationErrors(property: IProperty): ValidationError[];
loadNavigationProperty(navigationProperty: string, callback?: Function, errorCallback?: Function): Promise;
loadNavigationProperty(navigationProperty: NavigationProperty, callback?: Function, errorCallback?: Function): Promise;
rejectChanges(): void;
removeValidationError(validator: Validator): void;
removeValidationError(validator: Validator, property: DataProperty): void;
removeValidationError(validator: Validator, property: NavigationProperty): void;
setDeleted(): void;
setModified(): void;
setUnchanged(): void;
setDetached(): boolean;
validateEntity(): boolean;
validateProperty(property: string, context?: any): boolean;
validateProperty(property: DataProperty, context?: any): boolean;
validateProperty(property: NavigationProperty, context?: any): boolean;
}
class PropertyChangedEventArgs {
entity: Entity;
propertyName: string;
oldValue: any;
newValue: any;
}
class PropertyChangedEvent extends breezeCore.Event {
subscribe(callback?: (data: PropertyChangedEventArgs) => void ): number;
}
class ValidationErrorsChangedEventArgs {
entity: Entity;
added: ValidationError[];
removed: ValidationError[];
}
class ValidationErrorsChangedEvent extends breezeCore.Event {
subscribe(callback?: (data: ValidationErrorsChangedEventArgs) => void ): number;
}
class EntityKey {
constructor (entityType: EntityType, keyValue: any);
constructor (entityType: EntityType, keyValues: any[]);
equals(entityKey: EntityKey): boolean;
static equals(k1: EntityKey, k2: EntityKey): boolean;
}
class EntityManager {
dataService: DataService;
keyGeneratorCtor: Function;
metadataStore: MetadataStore;
queryOptions: QueryOptions;
saveOptions: SaveOptions;
serviceName: string;
validationOptions: ValidationOptions;
entityChanged: EntityChangedEvent;
hasChangesChanged: HasChangesChangedEvent;
constructor (config?: EntityManagerOptions);
constructor (config?: string);
addEntity(entity: Entity): Entity;
attachEntity(entity: Entity, entityState?: EntityStateSymbol): Entity;
clear(): void;
createEmptyCopy(): EntityManager;
createEntity(typeName: string, config?: {}, entityState?: EntityStateSymbol) : Entity;
detachEntity(entity: Entity): boolean;
executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise;
executeQuery(query: EntityQuery, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise;
executeQueryLocally(query: EntityQuery): Entity[];
exportEntities(entities?: Entity[]): string;
fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: boolean): Promise;
fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: boolean): Promise;
fetchEntityByKey(entityKey: EntityKey): Promise;
fetchMetadata(callback?: (schema: any) => void , errorCallback?: breezeCore.ErrorCallback): Promise;
generateTempKeyValue(entity: Entity): any;
getChanges(): Entity[];
getChanges(entityTypeName: string): Entity[];
getChanges(entityTypeNames: string[]): Entity[];
getChanges(entityType: EntityType): Entity[];
getChanges(entityTypes: EntityType[]): Entity[];
getEntities(entityTypeName: string, entityState?: EntityStateSymbol): Entity[];
getEntities(entityTypeNames?: string[], entityState?: EntityStateSymbol): Entity[];
getEntities(entityTypeName?: string, entityStates?: EntityStateSymbol[]): Entity[];
getEntities(entityTypeNames?: string[], entityStates?: EntityStateSymbol[]): Entity[];
getEntities(entityType: EntityType, entityState?: EntityStateSymbol): Entity[];
getEntities(entityTypes?: EntityType[], entityState?: EntityStateSymbol): Entity[];
getEntities(entityType?: EntityType, entityStates?: EntityStateSymbol[]): Entity[];
getEntities(entityTypes?: EntityType[], entityStates?: EntityStateSymbol[]): Entity[];
getEntityByKey(typeName: string, keyValue: any): Entity;
getEntityByKey(typeName: string, keyValues: any[]): Entity;
getEntityByKey(entityKey: EntityKey): Entity;
hasChanges(): boolean;
hasChanges(entityTypeName: string): boolean;
hasChanges(entityTypeNames: string[]): boolean;
hasChanges(entityType: EntityType): boolean;
hasChanges(entityTypes: EntityType[]): boolean;
static importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; }): EntityManager;
importEntities(exportedString: any, config?: { mergeStrategy?: MergeStrategySymbol; }): EntityManager;
rejectChanges(): Entity[];
saveChanges(entities?: Entity[], saveOptions?: SaveOptions, callback?: SaveChangesSuccessCallback, errorCallback?: SaveChangesErrorCallback): Promise;
setProperties(config: EntityManagerProperties): void;
helper: {
unwrapInstance(structObj: Entity, isOData: boolean): any;
unwrapOriginalValues(target: Entity, metadataStore: MetadataStore, isOData: boolean): any;
unwrapChangedValues(target: Entity, metadataStore: MetadataStore, isOData: boolean): any;
getEntityKeyFromRawEntity(rawEntity: any, entityType: EntityType, isClient: boolean): EntityKey;
};
}
interface EntityManagerOptions {
serviceName?: string;
dataService?: DataService;
metadataStore?: MetadataStore;
queryOptions?: QueryOptions;
saveOptions?: SaveOptions;
validationOptions?: ValidationOptions;
keyGeneratorCtor?: Function;
}
interface EntityManagerProperties {
serviceName?: string;
dataService?: DataService;
queryOptions?: QueryOptions;
saveOptions?: SaveOptions;
validationOptions?: ValidationOptions;
keyGeneratorCtor?: Function;
}
interface ExecuteQuerySuccessCallback {
(data: { results: Entity[]; query: EntityQuery; XHR: XMLHttpRequest; }): void;
}
interface ExecuteQueryErrorCallback {
(error: { query: EntityQuery; XHR: XMLHttpRequest; }): void;
}
interface SaveChangesSuccessCallback {
(saveResult: { entities: Entity[]; keyMappings: any; XHR: XMLHttpRequest; }): void;
}
interface SaveChangesErrorCallback {
(error: { XHR: XMLHttpRequest; }): void;
}
class EntityChangedEventArgs {
entity: Entity;
entityAction: EntityActionSymbol;
args: Object;
}
class EntityChangedEvent extends breezeCore.Event {
subscribe(callback?: (data: EntityChangedEventArgs) => void ): number;
}
class HasChangesChangedEventArgs {
entityManager: EntityManager;
hasChanges: boolean;
}
class HasChangesChangedEvent extends breezeCore.Event {
subscribe(callback?: (data: HasChangesChangedEventArgs) => void ): number;
}
class EntityQuery {
entityManager: EntityManager;
orderByClause: OrderByClause;
parameters: Object;
queryOptions: QueryOptions;
resourceName: string;
skipCount: number;
takeCount: number;
wherePredicate: Predicate;
constructor (resourceName?: string);
execute(callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise;
executeLocally(): Entity[];
expand(propertyPaths: string[]): EntityQuery;
expand(propertyPaths: string): EntityQuery;
static from(resourceName: string): EntityQuery;
from(resourceName: string): EntityQuery;
static fromEntities(entity: Entity): EntityQuery;
static fromEntities(entities: Entity[]): EntityQuery;
static fromEntityKey(entityKey: EntityKey): EntityQuery;
static fromEntityNavigation(entity: Entity, navigationProperty: NavigationProperty): EntityQuery;
inlineCount(enabled?: boolean): EntityQuery;
orderBy(propertyPaths: string): EntityQuery;
orderBy(propertyPaths: string[]): EntityQuery;
orderByDesc(propertyPaths: string): EntityQuery;
orderByDesc(propertyPaths: string[]): EntityQuery;
select(propertyPaths: string): EntityQuery;
select(propertyPaths: string[]): EntityQuery;
skip(count: number): EntityQuery;
take(count: number): EntityQuery;
top(count: number): EntityQuery;
toType(typeName: string): EntityQuery;
toType(type: EntityType): EntityQuery;
using(obj: EntityManager): EntityQuery;
using(obj: MergeStrategySymbol): EntityQuery;
using(obj: FetchStrategySymbol): EntityQuery;
using(obj: JsonResultsAdapter): EntityQuery;
where(predicate: Predicate): EntityQuery;
where(property: string, operator: string, value: any): EntityQuery;
where(property: string, operator: FilterQueryOpSymbol, value: any): EntityQuery;
where(predicate: FilterQueryOpSymbol): EntityQuery;
withParameters(params: Object): EntityQuery;
}
interface OrderByClause {
}
class EntityStateSymbol extends breezeCore.EnumSymbol {
isAdded(): boolean;
isAddedModifiedOrDeleted(): boolean;
isDeleted(): boolean;
isDetached(): boolean;
isModified(): boolean;
isUnchanged(): boolean;
isUnchangedOrModified(): boolean;
}
interface EntityState extends breezeCore.IEnum {
Added: EntityStateSymbol;
Deleted: EntityStateSymbol;
Detached: EntityStateSymbol;
Modified: EntityStateSymbol;
Unchanged: EntityStateSymbol;
}
var EntityState: EntityState;
class EntityType implements IStructuralType {
autoGeneratedKeyType: AutoGeneratedKeyType;
complexProperties: DataProperty[];
concurrencyProperties: DataProperty[];
dataProperties: DataProperty[];
defaultResourceName: string;
foreignKeyProperties: DataProperty[];
keyProperties: DataProperty[];
metadataStore: MetadataStore;
name: string;
namespace: string;
navigationProperties: NavigationProperty[];
shortName: string;
unmappedProperties: DataProperty[];
validators: Validator[];
constructor (config: MetadataStore);
constructor (config: EntityTypeOptions);
addProperty(property: IProperty): void;
addValidator(validator: Validator, property?: IProperty): void;
createEntity(initialValues?: Object): Entity;
getDataProperty(propertyName: string): DataProperty;
getEntityCtor(): Function;
getNavigationProperty(propertyName: string): NavigationProperty;
getProperties(): IProperty[];
getProperty(propertyPath: string, throwIfNotFound?: boolean): IProperty;
getPropertyNames(): string[];
setProperties(config: EntityTypeProperties): void;
toString(): string;
}
interface EntityTypeOptions {
shortName?: string;
namespace?: string;
autogeneratedKeyType?: AutoGeneratedKeyType;
defaultResourceName?: string;
}
interface EntityTypeProperties {
autogeneratedKeyType?: AutoGeneratedKeyType;
defaultResourceName?: string;
}
class FetchStrategySymbol extends breezeCore.EnumSymbol {
}
interface FetchStrategy extends breezeCore.IEnum {
FromLocalCache: FetchStrategySymbol;
FromServer: FetchStrategySymbol;
}
var FetchStrategy: FetchStrategy;
class FilterQueryOpSymbol extends breezeCore.EnumSymbol {
}
interface FilterQueryOp extends breezeCore.IEnum {
Contains: FilterQueryOpSymbol;
EndsWith: FilterQueryOpSymbol;
Equals: FilterQueryOpSymbol;
GreaterThan: FilterQueryOpSymbol;
GreaterThanOrEqual: FilterQueryOpSymbol;
LessThan: FilterQueryOpSymbol;
LessThanOrEqual: FilterQueryOpSymbol;
NotEquals: FilterQueryOpSymbol;
StartsWith: FilterQueryOpSymbol;
}
var FilterQueryOp: FilterQueryOp;
class LocalQueryComparisonOptions {
static caseInsensitiveSQL: LocalQueryComparisonOptions;
static defaultInstance: LocalQueryComparisonOptions;
constructor (config: { name?: string; isCaseSensitive?: boolean; usesSql92CompliantStringComparison?: boolean; });
setAsDefault(): void;
}
class MergeStrategySymbol extends breezeCore.EnumSymbol {
}
interface MergeStrategy extends breezeCore.IEnum {
OverwriteChanges: MergeStrategySymbol;
PreserveChanges: MergeStrategySymbol;
}
var MergeStrategy: MergeStrategy;
class MetadataStore {
namingConvention: NamingConvention;
constructor (config?: MetadataStoreOptions);
addDataService(dataService: DataService): void;
addEntityType(structuralType: IStructuralType): void;
exportMetadata(): string;
fetchMetadata(dataService: string, callback?: (data) => void , errorCallback?: breezeCore.ErrorCallback): Promise;
fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: breezeCore.ErrorCallback): Promise;
getDataService(serviceName: string): DataService;
getEntityType(entityTypeName: string, okIfNotFound?: boolean): IStructuralType;
getEntityTypes(): IStructuralType[];
hasMetadataFor(serviceName: string): boolean;
static importMetadata(exportedString: string): MetadataStore;
importMetadata(exportedString: string): MetadataStore;
isEmpty(): boolean;
registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) =>void ): void;
trackUnmappedType(entityCtor: Function, interceptor?: Function);
setEntityTypeForResourceName(resourceName: string, entityTypeOrName: string): void;
}
interface MetadataStoreOptions {
namingConvention?: NamingConvention;
localQueryComparisonOptions?: LocalQueryComparisonOptions;
}
class NamingConvention {
static camelCase: NamingConvention;
static defaultInstance: NamingConvention;
static none: NamingConvention;
name: string;
constructor (config: NamingConventionOptions);
clientPropertyNameToServer(clientPropertyName: string): string;
clientPropertyNameToServer(clientPropertyName: string, property: IProperty): string;
serverPropertyNameToClient(serverPropertyName: string): string;
serverPropertyNameToClient(serverPropertyName: string, property: IProperty): string;
setAsDefault();
}
interface NamingConventionOptions {
serverPropertyNameToClient?: (name: string) => string;
clientPropertyNameToServer?: (name: string) => string;
}
class NavigationProperty implements IProperty {
associationName: string;
entityType: EntityType;
foreignKeyNames: string[];
inverse: NavigationProperty;
isDataProperty: boolean;
isNavigationProperty: boolean;
isScalar: boolean;
name: string;
parentEntityType: EntityType;
relatedDataProperties: DataProperty[];
validators: Validator[];
constructor (config: NavigationPropertyOptions);
}
interface NavigationPropertyOptions {
name?: string;
nameOnServer?: string;
entityTypeName: string;
isScalar?: boolean;
associationName?: string;
foreignKeyNames?: string[];
foreignKeyNamesOnServer?: string[];
validators?: Validator[];
}
class Predicate {
constructor (property: string, operator: string, value: any, valueIsLiteral?: boolean);
constructor (property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: boolean);
and: PredicateMethod;
static and: PredicateMethod;
static create: PredicateMethod;
static isPredicate(o: any): boolean;
static not(predicate: Predicate): Predicate;
not(): Predicate;
static or: PredicateMethod;
or: PredicateMethod;
toFunction(): Function;
toString(): string;
validate(entityType: EntityType): void;
}
interface PredicateMethod {
(predicates: Predicate[]): Predicate;
(...predicates: Predicate[]): Predicate;
(property: string, operator: string, value: any, valueIsLiteral?: boolean): Predicate;
(property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: boolean): Predicate;
}
class Promise {
fail(errorCallback: Function): Promise;
fin(finallyCallback: Function): Promise;
then(callback: Function): Promise;
}
class QueryOptions {
static defaultInstance: QueryOptions;
fetchStrategy: FetchStrategySymbol;
mergeStrategy: MergeStrategySymbol;
constructor (config?: QueryOptionsConfiguration);
setAsDefault(): void;
using(config: QueryOptionsConfiguration): QueryOptions;
using(config: MergeStrategySymbol): QueryOptions;
using(config: FetchStrategySymbol): QueryOptions;
}
interface QueryOptionsConfiguration {
fetchStrategy?: FetchStrategySymbol;
mergeStrategy?: MergeStrategySymbol;
}
class SaveOptions {
allowConcurrentSaves: boolean;
static defaultInstance: SaveOptions;
constructor (config?: { allowConcurrentSaves?: boolean; });
setAsDefault(): SaveOptions;
}
class ValidationError {
context: any;
errorMessage: string;
property: IProperty;
propertyName: string;
validator: Validator;
constructor (validator: Validator, context: any, errorMessage: string);
}
class ValidationOptions {
static defaultInstance: ValidationOptions;
validateOnAttach: boolean;
validateOnPropertyChange: boolean;
validateOnQuery: boolean;
validateOnSave: boolean;
constructor (config?: ValidationOptionsConfiguration);
setAsDefault(): ValidationOptions;
using(config: ValidationOptionsConfiguration): ValidationOptions;
}
interface ValidationOptionsConfiguration {
validateOnAttach?: boolean;
validateOnSave?: boolean;
validateOnQuery?: boolean;
validateOnPropertyChange?: boolean;
}
class Validator {
static messageTemplates: any;
constructor (name: string, validatorFn: ValidatorFunction, context?: any);
static bool(): Validator;
static byte(): Validator;
static date(): Validator;
static duration(): Validator;
getMessage(): string;
static guid(): Validator;
static int16(): Validator;
static int32(): Validator;
static int64(): Validator;
static maxLength(context: { maxLength: number; }): Validator;
static number(): Validator;
static required(): Validator;
static string(): Validator;
static stringLength(context: { maxLength: number; minLength: number; }): Validator;
validate(value: any, context?: any): ValidationError;
}
interface ValidatorFunction {
(value: any, context: ValidatorFunctionContext): void;
}
interface ValidatorFunctionContext {
value: any;
validatorName: string;
displayName: string;
messageTemplate: string;
message?: string;
}
}
+876 -797
View File
File diff suppressed because it is too large Load Diff
+899 -778
View File
File diff suppressed because it is too large Load Diff
+95
View File
@@ -0,0 +1,95 @@
/// <reference path="./browser-harness.d.ts" />
import harness = require('browser-harness');
harness.listen(4500);
harness.listen(4500, function(){});
harness.config.retryMS = 50;
harness.config.timeoutMS = 1500;
var browser = new harness.Browser({ type: 'chrome' });
browser.open('http://localhost:8000/harness.html');
browser.close();
harness.events.on('ready', function(driver){
driver.events.on('console.log', function(text){
console.log(text);
});
driver.events.on('console.warn', function(text){
console.log(text);
});
driver.events.on('console.error', function(text){
console.log(text);
});
driver.events.on('window.onerror', function(text){
console.log(text);
});
driver.setUrl('http://localhost:8000');
driver.setUrl('http://localhost:8000', function(){});
var element = driver.findElement('body');
var html = element.html();
element.addClass('test').click();
driver.findElements('div').removeClass('test');
driver.findVisible('html').findVisible('body').toggleClass('test');
driver.findVisibles('div').hide().show();
driver.find('div').css('color', 'red', function(err, element){
element.hide().show();
});
driver.waitFor(function(){
return false;
});
driver.waitFor(function(){
return false;
}, function(){
});
driver.waitFor({
condition: function(){
},
exec: function(){
},
timeoutMS: 1000
});
driver.exec(function(){
});
driver.exec(function(){}, function(){});
driver.exec({ func: function(){}, args: [] });
driver.exec({ func: function(){}, args: [] }, function(){});
});
harness.events.once('ready', function(driver){
driver.events.once('console.log', function(text){
console.log(text);
});
driver.events.once('console.warn', function(text){
console.log(text);
});
driver.events.once('console.error', function(text){
console.log(text);
});
driver.events.once('window.onerror', function(text){
console.log(text);
});
});
+133
View File
@@ -0,0 +1,133 @@
// Type definitions for Browser Harness
// Project: https://github.com/scriby/browser-harness
// Definitions by: Chris Scribner <https://github.com/scriby>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "browser-harness" {
import events = require("events");
interface HarnessEvents extends events.NodeEventEmitter {
once(event: string, listener: (driver: Driver) => void);
once(event: 'ready', listener: (driver: Driver) => void);
on(event: string, listener: (driver: Driver) => void);
on(event: 'ready', listener: (driver: Driver) => void);
}
interface DriverEvents extends events.NodeEventEmitter {
once(event: string, listener: (text: string) => void);
once(event: 'console.log', listener: (text: string) => void);
once(event: 'console.warn', listener: (text: string) => void);
once(event: 'console.error', listener: (text: string) => void);
once(event: 'window.onerror', listener: (text: string) => void);
on(event: string, listener: (text: string) => void);
on(event: 'console.log', listener: (text: string) => void);
on(event: 'console.warn', listener: (text: string) => void);
on(event: 'console.error', listener: (text: string) => void);
on(event: 'window.onerror', listener: (text: string) => void);
}
export interface Driver {
exec(args: { func: Function; args?: any[]}, callback?: Function) : any;
exec(func: Function, callback?: Function) : any;
setUrl(url: string, callback?: Function);
waitFor(args: { condition: Function; exec?: Function; timeoutMS?: number }, callback?: Function);
waitFor(condition: Function, callback?: Function);
findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy;
findElements(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy;
findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy;
findVisibles(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy;
find(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy;
events: DriverEvents;
}
export interface ElementProxy {
click(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
focus(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
blur(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
val(value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
attr(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
removeAttr(name: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
prop(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
removeProp(name: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
html(value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
text(value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
hasClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
addClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
removeClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
toggleClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
trigger(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
triggerHandler(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
css(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
height(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
innerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
outerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
width(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
innerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
outerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
offset(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
position(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
scrollLeft(value?: number, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
scrollTop(value?: number, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
hide(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
show(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
toggle(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
children(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
closest(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
contents(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
find(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
findElements(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
findVisibles(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
isActionable(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
first(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
has(arg: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
is(arg: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
last(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
next(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
nextAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
nextUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
offsetParent(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
parent(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
parents(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
parentsUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
prev(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
prevAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
prevUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
siblings(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
data(name: string, value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
removeData(name: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
filter(selector: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy
}
export class Browser {
//constructor(args: { type: string; location?: string; args?: string[] });
constructor(args: { type: string; location?: string; args?: any; });
open(harnessUrl: string, serverUrl?: string);
close();
}
export function listen(port: number, callback?: Function)
export var events: HarnessEvents;
export var config: {
timeoutMS: number;
retryMS: number;
};
}
+7
View File
@@ -0,0 +1,7 @@
import browserify = require("browserify");
import fs = require("fs");
var b = browserify();
b.add('./browser/main.js');
b.transform('deamdify');
b.bundle().pipe(fs.createWriteStream('bundle.js'));
+39
View File
@@ -0,0 +1,39 @@
// Type definitions for Browserify
// Project: http://browserify.org/
// Definitions by: Andrew Gaspar <https://github.com/AndrewGaspar/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
interface BrowserifyObject {
add(file: string);
require(file: string, opts?: {
expose: string;
});
bundle(opts?: {
insertGlobals?: boolean;
detectGlobals?: boolean;
debug?: boolean;
standalone?: string;
insertGlobalVars? ;
}, cb?: (err, src) => void): ReadableStream;
external(file: string);
ignore(file: string);
transform(tr: string);
transform(tr: Function);
on(event: string, action: Function): void;
on(event: "file", action: (file, id, parent) => void);
}
declare module "browserify" {
function browserify(): BrowserifyObject;
function browserify(files: string[]): BrowserifyObject;
function browserify(opts: {
entries?: string[];
noParse?: string[];
}): BrowserifyObject;
export = browserify;
}
+55
View File
@@ -0,0 +1,55 @@
/// <reference path="camljs.d.ts" />
var caml = new CamlBuilder().Where()
.Any(
CamlBuilder.Expression().TextField("Email").EqualTo("support@google.com"),
CamlBuilder.Expression().TextField("Email").EqualTo("plus@google.com"),
CamlBuilder.Expression().TextField("Title").BeginsWith("[Google]"),
CamlBuilder.Expression().TextField("Content").Contains("Google")
)
.ToString();
caml = new CamlBuilder().Where()
.UserField("AssignedTo").EqualToCurrentUser()
.Or()
.UserField("AssignedTo").Membership.CurrentUserGroups()
.GroupBy("Category")
.OrderBy("Priority").ThenBy("Title")
.ToString();
caml = new CamlBuilder().Where()
.All(
CamlBuilder.Expression().All(
CamlBuilder.Expression().BooleanField("Enabled").IsTrue(),
CamlBuilder.Expression().UserMultiField("TargetAudience").EqualTo("55").Or().UserMultiField("TargetAudience").EqualTo("66")
),
CamlBuilder.Expression().Any(
CamlBuilder.Expression().TextField("NotificationScope").EqualTo("77"),
CamlBuilder.Expression().TextField("NotificationScope").EqualTo("88").And().TextField("ScopeWebRelativeUrl").EqualTo("99")
)
)
.ToString();
caml = new CamlBuilder().Where()
.LookupIdField("Category").In([2, 3, 10])
.And()
.DateField("ExpirationDate").GreaterThan(CamlBuilder.CamlValues.Now)
.OrderBy("ExpirationDate")
.ToString()
caml = new CamlBuilder().Where().CounterField("ID").In([1, 2, 3]).ToString();
caml = CamlBuilder.Expression()
.All(
CamlBuilder.Expression().DateField("BroadcastExpires").GreaterThanOrEqualTo(CamlBuilder.CamlValues.Today),
CamlBuilder.Expression().Any(
CamlBuilder.Expression().UserField("BroadcastTo").IsInCurrentUserGroups(),
CamlBuilder.Expression().UserField("BroadcastTo").EqualToCurrentUser()
),
CamlBuilder.Expression().DateRangesOverlap(CamlBuilder.DateRangesOverlapType.Year, new Date().toISOString())
)
.ToString();
caml = new CamlBuilder().Where().DateTimeField("Created").GreaterThan(new Date(Date.UTC(2013,0,1))).ToString();
+349
View File
@@ -0,0 +1,349 @@
// Type definitions for camljs
// Project: http://camljs.codeplex.com
// Definitions by: Andrey Markeev <http://markeev.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Sys {
class StringBuilder {
/** Appends a string to the string builder */
public append(s: string): void;
/** Appends a line to the string builder */
public appendLine(s: string): void;
/** Clears the contents of the string builder */
public clear(): void;
/** Indicates wherever the string builder is empty */
public isEmpty(): boolean;
/** Gets the contents of the string builder as a string */
public toString(): string;
}
}
declare module SP {
/** Defines a writer that provides a set of methods to append text in XML format. Use the static SP.XmlWriter.create(sb) Method to create an SP.XmlWriter object with the Sys.StringBuilder object you pass in. */
class XmlWriter {
/** Creates a new instance of the XmlWriter class with the specified string builder. */
static create(sb: Sys.StringBuilder): XmlWriter;
/** Appends a start element tag with the specified name in XML format to the object?s string builder. */
public writeStartElement(tagName: string): void;
/** Appends an element with the specified tag name and value in XML format to the string builder. */
public writeElementString(tagName: string, value: string): void;
/** Appends an end element tag in XML format to the object?s string builder. This method appends the end element tag ?/>? if the start element tag is not closed; otherwise, it appends a full end element tag ?</tagName>? to the string builder. */
public writeEndElement(): void;
/** Appends an attribute with the specified name and value in XML format to the object?s string builder. */
public writeAttributeString(localName: string, value: string): void;
/** This method only appends the name of the attribute. You can append the value of the attribute by calling the SP.XmlWriter.writeString(value) Method, and close the attribute by calling the SP.XmlWriter.writeEndAttribute() Method. */
public writeStartAttribute(localName: string): void;
/** Appends an end of an attribute in XML format to the object?s string builder. */
public writeEndAttribute(): void;
/** Appends the specified value for an element tag or attribute to the object?s string builder. */
public writeString(value: string): void;
/** Appends the specified text to the object?s string builder. */
public writeRaw(xml: string): void;
/** This member is reserved for internal use and is not intended to be used directly from your code. */
public close(): void;
}
}
declare class CamlBuilder {
constructor();
public Where(): CamlBuilder.IFieldExpression;
/** Use for:
1. SPServices CAMLQuery attribute
2. Creating partial expressions
3. In conjunction with Any & All clauses
*/
static Expression(): CamlBuilder.IFieldExpression;
}
declare module CamlBuilder {
interface IView {
Query(): IQuery;
}
interface IQuery {
Where(): IFieldExpression;
}
interface IFinalizable {
/** Get the resulting CAML query as string */
ToString(): string;
}
interface ISortable extends IFinalizable {
/** Adds OrderBy clause to the query
@param fieldInternalName Internal field of the first field by that the data will be sorted (ascending)
@param override This is only necessary for large lists. DON'T use it unless you know what it is for!
@param useIndexForOrderBy This is only necessary for large lists. DON'T use it unless you know what it is for!
*/
OrderBy(fieldInternalName: string, override?: boolean, useIndexForOrderBy?: boolean): ISortedQuery;
/** Adds OrderBy clause to the query (using descending order for the first field).
@param fieldInternalName Internal field of the first field by that the data will be sorted (descending)
@param override This is only necessary for large lists. DON'T use it unless you know what it is for!
@param useIndexForOrderBy This is only necessary for large lists. DON'T use it unless you know what it is for!
*/
OrderByDesc(fieldInternalName: string, override?: boolean, useIndexForOrderBy?: boolean): ISortedQuery;
}
interface IGroupable extends ISortable {
/** Adds GroupBy clause to the query.
@param collapse If true, only information about the groups is retrieved, otherwise items are also retrieved. */
GroupBy(fieldInternalName): IGroupedQuery;
}
interface IExpression extends IGroupable {
/** Adds And clause to the query. */
And(): IFieldExpression;
/** Adds Or clause to the query. */
Or(): IFieldExpression;
}
interface IGroupedQuery extends ISortable {
}
interface ISortedQuery extends IFinalizable {
/** Specifies next order field (ascending) */
ThenBy(fieldInternalName: string): any;
/** Specifies next order field (descending) */
ThenByDesc(fieldInternalName: string): any;
}
interface IFieldExpression {
/** Adds And clauses to the query. Use for creating bracket-expressions in conjuction with CamlBuilder.Expression(). */
All(...conditions: IExpression[]): IExpression;
/** Adds Or clauses to the query. Use for creating bracket-expressions in conjuction with CamlBuilder.Expression(). */
Any(...conditions: IExpression[]): IExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Text */
TextField(internalName: string): ITextFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Boolean */
BooleanField(internalName: string): IBooleanFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is URL */
UrlField(internalName: string): ITextFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Number */
NumberField(internalName: string): INumberFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Counter (usually ID fields) */
CounterField(internalName: string): INumberFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Integer */
IntegerField(internalName: string): INumberFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is User */
UserField(internalName: string): IUserFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Lookup */
LookupField(internalName: string): ILookupFieldExpression;
/** DEPRECATED. Please use LookupField(...).Id() instead */
LookupIdField(internalName: string): INumberFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is LookupMulti */
LookupMultiField(internalName: string): ILookupMultiFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is UserMulti */
UserMultiField(internalName: string): ILookupMultiFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Date */
DateField(internalName: string): IDateTimeFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is DateTime */
DateTimeField(internalName: string): IDateTimeFieldExpression;
/** Used in queries for retrieving recurring calendar events.
NOTICE: DateRangesOverlap with overlapType other than Now cannot be used with SP.CamlQuery, because it doesn't support
CalendarDate and ExpandRecurrence query options. Lists.asmx, however, supports them, so you can still use DateRangesOverlap
with SPServices.
@param overlapType Defines type of overlap: return all events for a day, for a week, for a month or for a year
@param calendarDate Defines date that will be used for determining events for which exactly day/week/month/year will be returned.
This value is ignored for overlapType=Now, but for the other overlap types it is mandatory.
@param eventDateField Internal name of "Start Time" field (default: "EventDate" - all OOTB Calendar lists use this name)
@param endDateField Internal name of "End Time" field (default: "EndDate" - all OOTB Calendar lists use this name)
@param recurrenceIDField Internal name of "Recurrence ID" field (default: "RecurrenceID" - all OOTB Calendar lists use this name)
*/
DateRangesOverlap(overlapType: DateRangesOverlapType, calendarDate: string, eventDateField?: string, endDateField?: string, recurrenceIDField?: string): IExpression;
}
interface IBooleanFieldExpression {
/** Checks whether the value of the field is True */
IsTrue(): IExpression;
/** Checks whether the value of the field is False */
IsFalse(): IExpression;
/** Checks whether the value of the field is equal to the specified value */
EqualTo(value: boolean): IExpression;
/** Checks whether the value of the field is not equal to the specified value */
NotEqualTo(value: boolean): IExpression;
/** Checks whether the value of the field was specified by user */
IsNull(): IExpression;
/** Checks whether the value of the field was not specified by user */
IsNotNull(): IExpression;
}
interface INumberFieldExpression {
/** Checks whether the value of the field is equal to the specified value */
EqualTo(value: number): IExpression;
/** Checks whether the value of the field is not equal to the specified value */
NotEqualTo(value: number): IExpression;
/** Checks whether the value of the field is greater than the specified value */
GreaterThan(value: number): IExpression;
/** Checks whether the value of the field is less than the specified value */
LessThan(value: number): IExpression;
/** Checks whether the value of the field is greater than or equal to the specified value */
GreaterThanOrEqualTo(value: number): IExpression;
/** Checks whether the value of the field is less than or equal to the specified value */
LessThanOrEqualTo(value: number): IExpression;
/** Checks whether the value of the field was specified by user */
IsNull(): IExpression;
/** Checks whether the value of the field was not specified by user */
IsNotNull(): IExpression;
/** Checks whether the value of the field is equal to one of the specified values */
In(arrayOfValues: number[]): IExpression;
}
interface IDateTimeFieldExpression {
/** Checks whether the value of the field was specified by user */
IsNull(): IExpression;
/** Checks whether the value of the field was not specified by user */
IsNotNull(): IExpression;
/** Checks whether the value of the field is equal to the specified value */
EqualTo(value: Date): IExpression;
/** Checks whether the value of the field is not equal to the specified value */
NotEqualTo(value: Date): IExpression;
/** Checks whether the value of the field is greater than the specified value */
GreaterThan(value: Date): IExpression;
/** Checks whether the value of the field is less than the specified value */
LessThan(value: Date): IExpression;
/** Checks whether the value of the field is greater than or equal to the specified value */
GreaterThanOrEqualTo(value: Date): IExpression;
/** Checks whether the value of the field is less than or equal to the specified value */
LessThanOrEqualTo(value: Date): IExpression;
/** Checks whether the value of the field is equal to one of the specified values */
In(arrayOfValues: Date[]): IExpression;
/** Checks whether the value of the field is equal to the specified value.
The datetime value should be defined in ISO 8601 format! */
EqualTo(value: string): IExpression;
/** Checks whether the value of the field is not equal to the specified value.
The datetime value should be defined in ISO 8601 format! */
NotEqualTo(value: string): IExpression;
/** Checks whether the value of the field is greater than the specified value.
The datetime value should be defined in ISO 8601 format! */
GreaterThan(value: string): IExpression;
/** Checks whether the value of the field is less than the specified value.
The datetime value should be defined in ISO 8601 format! */
LessThan(value: string): IExpression;
/** Checks whether the value of the field is greater than or equal to the specified value.
The datetime value should be defined in ISO 8601 format! */
GreaterThanOrEqualTo(value: string): IExpression;
/** Checks whether the value of the field is less than or equal to the specified value.
The datetime value should be defined in ISO 8601 format! */
LessThanOrEqualTo(value: string): IExpression;
/** Checks whether the value of the field is equal to one of the specified values.
The datetime value should be defined in ISO 8601 format! */
In(arrayOfValues: string[]): IExpression;
}
interface ITextFieldExpression {
/** Checks whether the value of the field is equal to the specified value */
EqualTo(value: string): IExpression;
/** Checks whether the value of the field is not equal to the specified value */
NotEqualTo(value: string): IExpression;
/** Checks whether the value of the field contains the specified substring */
Contains(value: string): IExpression;
/** Checks whether the value of the field begins with the specified substring */
BeginsWith(value: string): IExpression;
/** Checks whether the value of the field was specified by user */
IsNull(): IExpression;
/** Checks whether the value of the field was not specified by user */
IsNotNull(): IExpression;
/** Checks whether the value of the field is equal to one of the specified values */
In(arrayOfValues: string[]): IExpression;
}
interface IUserFieldExpression {
/** DEPRECATED. Please use IsIn* methods instead. This property will be removed in next release(!!) */
Membership: IMembership;
/** Checks whether the value of the User field is equal to id of the current user */
EqualToCurrentUser(): IExpression;
/** Checks whether the group specified by the value of the field includes the current user. */
IsInCurrentUserGroups(): IExpression;
/** Checks whether the user specified by the value of the field is member of the specified SharePoint Group. */
IsInSPGroup(groupId: number): IExpression;
/** Checks whether the user specified by the value of the field is member of current SPWeb groups. */
IsInSPWebGroups(): IExpression;
/** Checks whether the user specified by the value of the field is in current SPWeb users. */
IsInSPWebAllUsers(): IExpression;
/** Checks whether the user specified by the value of the field has received the rights to the site directly (not through a group). */
IsInSPWebUsers(): IExpression;
/** Specifies that id of the user will be used for further comparisons. */
Id(): INumberFieldExpression;
/** Specifies that lookup target field value will be used for further comparisons. */
ValueAsText(): ITextFieldExpression;
}
/** DEPRECATED!! Please use UserField(...).IsIn* methods instead. This interface will be removed in the next release */
interface IMembership {
/** DEPRECATED. Please use UserField(...).IsInCurrentUserGroups() instead */
CurrentUserGroups(): IExpression;
/** DEPRECATED. Please use UserField(...).IsInSPGroup() instead */
SPGroup(groupId: number): IExpression;
/** DEPRECATED. Please use UserField(...).IsInSPWeb* methods instead */
SPWeb: IMembershipSPWeb;
}
/** DEPRECATED!! Please use UserField(...).IsInSPWeb* methods instead. This interface will be removed in the next release */
interface IMembershipSPWeb {
/** DEPRECATED. Please use UserField(...).IsInSPWebAllUsers() instead */
AllUsers(): IExpression;
/** DEPRECATED. Please use UserField(...).IsInSPWebUsers() instead */
Users(): IExpression;
/** DEPRECATED. Please use UserField(...).IsInSPWebGroups() instead */
Groups(): IExpression;
}
interface ILookupFieldExpression {
/** Specifies that lookup id value will be used. */
Id(): INumberFieldExpression;
/** Specifies that lookup value will be used and this value is of type Text */
ValueAsText(): ITextFieldExpression;
/** Specifies that lookup value will be used and this value is of type Number */
ValueAsNumber(): INumberFieldExpression;
/** Specifies that lookup value will be used and this value is of type Date */
ValueAsDate(): IDateTimeFieldExpression;
/** Specifies that lookup value will be used and this value is of type DateTime */
ValueAsDateTime(): IDateTimeFieldExpression;
/** Specifies that lookup value will be used and this value is of type Boolean */
ValueAsBoolean(): IBooleanFieldExpression;
}
interface ILookupMultiFieldExpression {
/** Checks whether the value of the field is equal to the specified value */
EqualTo(value: string): IExpression;
/** Checks whether the value of the field is not equal to the specified value */
NotEqualTo(value: string): IExpression;
/** Checks whether the values of the field includes the specified value */
Includes(value): IExpression;
/** Checks whether the values of the field not includes the specified value */
NotIncludes(value): IExpression;
}
enum DateRangesOverlapType {
/** Returns events for today */
Now,
/** Returns events for one day, specified by CalendarDate in QueryOptions */
Day,
/** Returns events for one week, specified by CalendarDate in QueryOptions */
Week,
/** Returns events for one month, specified by CalendarDate in QueryOptions.
Caution: usually also returns few days from previous and next months */
Month,
/** Returns events for one year, specified by CalendarDate in QueryOptions */
Year,
}
class Internal {
static createView(): IView;
static createWhere(): IFieldExpression;
static createExpression(): IFieldExpression;
}
class CamlValues {
/** Dynamic value that represents Id of the current user */
static UserID: string;
/** Dynamic value that represents current date */
static Today: string;
/** Dynamic value that represents current date with specified offset (may be negative) */
static TodayWithOffset(offsetDays: number): string;
static Now: string;
/** Dynamic value that represents a property of the current list */
static ListProperty: {
Created: string;
DefaultViewUrl: string;
Description: string;
EnableSyndication: string;
ItemCount: string;
LinkTitle: string;
MajorVersionLimit: string;
MajorWithMinorVersionsLimit: string;
RelativeFolderPath: string;
Title: string;
ViewSelector: string;
};
/** Dynamic value that represents a property of the current SPWeb */
static ProjectProperty: {
BlogCategoryTitle: string;
BlogPostTitle: string;
Description: string;
RecycleBinEnabled: string;
SiteOwnerName: string;
SiteUrl: string;
Title: string;
Url: string;
};
}
}
+14 -14
View File
@@ -24,7 +24,7 @@ interface Casper {
captureBase64(format: string, area: any);
captureSelector(targetFile: string, selector: string);
clear();
debugHTML(selector?: string, outer?: bool);
debugHTML(selector?: string, outer?: boolean);
debugPage();
die(message: string, status?: number);
download(url: string, target?: string, method?: string, data?: any);
@@ -37,7 +37,7 @@ interface Casper {
fetchText(selector: string);
forward();
log(message: string, level?: string, space?: string);
fill(selector: string, values: any, submit?: bool);
fill(selector: string, values: any, submit?: boolean);
getCurrentUrl(): string;
getElementAttribute(selector: string, attribute: string): string;
getElementBounds(selector: string): ElementBounds;
@@ -45,7 +45,7 @@ interface Casper {
getElementInfo(selector: string): ElementInfo;
getFormValues(selector: string): any;
getGlobal(name: string): any;
getHTML(selector?: string, outer?: bool): string;
getHTML(selector?: string, outer?: boolean): string;
getPageContent(): string;
getTitle(): string;
mouseEvent(type: string, selector: string);
@@ -58,7 +58,7 @@ interface Casper {
sendKeys(selector: string, keys: string, options?: any);
setHttpAuth(username: string, password: string);
start(url?: string, then?: (response: HttpResponse) => void): Casper;
status(asString: bool): any;
status(asString: boolean): any;
then(fn: (self?: Casper) => void);
thenClick(selector: string);
thenEvaluate(fn: Function, ...args: any[]);
@@ -123,12 +123,12 @@ interface ElementInfo {
y: number;
width: number;
height: number;
visible: bool;
visible: boolean;
}
interface CasperOptions {
clientScripts: Array;
exitOnError: bool;
exitOnError: boolean;
httpStatusHandlers: any;
logLevel: string;
onAlert: Function;
@@ -145,10 +145,10 @@ interface CasperOptions {
page: WebPage;
pageSettings: any;
remoteScripts: Array;
safeLogs: bool;
safeLogs: boolean;
stepTimeout: number;
timeout: number;
verbose: bool;
verbose: boolean;
viewportSize: any;
waitTimeout: number;
}
@@ -170,7 +170,7 @@ interface ClientUtils {
getFormValues(selector: string);
mouseEvent(type: string, selector: string);
removeElementsByXPath(expression: string);
sendAJAX(url: string, method?: string, data?: any, async?: bool);
sendAJAX(url: string, method?: string, data?: any, async?: boolean);
visible(selector: string);
}
@@ -180,7 +180,7 @@ interface Colorizer {
}
interface Tester {
assert(condition: bool, message?: string);
assert(condition: boolean, message?: string);
assertDoesntExist(selector: string, message?: string);
assertEquals(testValue: any, expected: any, message?: string);
assertEval(fn: Function, message: string, arguments: any);
@@ -216,7 +216,7 @@ interface Tester {
getPasses(): Cases;
info(message: string);
pass(message: string);
renderResults(exit: bool, status: number, save: string);
renderResults(exit: boolean, status: number, save: string);
}
interface Cases {
@@ -225,7 +225,7 @@ interface Cases {
}
interface Case {
success: bool;
success: boolean;
type: string;
standard: string;
file: string;
@@ -233,8 +233,8 @@ interface Case {
}
interface CaseValues {
subject: bool;
expected: bool;
subject: boolean;
expected: boolean;
}
interface Utils {
+17
View File
@@ -0,0 +1,17 @@
// Type definitions for chai-fuzzy 1.3.0 assert style
// Project: http://chaijs.com/plugins/chai-fuzzy
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../chai/chai-assert.d.ts" />
declare module chai {
interface Assert {
like(act:any, exp:any, msg?:string);
notLike(act:any, exp:any, msg?:string);
containOneLike(act:any, exp:any, msg?:string);
notContainOneLike(act:any, exp:any, msg?:string);
jsonOf(act:any, exp:any, msg?:string);
notJsonOf(act:any, exp:any, msg?:string);
}
}
+25 -2
View File
@@ -1,5 +1,7 @@
/// <reference path="../chai/chai.d.ts" />
/// <reference path="chai-jquery.d.ts" />
/// <reference path="../chai/chai.d.ts" />
/// <reference path="chai-jquery.d.ts" />
// tests taken from https://github.com/chaijs/chai-jquery
declare var $;
var expect = chai.expect;
@@ -17,6 +19,7 @@ function test_css() {
function test_data() {
expect($('#foo')).to.have.data('toggle');
expect($('#foo')).to.have.css('toggle', 'true');
expect($('body')).to.have.css('font-family').match(/sans-serif/);
}
function test_class() {
@@ -59,10 +62,30 @@ function test_disabled() {
expect($('#foo')).to.be.disabled;
}
function test_empty() {
$('.empty').should.be.empty;
expect($('body')).not.to.be.empty;
}
function test_exist() {
$('#exists').should.exist;
expect($('#nonexistent')).not.to.exist;
}
function test_match_selector() {
$('input').should.match('#foo');
}
function test_contain() {
$('body').should.contain('text');
expect($('#content')).to.contain('text');
}
function test_be_selector() {
expect($('#foo')).to.be(':empty');
}
function test_have_selector() {
$('body').should.have('h1');
expect($('#foo')).to.have('div');
}
+14 -14
View File
@@ -7,31 +7,31 @@
declare module chai {
interface NameValueRegexMatcher {
match(value: RegExp): bool;
match(value: RegExp): boolean;
}
interface NameValueMatcher {
(name: string, value?: string): bool;
(name: string, value?: string): boolean;
}
interface Have {
attr: NameValueMatcher;
css: NameValueMatcher;
data: NameValueMatcher;
class(className: string): bool;
id(id: string): bool;
html(html: string): bool;
text(text: string): bool;
value(text: string): bool;
(selector: string): bool;
class(className: string): boolean;
id(id: string): boolean;
html(html: string): boolean;
text(text: string): boolean;
value(text: string): boolean;
(selector: string): boolean;
}
interface Be {
visible: bool;
hidden: bool;
selected: bool;
checked: bool;
disabled: bool;
(selector: string): bool;
visible: boolean;
hidden: boolean;
selected: boolean;
checked: boolean;
disabled: boolean;
(selector: string): boolean;
}
}
@@ -330,7 +330,7 @@ suite('assert', function () {
test('isArray', function () {
assert.isArray([]);
assert.isArray(new Array);
assert.isArray(new Array<any>());
err(function () {
assert.isArray({});
@@ -345,7 +345,7 @@ suite('assert', function () {
}, "expected [] not to be an array");
err(function () {
assert.isNotArray(new Array);
assert.isNotArray(new Array<any>());
}, "expected [] not to be an array");
});
+71 -70
View File
@@ -1,4 +1,4 @@
// Type definitions for chai v1.6.0 assert style
// Type definitions for chai v1.7.0 assert style
// Project: http://chaijs.com/
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -7,107 +7,108 @@ declare module chai
{
interface Assert
{
(express:any, msg?:string);
(express:any, msg?:string):void;
fail(actual?:any, expected?:any, msg?:string, operator?:string);
ok(val:any, msg?:string);
fail(actual?:any, expected?:any, msg?:string, operator?:string):void;
equal(act:any, exp:any, msg?:string);
notEqual(act:any, exp:any, msg?:string);
ok(val:any, msg?:string):void;
notOk(val:any, msg?:string):void;
strictEqual(act:any, exp:any, msg?:string);
notStrictEqual(act:any, exp:any, msg?:string);
equal(act:any, exp:any, msg?:string):void;
notEqual(act:any, exp:any, msg?:string):void;
deepEqual(act:any, exp:any, msg?:string);
notDeepEqual(act:any, exp:any, msg?:string);
strictEqual(act:any, exp:any, msg?:string):void;
notStrictEqual(act:any, exp:any, msg?:string):void;
isTrue(val:any, msg?:string);
isFalse(val:any, msg?:string);
deepEqual(act:any, exp:any, msg?:string):void;
notDeepEqual(act:any, exp:any, msg?:string):void;
isNull(val:any, msg?:string);
isNotNull(val:any, msg?:string);
isTrue(val:any, msg?:string):void;
isFalse(val:any, msg?:string):void;
isUndefined(val:any, msg?:string);
isDefined(val:any, msg?:string);
isNull(val:any, msg?:string):void;
isNotNull(val:any, msg?:string):void;
isFunction(val:any, msg?:string);
isNotFunction(val:any, msg?:string);
isUndefined(val:any, msg?:string):void;
isDefined(val:any, msg?:string):void;
isObject(val:any, msg?:string);
isNotObject(val:any, msg?:string);
isFunction(val:any, msg?:string):void;
isNotFunction(val:any, msg?:string):void;
isArray(val:any, msg?:string);
isNotArray(val:any, msg?:string);
isObject(val:any, msg?:string):void;
isNotObject(val:any, msg?:string):void;
isString(val:any, msg?:string);
isNotString(val:any, msg?:string);
isArray(val:any, msg?:string):void;
isNotArray(val:any, msg?:string):void;
isNumber(val:any, msg?:string);
isNotNumber(val:any, msg?:string);
isString(val:any, msg?:string):void;
isNotString(val:any, msg?:string):void;
isBoolean(val:any, msg?:string);
isNotBoolean(val:any, msg?:string);
isNumber(val:any, msg?:string):void;
isNotNumber(val:any, msg?:string):void;
typeOf(val:any, type:string, msg?:string);
notTypeOf(val:any, type:string, msg?:string);
isBoolean(val:any, msg?:string):void;
isNotBoolean(val:any, msg?:string):void;
instanceOf(val:any, type:Function, msg?:string);
notInstanceOf(val:any, type:Function, msg?:string);
typeOf(val:any, type:string, msg?:string):void;
notTypeOf(val:any, type:string, msg?:string):void;
include(exp:string, inc:any, msg?:string);
include(exp:any[], inc:any, msg?:string);
instanceOf(val:any, type:Function, msg?:string):void;
notInstanceOf(val:any, type:Function, msg?:string):void;
notInclude(exp:string, inc:any, msg?:string);
notInclude(exp:any[], inc:any, msg?:string);
include(exp:string, inc:any, msg?:string):void;
include(exp:any[], inc:any, msg?:string):void;
match(exp:any, re:RegExp, msg?:string);
notMatch(exp:any, re:RegExp, msg?:string);
notInclude(exp:string, inc:any, msg?:string):void;
notInclude(exp:any[], inc:any, msg?:string):void;
property(obj:Object, prop:string, msg?:string);
notProperty(obj:Object, prop:string, msg?:string);
deepProperty(obj:Object, prop:string, msg?:string);
notDeepProperty(obj:Object, prop:string, msg?:string);
match(exp:any, re:RegExp, msg?:string):void;
notMatch(exp:any, re:RegExp, msg?:string):void;
propertyVal(obj:Object, prop:string, val:any, msg?:string);
propertyNotVal(obj:Object, prop:string, val:any, msg?:string);
property(obj:Object, prop:string, msg?:string):void;
notProperty(obj:Object, prop:string, msg?:string):void;
deepProperty(obj:Object, prop:string, msg?:string):void;
notDeepProperty(obj:Object, prop:string, msg?:string):void;
propertyVal(obj:Object, prop:string, val:any, msg?:string):void;
propertyNotVal(obj:Object, prop:string, val:any, msg?:string):void;
deepPropertyVal(obj:Object, prop:string, val:any, msg?:string);
deepPropertyNotVal(obj:Object, prop:string, val:any, msg?:string);
deepPropertyVal(obj:Object, prop:string, val:any, msg?:string):void;
deepPropertyNotVal(obj:Object, prop:string, val:any, msg?:string):void;
lengthOf(exp:any, len:number, msg?:string);
lengthOf(exp:any, len:number, msg?:string):void;
//alias frenzy
throw(fn:Function, msg?:string);
throw(fn:Function, regExp:RegExp);
throw(fn:Function, errType:Function, msg?:string);
throw(fn:Function, errType:Function, regExp:RegExp);
throw(fn:Function, msg?:string):void;
throw(fn:Function, regExp:RegExp):void;
throw(fn:Function, errType:Function, msg?:string):void;
throw(fn:Function, errType:Function, regExp:RegExp):void;
throws(fn:Function, msg?:string);
throws(fn:Function, regExp:RegExp);
throws(fn:Function, errType:Function, msg?:string);
throws(fn:Function, errType:Function, regExp:RegExp);
throws(fn:Function, msg?:string):void;
throws(fn:Function, regExp:RegExp):void;
throws(fn:Function, errType:Function, msg?:string):void;
throws(fn:Function, errType:Function, regExp:RegExp):void;
Throw(fn:Function, msg?:string);
Throw(fn:Function, regExp:RegExp);
Throw(fn:Function, errType:Function, msg?:string);
Throw(fn:Function, errType:Function, regExp:RegExp);
Throw(fn:Function, msg?:string):void;
Throw(fn:Function, regExp:RegExp):void;
Throw(fn:Function, errType:Function, msg?:string):void;
Throw(fn:Function, errType:Function, regExp:RegExp):void;
doesNotThrow(fn:Function, msg?:string);
doesNotThrow(fn:Function, regExp:RegExp);
doesNotThrow(fn:Function, errType:Function, msg?:string);
doesNotThrow(fn:Function, errType:Function, regExp:RegExp);
doesNotThrow(fn:Function, msg?:string):void;
doesNotThrow(fn:Function, regExp:RegExp):void;
doesNotThrow(fn:Function, errType:Function, msg?:string):void;
doesNotThrow(fn:Function, errType:Function, regExp:RegExp):void;
operator(val:any, operator:string, val2:any, msg?:string);
closeTo(act:number, exp:number, delta:number, msg?:string);
operator(val:any, operator:string, val2:any, msg?:string):void;
closeTo(act:number, exp:number, delta:number, msg?:string):void;
sameMembers(set1:any[], set2:any[], msg?:string);
includeMembers(set1:any[], set2:any[], msg?:string);
sameMembers(set1:any[], set2:any[], msg?:string):void;
includeMembers(set1:any[], set2:any[], msg?:string):void;
ifError(val:any, msg?:string);
ifError(val:any, msg?:string):void;
}
//node module
declare var assert:Assert;
var assert:Assert;
}
//browser global
declare var assert:chai.Assert;
declare var assert:chai.Assert;
+728 -55
View File
@@ -1,90 +1,763 @@
/// <reference path="chai.d.ts" />
var expect = chai.expect;
declare var err: Function;
function test_be() {
expect(true).to.be.ok;
function chaiVersion() {
expect(chai).to.have.property('version');
}
function assertion() {
expect('test').to.be.a('string');
expect('foo').to.equal('foo');
}
function _true() {
expect(true).to.be.true;
expect(false).to.not.be.true;
expect(1).to.not.be.true;
err(() => {
expect('test').to.be.true;
}, "expected 'test' to be true")
}
function ok() {
expect(true).to.be.ok;
expect(false).to.not.be.ok;
expect(1).to.be.ok;
expect(0).to.not.be.ok;
err(() => {
expect('').to.be.ok;
}, "expected '' to be truthy");
err(() => {
expect('test').to.not.be.ok;
}, "expected 'test' to be falsy");
}
function _false() {
expect(false).to.be.false;
expect(true).to.not.be.false;
expect(0).to.not.be.false;
err(() => {
expect('').to.be.false;
}, "expected '' to be false")
}
function _null() {
expect(null).to.be.null;
expect(false).to.not.be.null;
err(() => {
expect('').to.be.null;
}, "expected '' to be null")
}
function _undefined() {
expect(undefined).to.be.undefined;
expect([]).to.be.empty;
expect([]).to.be.arguments;
expect({}).to.be.an('object');
expect({}).to.be.an.instanceof(Object);
expect(null).to.not.be.undefined;
err(() => {
expect('').to.be.undefined;
}, "expected '' to be undefined")
}
function exist() {
var foo = 'bar'
, bar;
expect(foo).to.exist;
expect(bar).to.not.exist;
}
function arguments() {
var args = arguments;
expect(args).to.be.arguments;
expect([]).to.not.be.arguments;
expect(args).to.be.an('arguments').and.be.arguments;
expect([]).to.be.an('array').and.not.be.Arguments;
}
function equal() {
var foo;
expect(undefined).to.equal(foo);
}
function _typeof() {
expect('test').to.be.a('string');
err(() => {
expect('test').to.not.be.a('string');
}, "expected 'test' not to be a string");
expect(arguments).to.be.an('arguments');
expect(5).to.be.a('number');
expect(new Number(1)).to.be.a('number');
expect(Number(1)).to.be.a('number');
expect(true).to.be.a('boolean');
expect(new Array()).to.be.a('array');
expect(new Object()).to.be.a('object');
expect({}).to.be.a('object');
expect([]).to.be.a('array');
expect(function () { }).to.be.a('function');
expect(null).to.be.a('null');
err(() => {
expect(5).to.not.be.a('number', 'blah');
}, "blah: expected 5 not to be a number");
}
function _instanceof() {
function Foo() { }
expect(new Foo()).to.be.an.instanceof(Foo);
err(() => {
expect(3).to.an.instanceof(Foo, 'blah');
}, "blah: expected 3 to be an instance of Foo");
}
function within(start, finish) {
expect(5).to.be.within(5, 10);
expect(5).to.be.within(3, 6);
expect(5).to.be.within(3, 5);
expect(5).to.not.be.within(1, 3);
expect('foo').to.have.length.within(2, 4);
expect([1, 2, 3]).to.have.length.within(2, 4);
err(() => {
expect(5).to.not.be.within(4, 6, 'blah');
}, "blah: expected 5 to not be within 4..6", 'blah');
err(() => {
expect(10).to.be.within(50, 100, 'blah');
}, "blah: expected 10 to be within 50..100");
err(() => {
expect('foo').to.have.length.within(5, 7, 'blah');
}, "blah: expected \'foo\' to have a length within 5..7");
err(() => {
expect([1, 2, 3]).to.have.length.within(5, 7, 'blah');
}, "blah: expected [ 1, 2, 3 ] to have a length within 5..7");
}
function above(n) {
expect(5).to.be.above(2);
expect(5).to.be.greaterThan(2);
expect(5).to.not.be.above(5);
expect(5).to.not.be.above(6);
expect('foo').to.have.length.above(2);
expect([1, 2, 3]).to.have.length.above(2);
err(() => {
expect(5).to.be.above(6, 'blah');
}, "blah: expected 5 to be above 6", 'blah');
err(() => {
expect(10).to.not.be.above(6, 'blah');
}, "blah: expected 10 to be at most 6");
err(() => {
expect('foo').to.have.length.above(4, 'blah');
}, "blah: expected \'foo\' to have a length above 4 but got 3");
err(() => {
expect([1, 2, 3]).to.have.length.above(4, 'blah');
}, "blah: expected [ 1, 2, 3 ] to have a length above 4 but got 3");
}
function least(n) {
expect(5).to.be.at.least(2);
expect(5).to.be.at.least(5);
expect(5).to.be.at.gte(5);
expect(5).to.be.at.most(5);
expect(5).to.be.at.lte(5);
expect('').to.be.a('string');
expect(5).to.be.within(1, 6);
expect(5.001).to.be.closeTo(5, 0.5);
expect(5).to.not.be.at.least(6);
expect('foo').to.have.length.of.at.least(2);
expect([1, 2, 3]).to.have.length.of.at.least(2);
err(() => {
expect(5).to.be.at.least(6, 'blah');
}, "blah: expected 5 to be at least 6", 'blah');
err(() => {
expect(10).to.not.be.at.least(6, 'blah');
}, "blah: expected 10 to be below 6");
err(() => {
expect('foo').to.have.length.of.at.least(4, 'blah');
}, "blah: expected \'foo\' to have a length at least 4 but got 3");
err(() => {
expect([1, 2, 3]).to.have.length.of.at.least(4, 'blah');
}, "blah: expected [ 1, 2, 3 ] to have a length at least 4 but got 3");
err(() => {
expect([1, 2, 3, 4]).to.not.have.length.of.at.least(4, 'blah');
}, "blah: expected [ 1, 2, 3, 4 ] to have a length below 4");
}
function test_not() {
expect(5).to.not.be.a('string');
function below(n) {
expect(2).to.be.below(5);
expect(2).to.be.lessThan(5);
expect(2).to.not.be.below(2);
expect(2).to.not.be.below(1);
expect('foo').to.have.length.below(4);
expect([1, 2, 3]).to.have.length.below(4);
err(() => {
expect(6).to.be.below(5, 'blah');
}, "blah: expected 6 to be below 5");
err(() => {
expect(6).to.not.be.below(10, 'blah');
}, "blah: expected 6 to be at least 10");
err(() => {
expect('foo').to.have.length.below(2, 'blah');
}, "blah: expected \'foo\' to have a length below 2 but got 3");
err(() => {
expect([1, 2, 3]).to.have.length.below(2, 'blah');
}, "blah: expected [ 1, 2, 3 ] to have a length below 2 but got 3");
}
function test_deep() {
expect(5).to.deep.equal(5);
expect({ foo: 'bar' }).to.deep.property('foo', 'bar');
function most(n) {
expect(2).to.be.at.most(5);
expect(2).to.be.at.most(2);
expect(2).to.not.be.at.most(1);
expect(2).to.not.be.at.most(1);
expect('foo').to.have.length.of.at.most(4);
expect([1, 2, 3]).to.have.length.of.at.most(4);
err(() => {
expect(6).to.be.at.most(5, 'blah');
}, "blah: expected 6 to be at most 5");
err(() => {
expect(6).to.not.be.at.most(10, 'blah');
}, "blah: expected 6 to be above 10");
err(() => {
expect('foo').to.have.length.of.at.most(2, 'blah');
}, "blah: expected \'foo\' to have a length at most 2 but got 3");
err(() => {
expect([1, 2, 3]).to.have.length.of.at.most(2, 'blah');
}, "blah: expected [ 1, 2, 3 ] to have a length at most 2 but got 3");
err(() => {
expect([1, 2]).to.not.have.length.of.at.most(2, 'blah');
}, "blah: expected [ 1, 2 ] to have a length above 2");
}
function test_have() {
expect({ foo: 'bar' }).to.have.property('foo', 'bar');
expect([]).to.have.length(5);
expect({ foo: 'bar' }).to.have.ownProperty('foo');
expect('foo-bar').to.have.string('bar');
expect({ foo: 'bar', baz: 'qux' }).to.have.keys('foo', 'baz');
function match(regexp) {
expect('foobar').to.match(/^foo/);
expect('foobar').to.not.match(/^bar/);
err(() => {
expect('foobar').to.match(/^bar/i, 'blah')
}, "blah: expected 'foobar' to match /^bar/i");
err(() => {
expect('foobar').to.not.match(/^foo/i, 'blah')
}, "blah: expected 'foobar' not to match /^foo/i");
}
function test_exist() {
var obj = { foo: 'bar' };
expect(obj.foo).to.exist;
function length2(n) {
expect('test').to.have.length(4);
expect('test').to.not.have.length(3);
expect([1, 2, 3]).to.have.length(3);
err(() => {
expect(4).to.have.length(3, 'blah');
}, 'blah: expected 4 to have a property \'length\'');
err(() => {
expect('asd').to.not.have.length(3, 'blah');
}, "blah: expected 'asd' to not have a length of 3");
}
function test_equal() {
expect(5).to.equal(5);
function eql(val) {
expect('test').to.eql('test');
expect({ foo: 'bar' }).to.eql({ foo: 'bar' });
expect(1).to.eql(1);
expect('4').to.not.eql(4);
err(() => {
expect(4).to.eql(3, 'blah');
}, 'blah: expected 4 to deeply equal 3');
}
function test_include() {
expect('foo-bar').to.include('o-b');
expect([1,2,3]).to.include(2);
expect({ foo: 'bar', baz: 'qux' }).to.include.keys('foo', 'baz');
function buffer() {
var Buffer;
expect(new Buffer([1])).to.eql(new Buffer([1]));
expect('foo-bar').to.contain('o-b');
expect([1,2,3]).to.contain(2);
expect({ foo: 'bar', baz: 'qux' }).to.contain.keys('foo', 'baz');
err(() => {
expect(new Buffer([0])).to.eql(new Buffer([1]));
}, 'expected <Buffer 00> to deeply equal <Buffer 01>');
}
function test_throw() {
var foo = {
bar: () => { }
function equal2(val) {
expect('test').to.equal('test');
expect(1).to.equal(1);
err(() => {
expect(4).to.equal(3, 'blah');
}, 'blah: expected 4 to equal 3');
err(() => {
expect('4').to.equal(4, 'blah');
}, "blah: expected '4' to equal 4");
}
function deepEqual(val) {
expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
expect({ foo: 'bar' }).not.to.deep.equal({ foo: 'baz' });
}
function deepEqual2() {
expect(/a/).to.deep.equal(/a/);
expect(/a/).not.to.deep.equal(/b/);
expect(/a/).not.to.deep.equal({});
expect(/a/g).to.deep.equal(/a/g);
expect(/a/g).not.to.deep.equal(/b/g);
expect(/a/i).to.deep.equal(/a/i);
expect(/a/i).not.to.deep.equal(/b/i);
expect(/a/m).to.deep.equal(/a/m);
expect(/a/m).not.to.deep.equal(/b/m);
}
function deepEqual3(Date) {
var a = new Date(1, 2, 3)
, b = new Date(4, 5, 6);
expect(a).to.deep.equal(a);
expect(a).not.to.deep.equal(b);
expect(a).not.to.deep.equal({});
}
function empty() {
function FakeArgs() { };
FakeArgs.prototype.length = 0;
expect('').to.be.empty;
expect('foo').not.to.be.empty;
expect([]).to.be.empty;
expect(['foo']).not.to.be.empty;
expect(new FakeArgs).to.be.empty;
expect({ arguments: 0 }).not.to.be.empty;
expect({}).to.be.empty;
expect({ foo: 'bar' }).not.to.be.empty;
err(() => {
expect('').not.to.be.empty;
}, "expected \'\' not to be empty");
err(() => {
expect('foo').to.be.empty;
}, "expected \'foo\' to be empty");
err(() => {
expect([]).not.to.be.empty;
}, "expected [] not to be empty");
err(() => {
expect(['foo']).to.be.empty;
}, "expected [ \'foo\' ] to be empty");
err(() => {
expect(new FakeArgs).not.to.be.empty;
}, "expected { length: 0 } not to be empty");
err(() => {
expect({ arguments: 0 }).to.be.empty;
}, "expected { arguments: 0 } to be empty");
err(() => {
expect({}).not.to.be.empty;
}, "expected {} not to be empty");
err(() => {
expect({ foo: 'bar' }).to.be.empty;
}, "expected { foo: \'bar\' } to be empty");
}
function property(name) {
expect('test').to.have.property('length');
expect(4).to.not.have.property('length');
expect({ 'foo.bar': 'baz' })
.to.have.property('foo.bar');
expect({ foo: { bar: 'baz' } })
.to.not.have.property('foo.bar');
err(() => {
expect('asd').to.have.property('foo');
}, "expected 'asd' to have a property 'foo'");
err(() => {
expect({ foo: { bar: 'baz' } })
.to.have.property('foo.bar');
}, "expected { foo: { bar: 'baz' } } to have a property 'foo.bar'");
}
function deepProperty(name) {
expect({ 'foo.bar': 'baz' })
.to.not.have.deep.property('foo.bar');
expect({ foo: { bar: 'baz' } })
.to.have.deep.property('foo.bar');
err(() => {
expect({ 'foo.bar': 'baz' })
.to.have.deep.property('foo.bar');
}, "expected { 'foo.bar': 'baz' } to have a deep property 'foo.bar'");
}
function property2(name, val) {
expect('test').to.have.property('length', 4);
expect('asd').to.have.property('constructor', String);
err(() => {
expect('asd').to.have.property('length', 4, 'blah');
}, "blah: expected 'asd' to have a property 'length' of 4, but got 3");
err(() => {
expect('asd').to.not.have.property('length', 3, 'blah');
}, "blah: expected 'asd' to not have a property 'length' of 3");
err(() => {
expect('asd').to.not.have.property('foo', 3, 'blah');
}, "blah: 'asd' has no property 'foo'");
err(() => {
expect('asd').to.have.property('constructor', Number, 'blah');
}, "blah: expected 'asd' to have a property 'constructor' of [Function: Number], but got [Function: String]");
}
function deepProperty2(name, val) {
expect({ foo: { bar: 'baz' } })
.to.have.deep.property('foo.bar', 'baz');
err(() => {
expect({ foo: { bar: 'baz' } })
.to.have.deep.property('foo.bar', 'quux', 'blah');
}, "blah: expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'quux', but got 'baz'");
err(() => {
expect({ foo: { bar: 'baz' } })
.to.not.have.deep.property('foo.bar', 'baz', 'blah');
}, "blah: expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'");
err(() => {
expect({ foo: 5 })
.to.not.have.deep.property('foo.bar', 'baz', 'blah');
}, "blah: { foo: 5 } has no deep property 'foo.bar'");
}
function ownProperty(name) {
expect('test').to.have.ownProperty('length');
expect('test').to.haveOwnProperty('length');
expect({ length: 12 }).to.have.ownProperty('length');
err(() => {
expect({ length: 12 }).to.not.have.ownProperty('length', 'blah');
}, "blah: expected { length: 12 } to not have own property 'length'");
}
function string() {
expect('foobar').to.have.string('bar');
expect('foobar').to.have.string('foo');
expect('foobar').to.not.have.string('baz');
err(() => {
expect(3).to.have.string('baz');
}, "expected 3 to be a string");
err(() => {
expect('foobar').to.have.string('baz', 'blah');
}, "blah: expected 'foobar' to contain 'baz'");
err(() => {
expect('foobar').to.not.have.string('bar', 'blah');
}, "blah: expected 'foobar' to not contain 'bar'");
}
function include() {
expect(['foo', 'bar']).to.include('foo');
expect(['foo', 'bar']).to.include('foo');
expect(['foo', 'bar']).to.include('bar');
expect([1, 2]).to.include(1);
expect(['foo', 'bar']).to.not.include('baz');
expect(['foo', 'bar']).to.not.include(1);
err(() => {
expect(['foo']).to.include('bar', 'blah');
}, "blah: expected [ 'foo' ] to include 'bar'");
err(() => {
expect(['bar', 'foo']).to.not.include('foo', 'blah');
}, "blah: expected [ 'bar', 'foo' ] to not include 'foo'");
}
function keys(array) {
expect({ foo: 1 }).to.have.keys(['foo']);
expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']);
expect({ foo: 1, bar: 2 }).to.have.keys('foo', 'bar');
expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar');
expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('bar', 'foo');
expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('baz');
expect({ foo: 1, bar: 2 }).to.contain.keys('foo');
expect({ foo: 1, bar: 2 }).to.contain.keys('bar', 'foo');
expect({ foo: 1, bar: 2 }).to.contain.keys(['foo']);
expect({ foo: 1, bar: 2 }).to.contain.keys(['bar']);
expect({ foo: 1, bar: 2 }).to.contain.keys(['bar', 'foo']);
expect({ foo: 1, bar: 2 }).to.not.have.keys('baz');
expect({ foo: 1, bar: 2 }).to.not.have.keys('foo', 'baz');
expect({ foo: 1, bar: 2 }).to.not.contain.keys('baz');
expect({ foo: 1, bar: 2 }).to.not.contain.keys('foo', 'baz');
expect({ foo: 1, bar: 2 }).to.not.contain.keys('baz', 'foo');
err(() => {
expect({ foo: 1 }).to.have.keys();
}, "keys required");
err(() => {
expect({ foo: 1 }).to.have.keys([]);
}, "keys required");
err(() => {
expect({ foo: 1 }).to.not.have.keys([]);
}, "keys required");
err(() => {
expect({ foo: 1 }).to.contain.keys([]);
}, "keys required");
err(() => {
expect({ foo: 1 }).to.have.keys(['bar']);
}, "expected { foo: 1 } to have key 'bar'");
err(() => {
expect({ foo: 1 }).to.have.keys(['bar', 'baz']);
}, "expected { foo: 1 } to have keys 'bar', and 'baz'");
err(() => {
expect({ foo: 1 }).to.have.keys(['foo', 'bar', 'baz']);
}, "expected { foo: 1 } to have keys 'foo', 'bar', and 'baz'");
err(() => {
expect({ foo: 1 }).to.not.have.keys(['foo']);
}, "expected { foo: 1 } to not have key 'foo'");
err(() => {
expect({ foo: 1 }).to.not.have.keys(['foo']);
}, "expected { foo: 1 } to not have key 'foo'");
err(() => {
expect({ foo: 1, bar: 2 }).to.not.have.keys(['foo', 'bar']);
}, "expected { foo: 1, bar: 2 } to not have keys 'foo', and 'bar'");
err(() => {
expect({ foo: 1 }).to.not.contain.keys(['foo']);
}, "expected { foo: 1 } to not contain key 'foo'");
err(() => {
expect({ foo: 1 }).to.contain.keys('foo', 'bar');
}, "expected { foo: 1 } to contain keys 'foo', and 'bar'");
}
function chaining() {
var tea = { name: 'chai', extras: ['milk', 'sugar', 'smile'] };
expect(tea).to.have.property('extras').with.lengthOf(3);
err(() => {
expect(tea).to.have.property('extras').with.lengthOf(4);
}, "expected [ 'milk', 'sugar', 'smile' ] to have a length of 4 but got 3");
expect(tea).to.be.a('object').and.have.property('name', 'chai');
}
function _throw() {
// See GH-45: some poorly-constructed custom errors don't have useful names
// on either their constructor or their constructor prototype, but instead
// only set the name inside the constructor itself.
var PoorlyConstructedError = () => {
this.name = 'PoorlyConstructedError';
};
PoorlyConstructedError.prototype = Object.create(Error.prototype);
var specificError = new RangeError('boo');
var goodFn = () => { 1 == 1; }
, badFn = () => { throw new Error('testing'); }
, refErrFn = () => { throw new ReferenceError('hello'); }
, ickyErrFn = () => { throw new PoorlyConstructedError(); }
, specificErrFn = () => { throw specificError; };
expect(goodFn).to.not.throw();
expect(goodFn).to.not.throw(Error);
expect(goodFn).to.not.throw(specificError);
expect(badFn).to.throw();
expect(badFn).to.throw(Error);
expect(badFn).to.not.throw(ReferenceError);
expect(badFn).to.not.throw(specificError);
expect(refErrFn).to.throw();
expect(refErrFn).to.throw(ReferenceError);
expect(refErrFn).to.throw(Error);
expect(refErrFn).to.not.throw(TypeError);
expect(refErrFn).to.not.throw(specificError);
expect(ickyErrFn).to.throw();
expect(ickyErrFn).to.throw(PoorlyConstructedError);
expect(ickyErrFn).to.throw(Error);
expect(ickyErrFn).to.not.throw(specificError);
expect(specificErrFn).to.throw(specificError);
expect(badFn).to.throw(/testing/);
expect(badFn).to.not.throw(/hello/);
expect(badFn).to.throw('testing');
expect(badFn).to.not.throw('hello');
expect(badFn).to.throw(Error, /testing/);
expect(badFn).to.throw(Error, 'testing');
err(() => {
expect(goodFn).to.throw();
}, "expected [Function] to throw an error");
err(() => {
expect(goodFn).to.throw(ReferenceError);
}, "expected [Function] to throw ReferenceError");
err(() => {
expect(goodFn).to.throw(specificError);
}, "expected [Function] to throw [RangeError: boo]");
err(() => {
expect(badFn).to.not.throw();
}, "expected [Function] to not throw an error but [Error: testing] was thrown");
err(() => {
expect(badFn).to.throw(ReferenceError);
}, "expected [Function] to throw 'ReferenceError' but [Error: testing] was thrown");
err(() => {
expect(badFn).to.throw(specificError);
}, "expected [Function] to throw [RangeError: boo] but [Error: testing] was thrown");
err(() => {
expect(badFn).to.not.throw(Error);
}, "expected [Function] to not throw 'Error' but [Error: testing] was thrown");
err(() => {
expect(refErrFn).to.not.throw(ReferenceError);
}, "expected [Function] to not throw 'ReferenceError' but [ReferenceError: hello] was thrown");
err(() => {
expect(badFn).to.throw(PoorlyConstructedError);
}, "expected [Function] to throw 'PoorlyConstructedError' but [Error: testing] was thrown");
err(() => {
expect(ickyErrFn).to.not.throw(PoorlyConstructedError);
}, /^(expected \[Function\] to not throw 'PoorlyConstructedError' but)(.*)(PoorlyConstructedError|\{ Object \()(.*)(was thrown)$/);
err(() => {
expect(ickyErrFn).to.throw(ReferenceError);
}, /^(expected \[Function\] to throw 'ReferenceError' but)(.*)(PoorlyConstructedError|\{ Object \()(.*)(was thrown)$/);
err(() => {
expect(specificErrFn).to.throw(new ReferenceError('eek'));
}, "expected [Function] to throw [ReferenceError: eek] but [RangeError: boo] was thrown");
err(() => {
expect(specificErrFn).to.not.throw(specificError);
}, "expected [Function] to not throw [RangeError: boo]");
err(() => {
expect(badFn).to.not.throw(/testing/);
}, "expected [Function] to throw error not matching /testing/");
err(() => {
expect(badFn).to.throw(/hello/);
}, "expected [Function] to throw error matching /hello/ but got 'testing'");
err(() => {
expect(badFn).to.throw(Error, /hello/, 'blah');
}, "blah: expected [Function] to throw error matching /hello/ but got 'testing'");
err(() => {
expect(badFn).to.throw(Error, 'hello', 'blah');
}, "blah: expected [Function] to throw error including 'hello' but got 'testing'");
}
function respondTo() {
function Foo() {};
var bar = {};
expect(Foo).to.respondTo('bar');
expect(Foo).to.not.respondTo('foo');
expect(Foo).itself.to.respondTo('func');
expect(Foo).itself.not.to.respondTo('bar');
expect(bar).to.respondTo('foo');
err(() => {
expect(Foo).to.respondTo('baz', 'constructor');
}, /^(constructor: expected)(.*)(\[Function: Foo\])(.*)(to respond to \'baz\')$/);
err(() => {
expect(bar).to.respondTo('baz', 'object');
}, /^(object: expected)(.*)(\{ foo: \[Function\] \}|\{ Object \()(.*)(to respond to \'baz\')$/);
}
function satisfy() {
function matcher(num) {
return num === 1;
};
expect(foo.bar).to.throw(new Error);
expect(foo.bar).to.throw('An error');
expect(foo.bar).to.throw(/error/);
expect(1).to.satisfy(matcher);
err(() => {
expect(2).to.satisfy(matcher, 'blah');
}, "blah: expected 2 to satisfy [Function: matcher]");
}
function test_eql() {
var foo = {}
expect(foo).to.eql({});
expect(foo).to.eqls({});
function closeTo() {
expect(1.5).to.be.closeTo(1.0, 0.5);
expect(10).to.be.closeTo(20, 20);
expect(-10).to.be.closeTo(20, 30);
err(() => {
expect(2).to.be.closeTo(1.0, 0.5, 'blah');
}, "blah: expected 2 to be close to 1 +/- 0.5");
err(() => {
expect(-10).to.be.closeTo(20, 29, 'blah');
}, "blah: expected -10 to be close to 20 +/- 29");
}
function test_match() {
expect('foo-bar').to.match(/foo/);
function includeMembers() {
expect([1, 2, 3]).to.include.members([]);
expect([1, 2, 3]).to.include.members([3, 2]);
expect([1, 2, 3]).to.not.include.members([8, 4]);
expect([1, 2, 3]).to.not.include.members([1, 2, 3, 4]);
}
function test_respondTo() {
var foo = {
bar: () => { }
};
function sameMembers() {
expect([5, 4]).to.have.same.members([4, 5]);
expect([5, 4]).to.have.same.members([5, 4]);
expect(foo).to.respondTo('bar');
expect([5, 4]).to.not.have.same.members([]);
expect([5, 4]).to.not.have.same.members([6, 3]);
expect([5, 4]).to.not.have.same.members([5, 4, 2]);
}
function test_satisfy() {
expect(1).to.satisfy((n) => n > 0);
}
function members() {
expect([5, 4]).members([4, 5]);
expect([5, 4]).members([5, 4]);
expect([5, 4]).not.members([]);
expect([5, 4]).not.members([6, 3]);
expect([5, 4]).not.members([5, 4, 2]);
}
+124 -84
View File
@@ -1,122 +1,162 @@
// Type definitions for chai 1.5.0
// Type definitions for chai 1.7.2
// Project: http://chaijs.com/
// Definitions by: Kazi Manzur Rashid <https://github.com/kazimanzurrashid/>
// Definitions by: Jed Hunsaker <https://github.com/jedhunsaker/>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
declare module chai {
interface Equality {
(expected: any, message?: string): bool;
function expect(target: any): Expect;
interface ExpectStatic {
(target: any): Expect;
}
interface Property {
(name: string, value?: any, message?: string): bool;
interface Assertions {
attr(name, value?);
css(name, value?);
data(name, value?);
class(className);
id(id);
html(html);
text(text);
value(value);
visible;
hidden;
selected;
checked;
disabled;
empty;
exist;
}
interface NumberComparer {
(value: number, message?: string): bool;
interface Expect extends LanguageChains, NumericComparison, TypeComparison, Assertions {
not: Expect;
deep: Deep;
a: TypeComparison;
an: TypeComparison;
include: Include;
contain: Include;
ok: Expect;
true: Expect;
false: Expect;
null: Expect;
undefined: Expect;
exist: Expect;
empty: Expect;
arguments: Expect;
Arguments: Expect;
equal: Equal;
equals: Equal;
eq: Equal;
eql: Equal;
eqls: Equal;
property: Property;
ownProperty: OwnProperty;
haveOwnProperty: OwnProperty;
length: Length;
lengthOf: Length;
match(RegularExpression: RegExp, message?: string): Expect;
string(string: string, message?: string): Expect;
keys: Keys;
key(string: string): Expect;
throw: Throw;
throws: Throw;
Throw: Throw;
respondTo(method: string, message?: string): Expect;
itself: Expect;
satisfy(matcher: Function, message?: string): Expect;
closeTo(expected: number, delta: number, message?: string): Expect;
members: Members;
}
interface Eql {
(value: any, message?: string): bool;
}
interface Include {
(value: Object, message?: string): bool;
(value: string, message?: string): bool;
(value: number, message?: string): bool;
keys(...names: string[]): bool;
}
interface Throw {
(constructor: Error, message?: string);
(expected: string, message?: string);
(expected: RegExp, message?: string);
}
interface TypeComparison {
(type: string, message?: string): bool;
instanceof(type: Object, ): bool;
interface LanguageChains {
to: Expect;
be: Expect;
been: Expect;
is: Expect;
that: Expect;
and: Expect;
have: Expect;
with: Expect;
at: Expect;
of: Expect;
same: Expect;
}
interface NumericComparison {
above: NumberComparer;
gt: NumberComparer;
greaterThan: NumberComparer;
least: NumberComparer;
gte: NumberComparer;
below: NumberComparer;
lt: NumberComparer;
lessThan: NumberComparer;
most: NumberComparer;
lte: NumberComparer;
within(start: number, finish: number, message?: string): Expect;
}
interface Length extends NumericComparison {
(value: number, message?: string): bool;
interface NumberComparer {
(value: number, message?: string): Expect;
}
interface TypeComparison {
(type: string, message?: string): Expect;
instanceof: InstanceOf;
instanceOf: InstanceOf;
}
interface InstanceOf {
(constructor: Object, message?: string): Expect;
}
interface Deep {
equal: Equality;
equal: Equal;
property: Property;
}
interface Have {
property: Property;
deep: Deep;
length: Length;
ownProperty(name: string, message?: string): bool;
string(value: string, message?: string): bool;
keys(...values: string[]): bool;
interface Equal {
(value: any, message?: string): Expect;
}
interface At {
least(value: number, message?: string): bool;
gte(value: number, message?: string): bool;
most(value: number, message?: string): bool;
lte(value: number, message?: string): bool;
interface Property {
(name: string, value?: any, message?: string): Expect;
}
interface Be extends NumericComparison {
ok: bool;
true: bool;
false: bool;
null: bool;
undefined: bool;
empty: bool;
arguments: bool;
an: TypeComparison;
at: At;
a(type: string, message?: string): bool;
within(start: number, finish: number, message?: string): bool;
closeTo(expected: number, delta: number, message?: string): bool;
interface OwnProperty {
(name: string, message?: string): Expect;
}
interface To {
be: Be;
not: To;
deep: Deep;
have: Have;
exist: bool;
equal: Equality;
include: Include;
contain: Include;
throw: Throw;
eql: Eql;
eqls: Eql;
match(value: RegExp, message?: string): bool;
respondTo(method: string, message?: string);
satisfy(matcher: Function, message?: string);
interface Length extends LanguageChains, NumericComparison {
(length: number, message?: string): Expect;
}
interface ExpectMatchers {
to: To;
interface Include {
(value: Object, message?: string): Expect;
(value: string, message?: string): Expect;
(value: number, message?: string): Expect;
keys: Keys;
members: Members;
}
var expect : {
(target: any): ExpectMatchers;
interface Keys {
(...keys: string[]): Expect;
(keys: Array): Expect;
}
}
interface Members {
(set: Array, message?: string): Expect;
}
interface Throw {
(): Expect;
(expected: string, message?: string): Expect;
(expected: RegExp, message?: string): Expect;
(constructor: Error, expected?: string, message?: string): Expect;
(constructor: Error, expected?: RegExp, message?: string): Expect;
(constructor: Function, expected?: string, message?: string): Expect;
(constructor: Function, expected?: RegExp, message?: string): Expect;
}
}
@@ -1,65 +1,65 @@
/// <reference path="cheerio.d.ts" />
import cheerio = module("cheerio");
var $ = cheerio.load("<html></html>");
var $el = $('selector');
var $multiEl = $('seletor', 'selector', 'selector');
$el.addClass("class").addClass("test");
$el.hasClass("test");
$el.removeClass("class").removeClass("test");
$el.attr('class');
$el.attr('class', 'test');
$el.removeAttr("class").removeAttr("test");
$el.find("ul").find("> li");
$el.parent().parent();
$el.next().next();
$el.prev().prev();
$el.siblings().siblings();
$el.children().children();
$el.children("li").children("a");
$el.children().each((index, element) => {
$(element).find('t');
});
$el.children().map((index, element) => {
return $(element).find('t');
});
$el.children().filter((index) => {
return $el.children().eq(index).find('t');
});
$el.filter('span').filter('li');
$el.first().last().find('t');
$('div').eq(0).find('b');
$('#id').append("test html", "other html").find('a');
$('#id').prepend("test html", "other html").find('a');
$('#id').after("test html", "other html").find('a');
$('#id').before("test html", "other html").find('a');
$el.remove('div').remove('a');
$('#id').replaceWith('some html').parent();
$('#id').empty().parent();
$el.html();
$el.html("<html></html>").find('div');
$el.text();
$el.text('some text');
$el.toArray();
$el.clone().find('a').parent();
$el.root().find('a');
$el.dom();
/// <reference path="cheerio.d.ts" />
import cheerio = require("cheerio");
var $ = cheerio.load("<html></html>");
var $el = $('selector');
var $multiEl = $('seletor', 'selector', 'selector');
$el.addClass("class").addClass("test");
$el.hasClass("test");
$el.removeClass("class").removeClass("test");
$el.attr('class');
$el.attr('class', 'test');
$el.removeAttr("class").removeAttr("test");
$el.find("ul").find("> li");
$el.parent().parent();
$el.next().next();
$el.prev().prev();
$el.siblings().siblings();
$el.children().children();
$el.children("li").children("a");
$el.children().each((index, element) => {
return $(element).find('t');
});
$el.children().map((index, element) => {
return $(element).find('t');
});
$el.children().filter((index) => {
return $el.children().eq(index).find('t');
});
$el.filter('span').filter('li');
$el.first().last().find('t');
$('div').eq(0).find('b');
$('#id').append("test html", "other html").find('a');
$('#id').prepend("test html", "other html").find('a');
$('#id').after("test html", "other html").find('a');
$('#id').before("test html", "other html").find('a');
$el.remove('div').remove('a');
$('#id').replaceWith('some html').parent();
$('#id').empty().parent();
$el.html();
$el.html("<html></html>").find('div');
$el.text();
$el.text('some text');
$el.toArray();
$el.clone().find('a').parent();
$el.root().find('a');
$el.dom();
+9 -9
View File
@@ -4,10 +4,10 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare interface Cheerio {
interface Cheerio {
addClass(classNames: string): Cheerio;
hasClass(className: string): bool;
hasClass(className: string): boolean;
removeClass(className?: any): Cheerio;
attr(attributeName: string, value: any): Cheerio;
@@ -57,21 +57,21 @@ declare interface Cheerio {
root() : Cheerio;
dom(): any;
contains(container: Element, contained: Element): bool;
isArray(obj: any): bool;
contains(container: Element, contained: Element): boolean;
isArray(obj: any): boolean;
inArray(value: any, array: any[], fromIndex?: number): number;
merge(first: any[], second: any[]): any[];
}
declare interface CheerioOptionsInterface {
ignoreWhitespace?: bool;
xmlMode?: bool;
lowerCaseTags?: bool;
interface CheerioOptionsInterface {
ignoreWhitespace?: boolean;
xmlMode?: boolean;
lowerCaseTags?: boolean;
}
declare interface CheerioStatic {
interface CheerioStatic {
(...selectors: any[]): Cheerio;
(): Cheerio;
}
+4 -4
View File
@@ -7,11 +7,11 @@
/// <reference path="../jquery/jquery.d.ts"/>
interface ChosenOptions {
allow_single_deselect?: bool;
allow_single_deselect?: boolean;
disable_search_threshold?: number;
disable_search?: bool;
search_contains?: bool;
single_backstroke_delete?: bool;
disable_search?: boolean;
search_contains?: boolean;
single_backstroke_delete?: boolean;
max_selected_options?: number;
placeholder_text_multiple?: string;
placeholder_text?: string;
+27
View File
@@ -0,0 +1,27 @@
/// <reference path="chrome-app.d.ts" />
import runtime = chrome.app.runtime;
import cwindow = chrome.app.window;
var createOptions: cwindow.CreateOptions = {
id: "My Window",
bounds: {
left: 0,
top: 0,
width: 640,
height: 480
},
resizable: true
};
//Create new window on app launch
chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchData) {
chrome.app.window.create('app/url', createOptions, function (created_window: cwindow.AppWindow) {
return;
});
});
chrome.app.runtime.onRestarted.addListener(function () { return; });
// Get Current Window
var currentWindow: cwindow.AppWindow = chrome.app.window.current();
+95
View File
@@ -0,0 +1,95 @@
// Type definitions for Chrome packaged application development.
// Project: http://developer.chrome.com/apps/
// Definitions by: Adam Lay <https://github.com/AdamLay>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
////////////////////
// App Runtime
////////////////////
declare module chrome.app.runtime {
interface LaunchData {
id?: string;
items?: LaunchDataItem[];
url?: string;
referrerUrl?: string;
isKioskSession?: boolean;
}
interface LaunchDataItem {
entry: File;
type: string;
}
interface LaunchedEvent {
addListener(callback: (launchData: LaunchData) => void);
}
interface RestartedEvent {
addListener(callback: () => void);
}
var onLaunched: LaunchedEvent;
var onRestarted: RestartedEvent;
}
////////////////////
// App Window
////////////////////
declare module chrome.app.window {
interface Bounds {
left?: number;
top?: number;
width?: number;
height?: number;
}
interface AppWindow {
focus: () => void;
fullscreen: () => void;
isFullscreen: () => boolean;
minimize: () => void;
isMinimized: () => boolean;
maximize: () => void;
isMaximized: () => boolean;
restore: () => void;
moveTo: (left: number, top: number) => void;
resizeTo: (width: number, height: number) => void;
drawAttention: () => void;
clearAttention: () => void;
close: () => void;
show: () => void;
hide: () => void;
getBounds: () => Bounds;
setBounds: (bounds: Bounds) => void;
contentWindow: Window;
}
interface CreateOptions {
id?: string;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
frame?: string; // "none", "chrome"
bounds?: Bounds;
transparentBackground?: boolean;
state?: string; // "normal", "fullscreen", "maximized", "minimized"
hidden?: boolean;
resizable?: boolean;
singleton?: boolean;
}
export function create(url: string, options?: CreateOptions, callback?: (created_window: AppWindow) => void): void;
export function current(): AppWindow;
interface WindowEvent {
addListener(callback: () => void): void;
}
var onBoundsChanged: WindowEvent;
var onClosed: WindowEvent;
var onFullscreened: WindowEvent;
var onMaximized: WindowEvent;
var onMinimized: WindowEvent;
var onRestored: WindowEvent;
}
+155
View File
@@ -0,0 +1,155 @@
/// <reference path="chrome.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../jqueryui/jqueryui.d.ts" />
// https://developer.chrome.com/extensions/examples/api/bookmarks/basic/popup.js
function bookmarksExample() {
$(function () {
$('#search').change(function () {
$('#bookmarks').empty();
dumpBookmarks($('#search').val());
});
});
// Traverse the bookmark tree, and print the folder and nodes.
function dumpBookmarks(query?) {
var bookmarkTreeNodes = chrome.bookmarks.getTree(
function (bookmarkTreeNodes) {
$('#bookmarks').append(dumpTreeNodes(bookmarkTreeNodes, query));
});
}
function dumpTreeNodes(bookmarkNodes, query) {
var list = $('<ul>');
var i;
for (i = 0; i < bookmarkNodes.length; i++) {
list.append(dumpNode(bookmarkNodes[i], query));
}
return list;
}
function dumpNode(bookmarkNode, query) {
if (bookmarkNode.title) {
if (query && !bookmarkNode.children) {
if (String(bookmarkNode.title).indexOf(query) == -1) {
return $('<span></span>');
}
}
var anchor = $('<a>');
anchor.attr('href', bookmarkNode.url);
anchor.text(bookmarkNode.title);
/*
* When clicking on a bookmark in the extension, a new tab is fired with
* the bookmark url.
*/
anchor.click(function () {
chrome.tabs.create({ url: bookmarkNode.url });
});
var span = $('<span>');
var options = bookmarkNode.children ?
$('<span>[<a href="#" id="addlink">Add</a>]</span>') :
$('<span>[<a id="editlink" href="#">Edit</a> <a id="deletelink" ' +
'href="#">Delete</a>]</span>');
var edit = bookmarkNode.children ? $('<table><tr><td>Name</td><td>' +
'<input id="title"></td></tr><tr><td>URL</td><td><input id="url">' +
'</td></tr></table>') : $('<input>');
// Show add and edit links when hover over.
span.hover(function () {
span.append(options);
$('#deletelink').click(function () {
$('#deletedialog').empty().dialog({
autoOpen: false,
title: 'Confirm Deletion',
resizable: false,
height: 140,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
buttons: {
'Yes, Delete It!': function () {
chrome.bookmarks.remove(String(bookmarkNode.id));
span.parent().remove();
$(this).dialog('destroy');
},
Cancel: function () {
$(this).dialog('destroy');
}
}
}).dialog('open');
});
$('#addlink').click(function () {
$('#adddialog').empty().append(edit).dialog({
autoOpen: false,
closeOnEscape: true, title: 'Add New Bookmark', modal: true,
buttons: {
'Add': function () {
chrome.bookmarks.create({
parentId: bookmarkNode.id,
title: $('#title').val(), url: $('#url').val()
});
$('#bookmarks').empty();
$(this).dialog('destroy');
dumpBookmarks();
},
'Cancel': function () {
$(this).dialog('destroy');
}
}
}).dialog('open');
});
$('#editlink').click(function () {
edit.val(anchor.text());
$('#editdialog').empty().append(edit).dialog({
autoOpen: false,
closeOnEscape: true, title: 'Edit Title', modal: true,
show: 'slide', buttons: {
'Save': function () {
chrome.bookmarks.update(String(bookmarkNode.id), {
title: edit.val()
});
anchor.text(edit.val());
options.show();
$(this).dialog('destroy');
},
'Cancel': function () {
$(this).dialog('destroy');
}
}
}).dialog('open');
});
options.fadeIn();
},
// unhover
function () {
options.remove();
}).append(anchor);
}
var li = $(bookmarkNode.title ? '<li>' : '<div>').append(span);
if (bookmarkNode.children && bookmarkNode.children.length > 0) {
li.append(dumpTreeNodes(bookmarkNode.children, query));
}
return li;
}
document.addEventListener('DOMContentLoaded', function () {
dumpBookmarks();
});
}
// https://developer.chrome.com/extensions/examples/api/browserAction/make_page_red/background.js
function pageRedder() {
chrome.browserAction.onClicked.addListener(function (tab) {
// No tabs or host permissions needed!
console.log('Turning ' + tab.url + ' red!');
chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="red"'
});
});
}
// https://developer.chrome.com/extensions/examples/api/browserAction/print/background.js
function printPage() {
chrome.browserAction.onClicked.addListener(function (tab) {
var action_url = "javascript:window.print();";
chrome.tabs.update(tab.id, { url: action_url });
});
}
+247 -231
View File
File diff suppressed because it is too large Load Diff
+8 -5
View File
@@ -1,15 +1,18 @@
/// <reference path="codemirror.d.ts" />
var myCodeMirror = CodeMirror(document.body);
var myCodeMirror: CodeMirror.Editor = CodeMirror(document.body);
var myCodeMirror2 = CodeMirror(document.body, {
var myCodeMirror2: CodeMirror.Editor = CodeMirror(document.body, {
value: "function myScript(){return 100;}\n",
mode: "javascript"
});
var myTextArea;
var myCodeMirror3 = CodeMirror(function (elt) {
var myTextArea: HTMLTextAreaElement;
var myCodeMirror3: CodeMirror.Editor = CodeMirror(function (elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
}, { value: myTextArea.value });
var myCodeMirror4 = CodeMirror.fromTextArea(myTextArea);
var myCodeMirror4: CodeMirror.Editor = CodeMirror.fromTextArea(myTextArea);
var doc: CodeMirror.Doc = new CodeMirror.Doc('text');
var doc2: CodeMirror.Doc = CodeMirror(document.body).getDoc();
+784 -217
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare interface String {
interface String {
bold:string;
italic:string;
underline:string;
+28
View File
@@ -0,0 +1,28 @@
// Type definitions for CometD 2.5.1
// Project: http://cometd.org
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module CometD {
var onListenerException: (exception: any, subscriptionHandle: any, isListener: boolean, message: string) => void;
function init(options: ConfigurationOptions): void;
function addListener(channel: string, listener: (message: any) => void): void;
function removeListener(listener: (message: any) => void): void;
function publish(channel: string, message: any): void;
interface ConfigurationOptions {
url: string;
logLevel?: string;
maxConnections?: number;
backoffIncrement?: number;
maxBackoff?: number;
reverseIncomingExtensions?: boolean;
maxNetworkDelay?: number;
requestHeaders?: any;
appendMessageTypeToURL?: boolean;
autoBatch?: boolean;
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
// [the code below was extracted from the documentation and examples, but does not seem to cover all cases]
//
import program = module("commander");
import program = require("commander");
program
.version('0.0.1')

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