diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c2a12283a..1e64d1cad 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -5,6 +5,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](acc-wizard/acc-wizard.d.ts) [acc-wizard](https://github.com/sathomas/acc-wizard) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](accounting/accounting.d.ts) [accounting.js](http://josscrowcroft.github.io/accounting.js) by [Sergey Gerasimov](https://github.com/gerich-home) * [:link:](ace/ace.d.ts) [Ace Ajax.org Cloud9 Editor](http://ace.ajax.org) by [Diullei Gomes](https://github.com/Diullei) +* [:link:](acorn/acorn.d.ts) [Acorn](https://github.com/marijnh/acorn) by [RReverser](https://github.com/RReverser) * [:link:](add2home/add2home.d.ts) [add2home](http://cubiq.org/add-to-home-screen) by [James Wilkins](http://www.codeplex.com/site/users/view/jamesnw) * [:link:](adm-zip/adm-zip.d.ts) [adm-zip](https://github.com/cthackers/adm-zip) by [John Vilk](https://github.com/jvilk) * [:link:](alertify/alertify.d.ts) [alertify](http://fabien-d.github.io/alertify.js) by [John Jeffery](http://github.com/jjeffery) @@ -12,6 +13,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](amplifyjs/amplifyjs.d.ts) [AmplifyJs](http://amplifyjs.com) by [Jonas Eriksson](https://github.com/joeriks) * [:link:](amqp-rpc/amqp-rpc.d.ts) [amqp-rpc](https://github.com/demchenkoe/node-amqp-rpc) by [Wonshik Kim](https://github.com/wokim) * [:link:](angular-file-upload/angular-file-upload.d.ts) [Angular File Upload](https://github.com/danialfarid/angular-file-upload) by [John Reilly](https://github.com/johnnyreilly) +* [:link:](angular-growl-v2/angular-growl-v2.d.ts) [Angular Growl 2 v.0.7.3](http://janstevens.github.io/angular-growl-2) by [Tadeusz Hucal](https://github.com/mkp05) * [:link:](angularjs/angular.d.ts) [Angular JS](http://angularjs.org) by [Diego Vilar](http://github.com/diegovilar) * [:link:](angularjs/angular-animate.d.ts) [Angular JS (ngAnimate module)](http://angularjs.org) by [Michel Salib](https://github.com/michelsalib), [Adi Dahiya](https://github.com/adidahiya), [Raphael Schweizer](https://github.com/rasch) * [:link:](angularjs/angular-cookies.d.ts) [Angular JS (ngCookies module)](http://angularjs.org) by [Diego Vilar](http://github.com/diegovilar) @@ -41,6 +43,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](any-db/any-db.d.ts) [any-db](https://github.com/grncdr/node-any-db) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](any-db-transaction/any-db-transaction.d.ts) [any-db-transaction](https://github.com/grncdr/node-any-db-transaction) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](cordova/cordova.d.ts) [Apache Cordova](http://cordova.apache.org) by [Microsoft Open Technologies Inc.](http://msopentech.com) +* [:link:](cordova-plugin-email-composer/cordova-plugin-email-composer.d.ts) [Apache Cordova Email Composer plugin](https://github.com/katzer/cordova-plugin-email-composer) by [Dave Taylor](http://davetayls.me) * [:link:](polymer/polymer.app-router.d.ts) [app-router](https://github.com/erikringsmuth/app-router) by [Louis Grignon](https://github.com/lgrignon) * [:link:](appframework/appframework.d.ts) [AppFramework](http://app-framework-software.intel.com) by [kyo_ago](https://github.com/kyo-ago) * [:link:](arbiter/Arbiter.d.ts) [Arbiter.js](http://arbiterjs.com) by [Arash Shakery](https://github.com/arash16) @@ -57,6 +60,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](atpl/atpl.d.ts) [atpl](https://github.com/soywiz/atpl.js) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](auth0/auth0.d.ts) [Auth0.js](http://auth0.com) by [Robert McLaws](https://github.com/advancedrei) * [:link:](auth0.widget/auth0.widget.d.ts) [Auth0Widget.js](http://auth0.com) by [Robert McLaws](https://github.com/advancedrei) +* [:link:](auth0.lock/auth0.lock.d.ts) [Auth0Widget.js](http://auth0.com) by [Robert McLaws](https://github.com/advancedrei) * [:link:](autobahn/autobahn.d.ts) [AutobahnJS](http://autobahn.ws/js) by [Elad Zelingher](https://github.com/darkl) * [:link:](aws-sdk/aws-sdk.d.ts) [aws-sdk](https://github.com/aws/aws-sdk-js) by [midknight41](https://github.com/midknight41) * [:link:](axios/axios.d.ts) [axios](https://github.com/mzabriskie/axios) by [Marcel Buesing](https://github.com/marcelbuesing) @@ -192,7 +196,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](errorhandler/errorhandler.d.ts) [errorhandler](https://github.com/expressjs/errorhandler) by [Santi Albo](https://github.com/santialbo) * [:link:](es6-promise/es6-promise.d.ts) [es6-promise](https://github.com/jakearchibald/ES6-Promise) by [François de Campredon](https://github.com/fdecampredon), [vvakame](https://github.com/vvakame) * [:link:](escape-latex/escape-latex.d.ts) [escape-latex](https://github.com/dangmai/escape-latex) by [Oliver Schneider](https://github.com/olsio) -* [:link:](esprima/esprima.d.ts) [Esprima](http://esprima.org) by [teppeis](https://github.com/teppeis) +* [:link:](esprima/esprima.d.ts) [Esprima](http://esprima.org) by [teppeis](https://github.com/teppeis), [RReverser](https://github.com/RReverser) +* [:link:](estree/estree.d.ts) [ESTree AST specification](https://github.com/estree/estree) by [RReverser](https://github.com/RReverser) * [:link:](event-loop-lag/event-loop-lag.d.ts) [event-loop-lag](https://github.com/pebble/event-loop-lag) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](eventemitter2/eventemitter2.d.ts) [EventEmitter2](https://github.com/asyncly/EventEmitter2) by [ryiwamoto](https://github.com/ryiwamoto) * [:link:](eventemitter3/eventemitter3.d.ts) [EventEmitter3](https://github.com/primus/eventemitter3) by [Yuichi Murata](https://github.com/mrk21) @@ -274,9 +279,9 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](greensock/greensock.d.ts) [GreenSock Animation Platform](http://www.greensock.com/get-started-js) by [Robert S](https://github.com/codebelt) * [:link:](gridfs-stream/gridfs-stream.d.ts) [gridfs-stream](https://github.com/aheckmann/gridfs-stream) by [Lior Mualem](https://github.com/liorm) * [:link:](gruntjs/gruntjs.d.ts) [Grunt 0.4.x](http://gruntjs.com) by [Jeff May](https://github.com/jeffmay), [Basarat Ali Syed](https://github.com/basarat) -* [:link:](gsap/Core.d.ts) [GSAP](http://greensock.com) by [VILIC VANE](https://vilic.github.io) -* [:link:](gsap/Ease.d.ts) [GSAP](http://greensock.com) by [VILIC VANE](https://vilic.github.io) * [:link:](gsap/TweenLite.d.ts) [GSAP](http://greensock.com) by [VILIC VANE](https://vilic.github.io) +* [:link:](gsap/Ease.d.ts) [GSAP](http://greensock.com) by [VILIC VANE](https://vilic.github.io) +* [:link:](gsap/Core.d.ts) [GSAP](http://greensock.com) by [VILIC VANE](https://vilic.github.io) * [:link:](gulp/gulp.d.ts) [Gulp v3.8.x](http://gulpjs.com) by [Drew Noakes](https://drewnoakes.com) * [:link:](gulp-autoprefixer/gulp-autoprefixer.d.ts) [gulp-autoprefixer](https://github.com/sindresorhus/gulp-autoprefixer) by [Asana](https://asana.com) * [:link:](gulp-concat/gulp-concat.d.ts) [gulp-concat](http://github.com/wearefractal/gulp-concat) by [Keita Kagurazaka](https://github.com/k-kagurazaka) @@ -302,6 +307,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](hapi/hapi.d.ts) [hapi](http://github.com/spumko/hapi) by [Jason Swearingen](http://github.com/jasonswearingen) * [:link:](hasher/hasher.d.ts) [Hasher.js](https://github.com/millermedeiros/hasher) by [flyfishMT](https://github.com/flyfishMT) * [:link:](hashmap/hashmap.d.ts) [HashMap](https://github.com/flesler/hashmap) by [RafaÅ‚ Wrzeszcz](http://wrzasq.pl) +* [:link:](he/he.d.ts) [he](https://github.com/mathiasbynens/he) by [Simon Edwards](https://github.com/sedwards2009) * [:link:](Headroom/headroom.d.ts) [headroom.js](http://wicky.nillia.ms/headroom.js) by [Jakub Olek](https://github.com/hakubo) * [:link:](heatmap.js/heatmap.d.ts) [heatmap.js](https://github.com/pa7/heatmap.js) by [Yang Guan](https://github.com/lookuptable) * [:link:](hellojs/hellojs.d.ts) [hello.js](http://adodson.com/hello.js) by [Pavel Zika](https://github.com/PavelPZ) @@ -322,6 +328,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](icheck/icheck.d.ts) [iCheck](http://damirfoy.com/iCheck) by [Dániel Tar](https://github.com/qcz) * [:link:](imagemagick/imagemagick.d.ts) [imagemagick](http://github.com/rsms/node-imagemagick) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](imap/imap.d.ts) [imap](https://www.npmjs.com/package/imap) by [Peter Snider](https://github.com/psnider) +* [:link:](imgur-rest-api/imgur-rest-api.d.ts) [Imgur REST API v3](https://api.imgur.com) by [Luke William Westby](http://github.com/lukewestby) * [:link:](impress/impress.d.ts) [Impress.js](https://github.com/bartaz/impress.js) by [Boris Yankov](https://github.com/borisyankov) * [:link:](inflection/inflection.d.ts) [inflection](https://github.com/dreamerslab/node.inflection) by [Shogo Iwano](https://github.com/shiwano) * [:link:](ini/ini.d.ts) [ini](https://github.com/isaacs/ini) by [Marcin PorÄ™bski](https://github.com/marcinporebski) @@ -360,7 +367,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jquery.contextMenu/jquery.contextMenu.d.ts) [jQuery contextMenu](http://medialize.github.com/jQuery-contextMenu) by [Natan Vivo](https://github.com/nvivo) * [:link:](jquery.cookie/jquery.cookie.d.ts) [jQuery Cookie Plugin](https://github.com/carhartl/jquery-cookie) by [Roy Goode](https://github.com/RoyGoode) * [:link:](jquery.cycle2/jquery.cycle2.d.ts) [jQuery Cycle2 version (build 20140216)](http://jquery.malsup.com/cycle2) by [Donny Nadolny](https://github.com/dnadolny) -* [:link:](jquery.dataTables/jquery.dataTables.d.ts) [JQuery DataTables](http://www.datatables.net) by [Armin Sander](https://github.com/pragmatrix) +* [:link:](jquery.dataTables/jquery.dataTables.d.ts) [JQuery DataTables](http://www.datatables.net) by [Kiarash Ghiaseddin](https://github.com/Silver-Connection/DefinitelyTyped), [Omid Rad](https://github.com/omidkrad), [Armin Sander](https://github.com/pragmatrix) * [:link:](jquery.fileupload/jquery.fileupload.d.ts) [jQuery File Upload Plugin](https://github.com/blueimp/jQuery-File-Upload) by [Rob Alarcon](https://github.com/rob-alarcon) * [:link:](jquery.joyride/jquery.joyride.d.ts) [jQuery JoyRide Plugin](https://github.com/zurb/joyride) by [Vincent Bortone](https://github.com/vbortone) * [:link:](jqgrid/jqgrid.d.ts) [jQuery jqgrid Plugin](https://github.com/tonytomov/jqGrid) by [Lokesh Peta](https://github.com/lokeshpeta) @@ -379,6 +386,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts) [jQuery UI DateTimePicker](http://trentrichardson.com/examples/timepicker) by [dougajmcdonald](https://github.com/dougajmcdonald) * [:link:](jquery.ui.layout/jquery.ui.layout.d.ts) [jQuery UI Layout Plug-in](http://layout.jquery-dev.net) by [Steve Fenton](https://github.com/Steve-Fenton) * [:link:](jquery.timepicker/jquery.timepicker.d.ts) [jQuery UI Timepicker](http://fgelinas.com/code/timepicker) by [Anwar Javed](https://github.com/anwarjaved) +* [:link:](jquery-fullscreen/jquery-fullscreen.d.ts) [jquery-fullscreen](https://github.com/kayahr/jquery-fullscreen-plugin) by [Bruno Grieder](https://github.com/bgrieder) * [:link:](jquery-handsontable/jquery-handsontable.d.ts) [jquery-handsontable](http://handsontable.com) by [Ted John](https://github.com/intelorca) * [:link:](jquery.menuaim/jquery.menuaim.d.ts) [jQuery-menu-aim](https://github.com/kamens/jQuery-menu-aim) by [Robert Fonseca-Ensor](http://www.robfe.com) * [:link:](jquery.pjax/jquery.pjax.d.ts) [jquery-pjax](https://github.com/defunkt/jquery-pjax) by [Junle Li](https://github.com/lijunle) @@ -590,28 +598,33 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](xml2js/xml2js.d.ts) [node-xml2js](https://github.com/Leonidas-from-XIV/node-xml2js) by [Michel Salib](https://github.com/michelsalib), [Jason McNeil](https://github.com/jasonrm) * [:link:](node/node.d.ts) [Node.js](http://nodejs.org) by [Microsoft TypeScript](http://typescriptlang.org), [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) * [:link:](restify/restify.d.ts) [node.js REST framework](https://github.com/mcavage/node-restify) by [Bret Little](https://github.com/blittle) -* [:link:](acl/acl-mongodbBackend.d.ts) [node_acl](https://github.com/optimalbits/node_acl) by [Qubo](https://github.com/tkQubo) * [:link:](acl/acl.d.ts) [node_acl](https://github.com/optimalbits/node_acl) by [Qubo](https://github.com/tkQubo) +* [:link:](acl/acl-mongodbBackend.d.ts) [node_acl](https://github.com/optimalbits/node_acl) by [Qubo](https://github.com/tkQubo) * [:link:](acl/acl-redisBackend.d.ts) [node_acl](https://github.com/optimalbits/node_acl) by [Qubo](https://github.com/tkQubo) * [:link:](mdns/mdns.d.ts) [node_mdns](https://github.com/agnat/node_mdns) by [Stefan Steinhart](https://github.com/reppners) * [:link:](node_redis/node_redis.d.ts) [node_redis](https://github.com/mranney/node_redis) by [Boris Yankov](https://github.com/borisyankov) * [:link:](each/each.d.ts) [NodeEach](http://www.adaltas.com/projects/node-each) by [Michael Zabka](https://github.com/misak113) -* [:link:](nodemailer/nodemailer.d.ts) [Nodemailer](https://github.com/andris9/Nodemailer) by [Vincent Bortone](https://github.com/vbortone) +* [:link:](nodemailer/nodemailer.d.ts) [Nodemailer](https://github.com/andris9/Nodemailer) by [Rogier Schouten](https://github.com/rogierschouten) +* [:link:](nodemailer-direct-transport/nodemailer-direct-transport.d.ts) [Nodemailer](https://github.com/andris9/nodemailer-direct-transport) by [Rogier Schouten](https://github.com/rogierschouten) +* [:link:](nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts) [Nodemailer](https://github.com/andris9/nodemailer-smptp-transport) by [Rogier Schouten](https://github.com/rogierschouten) +* [:link:](nodemailer-smtp-pool/nodemailer-smtp-pool.d.ts) [Nodemailer](https://github.com/andris9/nodemailer-smtp-pool) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](nodeunit/nodeunit.d.ts) [nodeunit](https://github.com/caolan/nodeunit) by [Jeff Goddard](https://github.com/jedigo) * [:link:](nomnom/nomnom.d.ts) [nomnom](https://github.com/harthur/nomnom) by [Paul Vick](https://github.com/panopticoncentral) * [:link:](nopt/nopt.d.ts) [nopt](https://github.com/npm/nopt) by [jbondc](https://github.com/jbondc) * [:link:](notifyjs/notifyjs.d.ts) [notify.js](https://github.com/alexgibson/notify.js) by [soundTricker](https://github.com/soundTricker) * [:link:](notify/notify.d.ts) [Notify.js](https://github.com/jpillora/notifyjs) by [Xiaohan Zhang](https://github.com/hellochar) -* [:link:](nouislider/nouislider.d.ts) [nouislider](https://github.com/leongersen/noUiSlider) by [Corey Jepperson](https://github.com/acoreyj) * [:link:](wnumb/wnumb.d.ts) [nouislider](https://github.com/leongersen/wnumb) by [Corey Jepperson](https://github.com/acoreyj) +* [:link:](nouislider/nouislider.d.ts) [nouislider](https://github.com/leongersen/noUiSlider) by [Corey Jepperson](https://github.com/acoreyj) * [:link:](noVNC/noVNC.d.ts) [noVNC](https://github.com/kanaka/noVNC) by [Ken Smith](https://github.com/smithkl42) * [:link:](npm/npm.d.ts) [npm](https://github.com/npm/npm) by [Maxime LUCE](https://github.com/SomaticIT) * [:link:](nprogress/NProgress.d.ts) [NProgress](https://github.com/rstacruz/nprogress) by [Judah Gabriel Himango](http://debuggerdotbreak.wordpress.com) * [:link:](numeraljs/numeraljs.d.ts) [Numeral.js](https://github.com/adamwdraper/Numeral-js) by [Vincent Bortone](https://github.com/vbortone) * [:link:](object-hash/object-hash.d.ts) [object-hash](https://github.com/puleos/object-hash) by [Michael Zabka](https://github.com/misak113) -* [:link:](object-path/object-path.d.ts) [objectPath](https://github.com/mariocasciaro/object-path) by [Paulo Cesar](https://github.com/pocesar) +* [:link:](object-path/object-path.d.ts) [objectPath v0.9.x](https://github.com/mariocasciaro/object-path) by [Paulo Cesar](https://github.com/pocesar) * [:link:](oboe/oboe.d.ts) [oboe](https://github.com/jimhigson/oboe.js) by [Jared Klopper](https://github.com/optical) * [:link:](oclazyload/oclazyload.d.ts) [oc.LazyLoad](https://github.com/ocombe/ocLazyLoad) by [Roland Zwaga](https://github.com/rolandzwaga) +* [:link:](on-finished/on-finished.d.ts) [on-finished](https://github.com/jshttp/on-finished) by [Honza Dvorsky](http://github.com/czechboy0) +* [:link:](onsenui/onsenui.d.ts) [Onsen UI](http://onsen.io) by [Fran Dios](https://github.com/frankdiox) * [:link:](open/open.d.ts) [open](https://github.com/jjrdn/node-open) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](openlayers/openlayers.d.ts) [OpenLayers.js](https://github.com/openlayers/openlayers) by [Ilya Bolkhovsky](https://github.com/bolhovsky) * [:link:](opn/opn.d.ts) [opn](https://github.com/sindresorhus/opn) by [Shinnosuke Watanabe](https://github.com/shinnn) @@ -636,6 +649,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](phantom/phantom.d.ts) [PhantomJS bridge for NodeJS](https://github.com/sgentle/phantomjs-node) by [horiuchi](https://github.com/horiuchi) * [:link:](phantomjs/phantomjs.d.ts) [PhantomJS v1.9.0 API](https://github.com/ariya/phantomjs/wiki/API-Reference) by [Jed Hunsaker](https://github.com/jedhunsaker), [Mike Keesey](https://github.com/keesey) * [:link:](phonegap/phonegap.d.ts) [PhoneGap](http://phonegap.com) by [Boris Yankov](https://github.com/borisyankov), [Dick van den Brink](https://github.com/DickvdBrink) +* [:link:](photoswipe/photoswipe.d.ts) [PhotoSwipe](http://photoswipe.com) by [Xiaohan Zhang](https://github.com/hellochar) * [:link:](physijs/physijs.d.ts) [Physijs](http://chandlerprall.github.io/Physijs) by [Satoru Kimura](https://github.com/gyohk) * [:link:](pickadate/pickadate.d.ts) [pickadate.js](https://github.com/amsul/pickadate.js) by [Adi Dahiya](https://github.com/adidahiya) * [:link:](pixi/pixi.d.ts) [PIXI](https://github.com/GoodBoyDigital/pixi.js) by [xperiments](http://github.com/xperiments) @@ -646,8 +660,11 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](podcast/podcast.d.ts) [podcast](http://github.com/maxnowack/node-podcast) by [Niklas Mollenhauer](https://github.com/nikeee) * [:link:](poly2tri/poly2tri.d.ts) [poly2tri](http://github.com/r3mi/poly2tri.js) by [Elemar Junior](https://github.com/elemarjr) * [:link:](polymer/polymer.d.ts) [polymer](https://github.com/polymer) by [Louis Grignon](https://github.com/lgrignon) +* [:link:](polymer/polymer.paper-dialog.d.ts) [polymer's paper-dialog](https://github.com/Polymer/paper-dialog) by [Louis Grignon](https://github.com/lgrignon) +* [:link:](polymer/polymer.core-overlay.d.ts) [polymer's paper-toast](https://github.com/Polymer/core-selector) by [Louis Grignon](https://github.com/lgrignon) * [:link:](polymer/polymer.paper-toast.d.ts) [polymer's paper-toast](https://github.com/Polymer/paper-toast) by [Louis Grignon](https://github.com/lgrignon) * [:link:](polymer/polymer.core-drawer-panel.d.ts) [polymer's paper-toast](https://github.com/Polymer/core-drawer-panel) by [Louis Grignon](https://github.com/lgrignon) +* [:link:](polymer/polymer.core-selector.d.ts) [polymer's paper-toast](https://github.com/Polymer/core-selector) by [Louis Grignon](https://github.com/lgrignon) * [:link:](popcorn/popcorn.d.ts) [Popcorn](https://github.com/mozilla/popcorn-js) by [grapswiz](https://github.com/grapswiz) * [:link:](pouchDB/pouch.d.ts) [Pouch](http://pouchdb.com) by [Bill Sears](https://github.com/MrBigDog2U) * [:link:](power-assert/power-assert.d.ts) [power-assert](https://github.com/twada/power-assert) by [vvakame](https://github.com/vvakame) @@ -722,6 +739,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](semver/semver.d.ts) [semver](https://github.com/isaacs/node-semver) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](sendgrid/sendgrid.d.ts) [sendgrid](https://github.com/sendgrid/sendgrid-nodejs) by [Maxime LUCE](https://github.com/SomaticIT) * [:link:](sequelize/sequelize.d.ts) [Sequelize 2.0.0 dev13](http://sequelizejs.com) by [samuelneff](https://github.com/samuelneff), [Peter Harris](https://github.com/codeanimal) +* [:link:](on-headers/on-headers.d.ts) [serve-favicon](https://github.com/jshttp/on-headers) by [John Jeffery](https://github.com/jjeffery) * [:link:](serve-favicon/serve-favicon.d.ts) [serve-favicon](https://github.com/expressjs/serve-favicon) by [Uros Smolnik](https://github.com/urossmolnik) * [:link:](serve-static/serve-static.d.ts) [serve-static](https://github.com/expressjs/serve-static) by [Uros Smolnik](https://github.com/urossmolnik) * [:link:](sharedworker/SharedWorker.d.ts) [SharedWorker](http://www.w3.org/TR/workers) by [Toshiya Nakakura](https://github.com/nakakura) @@ -740,6 +758,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](sipml/sipml.d.ts) [SIPml5](http://sipml5.org) by [A. Groenenboom](https://github.com/chookies) * [:link:](sjcl/sjcl.d.ts) [sjcl](http://crypto.stanford.edu/sjcl) by [Eugene Chernyshov](https://github.com/Evgenus) * [:link:](slickgrid/SlickGrid.d.ts) [SlickGrid](https://github.com/mleibman/SlickGrid) by [Josh Baldwin](https://github.com/jbaldwin) +* [:link:](slickgrid/slick.autotooltips.d.ts) [SlickGrid AutoToolTips Plugin](https://github.com/mleibman/SlickGrid) by [Ryo Iwamoto](https://github.com/ryiwamoto) * [:link:](slickgrid/slick.headerbuttons.d.ts) [SlickGrid HeaderButtons Plugin](https://github.com/mleibman/SlickGrid) by [Derek Cicerone](https://github.com/derekcicerone) * [:link:](slickgrid/slick.rowselectionmodel.d.ts) [SlickGrid RowSelectionModel Plugin](https://github.com/mleibman/SlickGrid) by [Derek Cicerone](https://github.com/derekcicerone) * [:link:](smoothie/smoothie.d.ts) [Smoothie Charts](https://github.com/joewalnes/smoothie) by [Drew Noakes](https://drewnoakes.com), [Mike H. Hawley](https://github.com/mikehhawley) @@ -758,6 +777,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](sprintf/sprintf.d.ts) [sprintff](https://github.com/maritz/node-sprintff) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](sharepoint/SharePoint.d.ts) [sptypescript](http://sptypescript.codeplex.com) by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru), [Andrey Markeev](http://markeev.com) * [:link:](sqlite3/sqlite3.d.ts) [sqlite3](https://github.com/mapbox/node-sqlite3) by [Nick Malaguti](https://github.com/nmalaguti) +* [:link:](squirejs/squirejs.d.ts) [Squire](https://github.com/iammerrick/Squire.js) by [Bradley Ayers](https://github.com/bradleyayers) * [:link:](stack-mapper/stack-mapper.d.ts) [stack-mapper](https://github.com/thlorenz/stack-mapper) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](stampit/stampit.d.ts) [stampit](https://github.com/ericelliott/stampit) by [Vasyl Boroviak](https://github.com/koresar) * [:link:](stats/stats.d.ts) [Stats.js r12](http://github.com/mrdoob/stats.js) by [Gregory Dalton](https://github.com/gregolai) @@ -779,6 +799,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](swig/swig.d.ts) [swig](http://github.com/paularmstrong/swig) by [Peter Harris](https://github.com/CodeAnimal), [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](swiper/swiper.d.ts) [Swiper](https://github.com/nolimits4web/Swiper) by [Sebastián Galiano](https://github.com/sgaliano) * [:link:](swipeview/swipeview.d.ts) [SwipeView](http://cubiq.org/swipeview) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](switchery/switchery.d.ts) [switchery](https://github.com/abpetkov/switchery) by [Bruno Grieder](https://github.com/bgrieder) * [:link:](swiz/swiz.d.ts) [swiz](https://github.com/racker/node-swiz) by [Jeff Goddard](https://github.com/jedigo) * [:link:](tape/tape.d.ts) [tape](https://github.com/substack/tape) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](tar/tar.d.ts) [tar](https://github.com/npm/node-tar) by [Maxime LUCE](https://github.com/SomaticIT) @@ -808,7 +829,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](timezonecomplete/timezonecomplete.d.ts) [timezonecomplete](https://github.com/SpiritIT/timezonecomplete) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](tv4/tv4.d.ts) [Tiny Validator tv4](https://github.com/geraintluff/tv4) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](tinycolor/tinycolor.d.ts) [tinycolor](https://github.com/bgrins/TinyColor) by [Mordechai Zuber](https://github.com/M-Zuber) -* [:link:](titanium/titanium.d.ts) [Titanium Movile 3.1.3.GA](http://www.appcelerator.com) by [Airam Rguez](https://github.com/airamrguez) +* [:link:](titanium/titanium.d.ts) [Titanium Mobile](http://www.appcelerator.com) by [Craig Younkins](https://github.com/cyounkins) * [:link:](tmp/tmp.d.ts) [tmp](https://www.npmjs.com/package/tmp) by [Jared Klopper](https://github.com/optical) * [:link:](toastr/toastr.d.ts) [Toastr](https://github.com/CodeSeven/toastr) by [Boris Yankov](https://github.com/borisyankov) * [:link:](sencha_touch/SenchaTouch.d.ts) [Touch](http://www.sencha.com/products/touch) by [Brian Kotek](https://github.com/brian428) @@ -840,6 +861,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](validator/validator.d.ts) [validator.js](https://github.com/chriso/validator.js) by [tgfjt](https://github.com/tgfjt) * [:link:](vega/vega.d.ts) [Vega](http://trifacta.github.io/vega) by [Tom Crockett](http://github.com/pelotom) * [:link:](velocity-animate/velocity-animate.d.ts) [Velocity](http://velocityjs.org) by [Greg Smith](https://github.com/smrq) +* [:link:](vex-js/vex-js.d.ts) [Vex](https://github.com/HubSpot/vex) by [Greg Cohan](https://github.com/gdcohan) * [:link:](videojs/videojs.d.ts) [Video.js](https://github.com/zencoder/video-js) by [Vincent Bortone](https://github.com/vbortone) * [:link:](vimeo/froogaloop.d.ts) [Vimeo](http://developer.vimeo.com/player/js-api) by [Daz Wilkin](https://github.com/DazWilkin) * [:link:](vinyl/vinyl.d.ts) [vinyl](https://github.com/wearefractal/vinyl) by [vvakame](https://github.com/vvakame), [jedmao](https://github.com/jedmao) @@ -853,12 +875,14 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](webmidi/webmidi.d.ts) [Web MIDI API](http://www.w3.org/TR/webmidi) by [Toshiya Nakakura](https://github.com/nakakura) * [:link:](webspeechapi/webspeechapi.d.ts) [Web Speech API](https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html) by [SaschaNaz](https://github.com/saschanaz) * [:link:](webcola/webcola.d.ts) [webcola](https://github.com/tgdwyer/WebCola) by [Qinfeng Chen](https://github.com/qinfchen) +* [:link:](webcomponents.js/webcomponents.js.d.ts) [webcomponents.js](https://github.com/webcomponents/webcomponentsjs) by [Adi Dahiya](https://github.com/adidahiya) * [:link:](webcrypto/WebCrypto.d.ts) [WebCrypto](http://www.w3.org/TR/WebCryptoAPI) by [Lucas Dixon](https://github.com/iislucas) * [:link:](webix/webix.d.ts) [Webix UI](http://webix.com) by [Maksim Kozhukh](http://github.com/mkozhukh) * [:link:](webrtc/MediaStream.d.ts) [WebRTC](http://dev.w3.org/2011/webrtc) by [Ken Smith](https://github.com/smithkl42) * [:link:](websocket/websocket.d.ts) [websocket](https://github.com/Worlize/WebSocket-Node) by [Paul Loyd](https://github.com/loyd) * [:link:](when/when.d.ts) [When](https://github.com/cujojs/when) by [Derek Cicerone](https://github.com/derekcicerone), [Wim Looman](https://github.com/Nemo157) * [:link:](which/which.d.ts) [which](https://github.com/isaacs/node-which) by [vvakame](https://github.com/vvakame) +* [:link:](jquery.window/jquery.window.d.ts) [Window plugin for jQuery](http://fstoke.me/jquery/window) by [Ryan Graham](https://github.com/ryan-codingintrigue) * [:link:](windows-service/windows-service.d.ts) [windows-service](https://bitbucket.org/stephenwvickers/node-windows-service) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](winjs/winjs.d.ts) [WinJS](http://try.buildwinjs.com) by [TypeScript samples](https://www.typescriptlang.org), [Adam Hewitt](https://github.com/adamhewitt627), [Craig Treasure](https://github.com/craigktreasure), [Jeff Fisher](https://github.com/xirzec) * [:link:](winrt/winrt.d.ts) [WinRT](http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx) by [TypeScript samples](https://www.typescriptlang.org) @@ -872,6 +896,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](xpath/xpath.d.ts) [xpath](https://github.com/goto100/xpath) by [Andrew Bradley](https://github.com/cspotcode) * [:link:](xregexp/xregexp.d.ts) [XRegExp](http://xregexp.com) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](xsockets/XSockets.d.ts) [XSockets.NET](http://xsockets.net) by [Jeffery Grajkowski](https://github.com/pushplay) +* [:link:](yamljs/yamljs.d.ts) [yamljs](https://github.com/jeremyfa/yaml.js) by [Tim Jonischkat](http://www.tim-jonischkat.de) * [:link:](yargs/yargs.d.ts) [yargs](https://github.com/chevex/yargs) by [Martin Poelstra](https://github.com/poelstra) * [:link:](yeoman-generator/yeoman-generator.d.ts) [yeoman-generator](https://github.com/yeoman/generator) by [Kentaro Okuno](http://github.com/armorik83) * [:link:](yosay/yosay.d.ts) [yosay](https://github.com/yeoman/yosay) by [Kentaro Okuno](http://github.com/armorik83) diff --git a/acorn/acorn-tests.ts b/acorn/acorn-tests.ts new file mode 100644 index 000000000..1c5cf27ba --- /dev/null +++ b/acorn/acorn-tests.ts @@ -0,0 +1,30 @@ +/// +/// + +import acorn = require('acorn'); + +var token: acorn.Token; +var tokens: acorn.Token[]; +var comment: acorn.Comment; +var comments: acorn.Comment[]; +var program: ESTree.Program; +var any: any; +var string: string; + +// acorn +string = acorn.version; +program = acorn.parse('code'); +program = acorn.parse('code', {range: true, onToken: tokens, onComment: comments}); +program = acorn.parse('code', { + ranges: true, + onToken: (token) => tokens.push(token), + onComment: (isBlock, text, start, end) => { } +}); + +// Token +token = tokens[0]; +string = token.type.label; +any = token.value; + +// Comment +string = comment.value; diff --git a/acorn/acorn.d.ts b/acorn/acorn.d.ts new file mode 100644 index 000000000..eaba47e3b --- /dev/null +++ b/acorn/acorn.d.ts @@ -0,0 +1,67 @@ +// Type definitions for Acorn v1.0.1 +// Project: https://github.com/marijnh/acorn +// Definitions by: RReverser +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module acorn { + var version: string; + function parse(input: string, options?: Options): ESTree.Program; + function parseExpressionAt(input: string, pos: number, options?: Options): ESTree.Expression; + var defaultOptions: Options; + + interface TokenType { + label: string; + keyword: string; + beforeExpr: boolean; + startsExpr: boolean; + isLoop: boolean; + isAssign: boolean; + prefix: boolean; + postfix: boolean; + binop: number; + updateContext: (prevType: TokenType) => any; + } + + interface AbstractToken { + start: number; + end: number; + loc: ESTree.SourceLocation; + range: [number, number]; + } + + interface Token extends AbstractToken { + type: TokenType; + value: any; + } + + interface Comment extends AbstractToken { + type: string; + value: string; + } + + interface Options { + ecmaVersion?: number; + sourceType?: string; + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; + allowReserved?: boolean; + allowReturnOutsideFunction?: boolean; + allowImportExportEverywhere?: boolean; + allowHashBang?: boolean; + locations?: boolean; + onToken?: ((token: Token) => any) | Token[]; + onComment?: ((isBlock: boolean, text: string, start: number, end: number, startLoc?: ESTree.Position, endLoc?: ESTree.Position) => any) | Comment[]; + ranges?: boolean; + program?: ESTree.Program; + sourceFile?: string; + directSourceFile?: string; + preserveParens?: boolean; + plugins?: { [name: string]: Function; }; + } +} + +declare module "acorn" { + export = acorn +} diff --git a/angular-growl-v2/angular-growl-v2-test.ts b/angular-growl-v2/angular-growl-v2-test.ts new file mode 100644 index 000000000..c9297932e --- /dev/null +++ b/angular-growl-v2/angular-growl-v2-test.ts @@ -0,0 +1,53 @@ +/// + +var app = angular.module("ag", ["pascalprecht.translate", "$httpProvider"]); + +app.config((growlProvider:angular.growl.IGrowlProvider, $httpProvider:angular.IHttpProvider) => { + var ttl:angular.growl.IGrowlTTLConfig = { + success: 5000, + error: 4000 + }; + + growlProvider.globalTimeToLive(ttl); + growlProvider.globalTimeToLive(5000); + growlProvider.globalDisableCloseButton(true); + growlProvider.globalDisableIcons(true); + growlProvider.globalReversedOrder(false); + growlProvider.globalDisableCountDown(true); + growlProvider.messageVariableKey("someKey"); + growlProvider.globalInlineMessages(false); + growlProvider.globalPosition("top-center"); + growlProvider.messagesKey("someKey"); + growlProvider.messageTextKey("someKey"); + growlProvider.messageTitleKey("someKey"); + growlProvider.messageSeverityKey("someKey"); + growlProvider.onlyUniqueMessages(false); + + $httpProvider.interceptors.push(growlProvider.serverMessagesInterceptor); +}); + +app.controller("Ctrl", ($scope:angular.IScope, growl:angular.growl.IGrowlService) => { + var config:angular.growl.IGrowlMessageConfig = { + ttl: 5000, + disableCountDown: true, + disableCloseButton: true + }; + + var message = "Some message"; + + growl.warning(message); + growl.warning(message, config); + growl.error(message); + growl.error(message, config); + growl.info(message); + growl.info(message, config); + growl.success(message); + growl.success(message, config); + growl.general(message); + growl.general(message, config); + growl.general(message, config, "error"); + growl.onlyUnique(); + growl.reverseOrder(); + growl.inlineMessages(); + growl.position(); +}); diff --git a/angular-growl-v2/angular-growl-v2.d.ts b/angular-growl-v2/angular-growl-v2.d.ts new file mode 100644 index 000000000..1c324723f --- /dev/null +++ b/angular-growl-v2/angular-growl-v2.d.ts @@ -0,0 +1,211 @@ +// Type definitions for Angular Growl 2 v.0.7.3 +// Project: http://janstevens.github.io/angular-growl-2 +// Definitions by: Tadeusz Hucal +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module angular.growl { + + /** + * Global Time-To-Leave configuration. + */ + interface IGrowlTTLConfig { + success?: number; + error?: number; + warning?: number; + info?: number; + } + + /** + * Custom configuration used in single message call. + */ + interface IGrowlMessageConfig { + title?: string; + ttl?: number; + disableCountDown?: boolean; + disableIcons?: boolean; + disableCloseButton?: boolean; + referenceId?: number; + onclose?: Function; + onopen?: Function; + } + + /** + * Growl message with configuration. + */ + interface IGrowlMessage extends IGrowlMessageConfig { + text: string; + } + + /** + * Growl service provider. + */ + interface IGrowlProvider extends angular.IServiceProvider { + /** + * Pre-defined server error interceptor. + */ + serverMessagesInterceptor: (string|Function)[]; + + /** + * Set default TTL settings. + * @param ttl configuration of TTL for different type of message + */ + globalTimeToLive(ttl: IGrowlTTLConfig): void; + /** + * Set default TTL settings. + * @param ttl ttl in milliseconds + */ + globalTimeToLive(ttl: number): void; + /** + * Set default setting for disabling close button. + * @param disableCloseButton + */ + globalDisableCloseButton(disableCloseButton: boolean): void; + /** + * Set default setting for disabling icons. + * @param disableIcons + */ + globalDisableIcons(disableIcons: boolean): void; + /** + * Set reversing order of displaying new messages. + * @param reverseOrder + */ + globalReversedOrder(reverseOrder: boolean): void + /** + * Set default setting for displaying message disappear countdown. + * @param disableCountDown + */ + globalDisableCountDown(disableCountDown: boolean): void; + /** + * Set default allowance for inline messages. + * @param inline + */ + globalInlineMessages(inline: boolean): void; + /** + * Set default message position. + * @param position + */ + globalPosition(position: string): void; + /** + * Enable/disable displaying only unique messages. + * @param onlyUniqueMessages + */ + onlyUniqueMessages(onlyUniqueMessages: boolean): void; + + /** + * Set key where messages are stored (for http interceptor). + * @param messageVariableKey + */ + messagesKey(messageKey: string): void; + /** + * Set key where message text is stored (for http interceptor). + * @param messageVariableKey + */ + messageTextKey(messageTextKey: string): void; + /** + * Set key where title of message is stored (for http interceptor). + * @param messageVariableKey + */ + messageTitleKey(messageTitleKey: string): void; + /** + * Set key where severity of message is stored (for http interceptor). + * @param messageVariableKey + */ + messageSeverityKey(messageSeverityKey: string): void; + /** + * Set key where variables for message are stored (for http interceptor). + * @param messageVariableKey + */ + messageVariableKey(messageVariableKey: string): void; + } + + /** + * Growl service. + */ + interface IGrowlService { + /** + * Show warning message. + * @param message text to display (or code for angular-translate) + */ + warning(message: string): IGrowlMessage; + /** + * Show warning message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + warning(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show error message. + * @param message text to display (or code for angular-translate) + */ + error(message: string): IGrowlMessage; + /** + * Show error message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + error(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show information message. + * @param message text to display (or code for angular-translate) + */ + info(message: string): IGrowlMessage; + /** + * Show information message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + info(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show success message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + success(message: string): IGrowlMessage; + /** + * Show success message. + * @param message text to display (or code for angular-translate) + */ + success(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show message (generic). + * @param message text to display (or code for angular-translate) + */ + general(message: string): IGrowlMessage; + /** + * Show message (generic). + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + general(message: string, config: IGrowlMessageConfig): IGrowlMessage; + /** + * Show message (generic). + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + * @param severity message severity (error, warning, success, info). + */ + general(message: string, config: IGrowlMessageConfig, severity: string): IGrowlMessage; + + /** + * Get current setting for displaying only unique messages. + */ + onlyUnique(): boolean; + /** + * Get current setting for reversing messages order. + */ + reverseOrder(): boolean; + /** + * Get current allowance for inline messages. + */ + inlineMessages(): boolean; + /** + * Get current messages position. + */ + position(): string; + } +} diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index cf7a20d79..1e3eda18a 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Material 0.8.3+ (ng.material module) +// Type definitions for Angular Material 0.8.3+ (angular.material module) // Project: https://github.com/angular/material // Definitions by: Matt Traynham // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -12,14 +12,14 @@ declare module angular.material { controller?: any; locals?: {[index: string]: any}; targetEvent?: any; - resolve?: {[index: string]: ng.IPromise} + resolve?: {[index: string]: angular.IPromise} controllerAs?: string; parent?: Element; disableParentScroll?: boolean; } interface MDBottomSheetService { - show(options: MDBottomSheetOptions): ng.IPromise; + show(options: MDBottomSheetOptions): angular.IPromise; hide(response?: any): void; cancel(response?: any): void; } @@ -49,14 +49,14 @@ declare module angular.material { controller?: any; locals?: {[index: string]: any}; bindToController?: boolean; - resolve?: {[index: string]: ng.IPromise} + resolve?: {[index: string]: angular.IPromise} controllerAs?: string; parent?: Element; onComplete?: Function; } interface MDDialogService { - show(dialog: MDDialogOptions|MDPresetDialog): ng.IPromise; + show(dialog: MDDialogOptions|MDPresetDialog): angular.IPromise; confirm(): MDConfirmDialog; alert(): MDAlertDialog; hide(response?: any): void; @@ -64,7 +64,7 @@ declare module angular.material { } interface MDIcon { - (path: string): ng.IPromise; + (path: string): angular.IPromise; } interface MDIconProvider { @@ -110,14 +110,14 @@ declare module angular.material { controller?: any; locals?: {[index: string]: any}; bindToController?: boolean; - resolve?: {[index: string]: ng.IPromise} + resolve?: {[index: string]: angular.IPromise} controllerAs?: string; parent?: Element; } interface MDToastService { - show(optionsOrPreset: MDToastOptions|MDToastPreset): ng.IPromise; - showSimple(): ng.IPromise; + show(optionsOrPreset: MDToastOptions|MDToastPreset): angular.IPromise; + showSimple(): angular.IPromise; simple(): MDSimpleToastPreset; build(): MDToastPreset; updateContent(): void; diff --git a/angular-translate/angular-translate-tests.ts b/angular-translate/angular-translate-tests.ts index 559555418..cc02a85d6 100644 --- a/angular-translate/angular-translate-tests.ts +++ b/angular-translate/angular-translate-tests.ts @@ -2,7 +2,7 @@ var app = angular.module('at', ['pascalprecht.translate']); -app.config(($translateProvider: ng.translate.ITranslateProvider) => { +app.config(($translateProvider: angular.translate.ITranslateProvider) => { $translateProvider.translations('en', { TITLE: 'Hello', FOO: 'This is a paragraph.', @@ -22,7 +22,7 @@ interface Scope extends ng.IScope { changeLanguage(key: any): void; } -app.controller('Ctrl', ($scope: Scope, $translate: ng.translate.ITranslateService) => { +app.controller('Ctrl', ($scope: Scope, $translate: angular.translate.ITranslateService) => { $scope['changeLanguage'] = function (key: any) { $translate.use(key); }; diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index c972c927d..bfc573dcc 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -33,8 +33,8 @@ declare module angular.translate { } interface ITranslateService { - (translationId: string, interpolateParams?: any, interpolationId?: string): ng.IPromise; - (translationId: string[], interpolateParams?: any, interpolationId?: string): ng.IPromise<{ [key: string]: string }>; + (translationId: string, interpolateParams?: any, interpolationId?: string): angular.IPromise; + (translationId: string[], interpolateParams?: any, interpolationId?: string): angular.IPromise<{ [key: string]: string }>; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; @@ -44,17 +44,17 @@ declare module angular.translate { isPostCompilingEnabled(): boolean; preferredLanguage(langKey?: string): string; proposedLanguage(): string; - refresh(langKey?: string): ng.IPromise; + refresh(langKey?: string): angular.IPromise; storage(): IStorage; storageKey(): string; use(): string; - use(key: string): ng.IPromise; + use(key: string): angular.IPromise; useFallbackLanguage(langKey?: string): void; versionInfo(): string; loaderCache(): any; } - interface ITranslateProvider extends ng.IServiceProvider { + interface ITranslateProvider extends angular.IServiceProvider { translations(): ITranslationTable; translations(key: string, translationTable: ITranslationTable): ITranslateProvider; cloakClassName(): string; diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 0cf796832..f5dfbeca5 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -62,7 +62,7 @@ declare module angular.ui { reloadOnSearch?: boolean; } - interface IStateProvider extends IServiceProvider { + interface IStateProvider extends ng.IServiceProvider { state(name:string, config:IState): IStateProvider; state(config:IState): IStateProvider; decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any; @@ -81,7 +81,7 @@ declare module angular.ui { type(name: string, definition: any, definitionFn?: any): any; } - interface IUrlRouterProvider extends IServiceProvider { + interface IUrlRouterProvider extends ng.IServiceProvider { when(whenPath: RegExp, handler: Function): IUrlRouterProvider; when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; when(whenPath: RegExp, toPath: string): IUrlRouterProvider; @@ -143,7 +143,7 @@ declare module angular.ui { * * @param options Options object. */ - go(to: string, params?: {}, options?: IStateOptions): IPromise; + go(to: string, params?: {}, options?: IStateOptions): ng.IPromise; transitionTo(state: string, params?: {}, updateLocation?: boolean): void; transitionTo(state: string, params?: {}, options?: IStateOptions): void; includes(state: string, params?: {}): boolean; diff --git a/angularjs/angular-resource-tests.ts b/angularjs/angular-resource-tests.ts index c80cc662d..148d40901 100644 --- a/angularjs/angular-resource-tests.ts +++ b/angularjs/angular-resource-tests.ts @@ -1,12 +1,12 @@ /// -interface IMyResource extends ng.resource.IResource { }; -interface IMyResourceClass extends ng.resource.IResourceClass { }; +interface IMyResource extends angular.resource.IResource { }; +interface IMyResourceClass extends angular.resource.IResourceClass { }; /////////////////////////////////////// // IActionDescriptor /////////////////////////////////////// -var actionDescriptor: ng.resource.IActionDescriptor; +var actionDescriptor: angular.resource.IActionDescriptor; actionDescriptor.headers = { header: 'value' }; actionDescriptor.isArray = true; @@ -19,7 +19,7 @@ actionDescriptor.params = { key: 'value' }; /////////////////////////////////////// var resourceClass: IMyResourceClass; var resource: IMyResource; -var resourceArray: ng.resource.IResourceArray; +var resourceArray: angular.resource.IResourceArray; resource = resourceClass.delete(); resource = resourceClass.delete({ key: 'value' }); @@ -49,7 +49,7 @@ resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }); resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { }); resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { }, function () { }); resourceArray.push(resource); -resourceArray.$promise.then(function(data: ng.resource.IResourceArray) {}); +resourceArray.$promise.then(function(data: angular.resource.IResourceArray) {}); resource = resourceClass.remove(); resource = resourceClass.remove({ key: 'value' }); @@ -73,8 +73,8 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { // IResource /////////////////////////////////////// -var promise : ng.IPromise; -var arrayPromise : ng.IPromise; +var promise : angular.IPromise; +var arrayPromise : angular.IPromise; promise = resource.$delete(); promise = resource.$delete({ key: 'value' }); @@ -97,7 +97,7 @@ arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { }); arrayPromise = resourceArray[0].$query(function () { }); arrayPromise = resourceArray[0].$query(function () { }, function () { }); arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { }, function () { }); -arrayPromise.then(function(data: ng.resource.IResourceArray) {}); +arrayPromise.then(function(data: angular.resource.IResourceArray) {}); promise = resource.$remove(); promise = resource.$remove({ key: 'value' }); @@ -116,7 +116,7 @@ promise = resource.$save({ key: 'value' }, function () { }, function () { }); /////////////////////////////////////// // IResourceService /////////////////////////////////////// -var resourceService: ng.resource.IResourceService; +var resourceService: angular.resource.IResourceService; resourceClass = resourceService('test'); resourceClass = resourceService('test'); resourceClass = resourceService('test'); @@ -125,12 +125,12 @@ resourceClass = resourceService('test'); // IModule /////////////////////////////////////// var mod: ng.IModule; -var resourceServiceFactoryFunction: ng.resource.IResourceServiceFactoryFunction; -var resourceService: ng.resource.IResourceService; +var resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction; +var resourceService: angular.resource.IResourceService; resourceClass = resourceServiceFactoryFunction(resourceService); -resourceServiceFactoryFunction = function (resourceService: ng.resource.IResourceService) { return resourceClass; }; +resourceServiceFactoryFunction = function (resourceService: angular.resource.IResourceService) { return resourceClass; }; mod = mod.factory('factory name', resourceServiceFactoryFunction); /////////////////////////////////////// diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 4f03a341c..057cc1b56 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -104,28 +104,28 @@ declare module angular.resource { // Instance calls always return the the promise of the request which retrieved the object // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L546 interface IResource { - $get(): ng.IPromise; - $get(params?: Object, success?: Function, error?: Function): ng.IPromise; - $get(success: Function, error?: Function): ng.IPromise; + $get(): angular.IPromise; + $get(params?: Object, success?: Function, error?: Function): angular.IPromise; + $get(success: Function, error?: Function): angular.IPromise; - $query(): ng.IPromise>; - $query(params?: Object, success?: Function, error?: Function): ng.IPromise>; - $query(success: Function, error?: Function): ng.IPromise>; + $query(): angular.IPromise>; + $query(params?: Object, success?: Function, error?: Function): angular.IPromise>; + $query(success: Function, error?: Function): angular.IPromise>; - $save(): ng.IPromise; - $save(params?: Object, success?: Function, error?: Function): ng.IPromise; - $save(success: Function, error?: Function): ng.IPromise; + $save(): angular.IPromise; + $save(params?: Object, success?: Function, error?: Function): angular.IPromise; + $save(success: Function, error?: Function): angular.IPromise; - $remove(): ng.IPromise; - $remove(params?: Object, success?: Function, error?: Function): ng.IPromise; - $remove(success: Function, error?: Function): ng.IPromise; + $remove(): angular.IPromise; + $remove(params?: Object, success?: Function, error?: Function): angular.IPromise; + $remove(success: Function, error?: Function): angular.IPromise; - $delete(): ng.IPromise; - $delete(params?: Object, success?: Function, error?: Function): ng.IPromise; - $delete(success: Function, error?: Function): ng.IPromise; + $delete(): angular.IPromise; + $delete(params?: Object, success?: Function, error?: Function): angular.IPromise; + $delete(success: Function, error?: Function): angular.IPromise; /** the promise of the original server interaction that created this instance. **/ - $promise : ng.IPromise; + $promise : angular.IPromise; $resolved : boolean; } @@ -134,14 +134,14 @@ declare module angular.resource { */ interface IResourceArray extends Array { /** the promise of the original server interaction that created this collection. **/ - $promise : ng.IPromise>; + $promise : angular.IPromise>; $resolved : boolean; } /** when creating a resource factory via IModule.factory */ interface IResourceServiceFactoryFunction { - ($resource: ng.resource.IResourceService): IResourceClass; - >($resource: ng.resource.IResourceService): U; + ($resource: angular.resource.IResourceService): IResourceClass; + >($resource: angular.resource.IResourceService): U; } } @@ -150,13 +150,13 @@ declare module angular { interface IModule { /** creating a resource service factory */ - factory(name: string, resourceServiceFactoryFunction: ng.resource.IResourceServiceFactoryFunction): IModule; + factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction): IModule; } } interface Array { /** the promise of the original server interaction that created this collection. **/ - $promise : ng.IPromise>; + $promise : angular.IPromise>; $resolved : boolean; } diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts index b791942a4..4ddf87cab 100644 --- a/angularjs/angular-route.d.ts +++ b/angularjs/angular-route.d.ts @@ -63,7 +63,7 @@ declare module angular.route { * * {Array.} - route parameters extracted from the current $location.path() by applying the current route */ - template?: string|{($routeParams?: ng.route.IRouteParamsService) : string;} + template?: string|{($routeParams?: angular.route.IRouteParamsService) : string;} /** * {string=|function()=} * Path or function that returns a path to an html template that should be used by ngView. @@ -72,7 +72,7 @@ declare module angular.route { * * {Array.} - route parameters extracted from the current $location.path() by applying the current route */ - templateUrl?: string|{ ($routeParams?: ng.route.IRouteParamsService): string; } + templateUrl?: string|{ ($routeParams?: angular.route.IRouteParamsService): string; } /** * {Object.=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is: * @@ -91,7 +91,7 @@ declare module angular.route { * - {Object} - current $location.search() * - The custom redirectTo function is expected to return a string which will be used to update $location.path() and $location.search(). */ - redirectTo?: string|{($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) : string}; + redirectTo?: string|{($routeParams?: angular.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) : string}; /** * Reload route when only $location.search() or $location.hash() changes. * diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 191aa7692..1e62aa5f2 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -665,6 +665,7 @@ declare module angular { // TODO undocumented, so we need to get it from the source code /////////////////////////////////////////////////////////////////////////// interface IBrowserService { + defer: angular.ITimeoutService; [key: string]: any; } @@ -1277,7 +1278,7 @@ declare module angular { interface IHttpPromiseCallbackArg { data?: T; status?: number; - headers?: (headerName: string) => string; + headers?: IHttpHeadersGetter; config?: IRequestConfig; statusText?: string; } diff --git a/atom/atom.d.ts b/atom/atom.d.ts index 96b7c849d..0abeda316 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -1145,6 +1145,18 @@ declare module AtomCore { new(state:IAtomState):IAtom; } + class Disposable { + constructor(disposalAction:any) + dispose():void + } + + class CommandRegistry { + add(target:string, commandName:string, callback:Function):Disposable + findCommands(params:Object):Object[] + dispatch(target:any,commandName:string):void + } + + // https://atom.io/docs/api/v0.106.0/api/classes/Atom.html /* Global Atom class : instance members */ interface IAtom { @@ -1175,6 +1187,8 @@ declare module AtomCore { workspace: IWorkspace; // really exists? end + commands: CommandRegistry; + initialize:Function; // registerRepresentationClass:Function; // registerRepresentationClasses:Function; @@ -1754,6 +1768,8 @@ declare module "atom" { cancel():any; } + + var WorkspaceView:AtomCore.IWorkspaceViewStatic; var Task:AtomCore.ITaskStatic; diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 834ebc831..7de8eb807 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -238,7 +238,7 @@ declare module Backbone { initial(n: number): TModel[]; inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; isEmpty(object: any): boolean; - invoke(methodName: string, arguments?: any[]): any; + invoke(methodName: string, args?: any[]): any; last(): TModel; last(n: number): TModel[]; lastIndexOf(element: TModel, fromIndex?: number): number; diff --git a/bootstrap-touchspin/bootstrap-touchspin-tests.ts b/bootstrap-touchspin/bootstrap-touchspin-tests.ts new file mode 100644 index 000000000..552c26f52 --- /dev/null +++ b/bootstrap-touchspin/bootstrap-touchspin-tests.ts @@ -0,0 +1,68 @@ +/// +/// + +$(function () { + // Example 1 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo1']").TouchSpin({ + min: 0, + max: 100, + step: 0.1, + decimals: 2, + boostat: 5, + maxboostedstep: 10, + postfix: '%' + }); + + // Example 2 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo2']").TouchSpin({ + min: -1000000000, + max: 1000000000, + stepinterval: 50, + maxboostedstep: 10000000, + prefix: '$' + }); + + // Example 3 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo_vertical']").TouchSpin({ + verticalbuttons: true + }); + + // Example 4 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo_vertical2']").TouchSpin({ + verticalbuttons: true, + verticalupclass: 'glyphicon glyphicon-plus', + verticaldownclass: 'glyphicon glyphicon-minus' + }); + + // Example 5 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo3']").TouchSpin(); + + // Example 6 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo3_21']").TouchSpin({ + initval: 40 + }); + + // Example 7 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo4']").TouchSpin({ + postfix: "a button", + postfix_extraclass: "btn btn-default" + }); + + // Example 8 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo4_2']").TouchSpin({ + postfix: "a button", + postfix_extraclass: "btn btn-default" + }); + + // Example 9 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo5']").TouchSpin({ + prefix: "pre", + postfix: "post" + }); + + // Example 10 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo6']").TouchSpin({ + buttondown_class: "btn btn-link", + buttonup_class: "btn btn-link" + }); +}); \ No newline at end of file diff --git a/bootstrap-touchspin/bootstrap-touchspin.d.ts b/bootstrap-touchspin/bootstrap-touchspin.d.ts new file mode 100644 index 000000000..2dcf62884 --- /dev/null +++ b/bootstrap-touchspin/bootstrap-touchspin.d.ts @@ -0,0 +1,130 @@ +// Type definitions for Bootstrap TouchSpin +// Project: http://www.virtuosoft.eu/code/bootstrap-touchspin/ +// Definitions by: Albin Sunnanbo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * TouchSpinOptions. All options are optional + */ +interface TouchSpinOptions { + /** + * Applied when no explicit value is set on the input with the value attribute. + * Empty string means that the value remains empty on initialization. + */ + initval?: number | string; + + /** + * Minimum value. + */ + min?: number; + + /** + * Maximum value. + */ + max?: number; + + /** + * Incremental/decremental step on up/down change. + */ + step?: number; + + /** + * How to force the value to be divisible by step value: 'none' | 'round' | 'floor' | 'ceil' + */ + forcestepdivisibility?: string; + + /** + * Number of decimal points. + */ + decimals?: number; + + /** + * Refresh rate of the spinner in milliseconds. + */ + stepinterval?: number; + + /** + * Time in milliseconds before the spinner starts to spin. + */ + stepintervaldelay?: number; + + /** + * Enables the traditional up/down buttons. + */ + verticalbuttons?: boolean; + + /** + * Class of the up button with vertical buttons mode enabled. + */ + verticalupclass?: string; + + /** + * Class of the down button with vertical buttons mode enabled. + */ + verticaldownclass?: string; + + /** + * Text before the input. + */ + prefix?: string; + + /** + * Text after the input. + */ + postfix?: string; + + /** + * Extra class(es) for prefix. + */ + prefix_extraclass?: string; + + /** + * Extra class(es) for postfix. + */ + postfix_extraclass?: string; + + /** + * If enabled, the the spinner is continually becoming faster as holding the button. + */ + booster?: boolean; + + /** + * Boost at every nth step. + */ + boostat?: number; + + /** + * Maximum step when boosted. + */ + maxboostedstep?: number | boolean; + + /** + * Enables the mouse wheel to change the value of the input. + */ + mousewheel?: boolean; + + /** + * Class(es) of down button. + */ + buttondown_class?: string; + + /** + * Class(es) of up button. + */ + buttonup_class?: string; +} + +interface JQuery { + /** + * Initialize TouchSpin + */ + TouchSpin(): JQuery; + + /** + * Inialize TouchSpin with options + * @param options a TouchSpinOptions object with one or more options + */ + TouchSpin(options: TouchSpinOptions): JQuery; +} diff --git a/breeze/breeze-tests.ts b/breeze/breeze-tests.ts index 979bc5683..f309462af 100644 --- a/breeze/breeze-tests.ts +++ b/breeze/breeze-tests.ts @@ -3,7 +3,6 @@ import core = breeze.core; import config = breeze.config; - function test_dataType() { var typ = breeze.DataType.DateTime; var nm = typ.getName(); @@ -888,4 +887,4 @@ function test_config() { config.registerType(f1, "myCtor"); s = config.stringifyPad; o = config.typeRegistry; -} \ No newline at end of file +} diff --git a/calq/calq-tests.ts b/calq/calq-tests.ts new file mode 100644 index 000000000..6f8019261 --- /dev/null +++ b/calq/calq-tests.ts @@ -0,0 +1,28 @@ +/// +function calq_base() +{ + calq.init("bfff14a4e0225789be3d9d22c4bb42a1"); + + calq.init("bfff14a4e0225789be3d9d22c4bb42a1", { your: "config" }); + + calq.action.track("Product Review", {"Rating": 9.0}); + + calq.action.trackSale("Product Sale", { "Product Id": 149, "Product Name": "Dinosaur T-Shirt XL" }, "USD",10); + + calq.action.trackHTMLLink('Link', { 'Target': 'Calq'}); + + calq.action.trackPageView(); + + calq.action.trackPageView("Custom Action"); + + calq.action.setGlobalProperty("Referral Source", "Google Campaign"); +} + +function calq_people() +{ + calq.user.identify("1001"); + + calq.user.clear(); + + calq.user.profile( { "Company": "MegaCorp", "$email": "super_customer1@notarealemail.com" }); +} diff --git a/calq/calq.d.ts b/calq/calq.d.ts new file mode 100644 index 000000000..c574df58f --- /dev/null +++ b/calq/calq.d.ts @@ -0,0 +1,34 @@ +// Type definitions for calq +// Project: https://calq.io/docs/client/javascript/reference +// Definitions by: Eirik Hoem +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Calq +{ + action:Calq.Action; + user:Calq.User; + + init(writeKey:string, options?:{[index:string]:any}):void; +} + +declare module Calq +{ + interface Action + { + track(action:string, params?:{[index:string]:any}):void; + trackSale(action:string, params:{[index:string]:any}, currency:string, amount:number):void; + trackHTMLLink(action:string, params?:{[index:string]:any}):void; + trackPageView(action?:string):void; + setGlobalProperty(name:string,value:any):void; + } + + interface User + { + identify(userId:string):void; + clear():void; + profile(params:{[index:string]:any}):void; + + } +} + +declare var calq:Calq; \ No newline at end of file diff --git a/chartjs/chart-tests.ts b/chartjs/chart-tests.ts index 2374b6228..4bd8820c6 100644 --- a/chartjs/chart-tests.ts +++ b/chartjs/chart-tests.ts @@ -252,12 +252,12 @@ var myPolarAreaChart = new Chart(ctx).PolarArea(polarAreaData, { var myPolarAreaChartLegend: string = myPolarAreaChart.generateLegend(); var myPolarAreaChartImage: string = myPolarAreaChart.toBase64Image(); -myPolarAreaChart.addData([{ +myPolarAreaChart.addData({ value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" -}], 0); +}, 0); myPolarAreaChart.clear(); myPolarAreaChart.removeData(0); myPolarAreaChart.resize(); @@ -301,12 +301,12 @@ var myPieChart = new Chart(ctx).Pie(pieData, { var myPieChartLegend: string = myPieChart.generateLegend(); var myPieChartImage: string = myPieChart.toBase64Image(); -myPieChart.addData([{ +myPieChart.addData({ value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" -}], 0); +}, 0); myPieChart.clear(); myPieChart.removeData(0); myPieChart.resize(); @@ -329,12 +329,12 @@ var myDoughnutChart = new Chart(ctx).Doughnut(pieData, { var myDoughnutChartLegend: string = myDoughnutChart.generateLegend(); var myDoughnutChartImage: string = myDoughnutChart.toBase64Image(); -myPieChart.addData([{ +myPieChart.addData({ value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" -}], 0); +}, 0); myDoughnutChart.clear(); myDoughnutChart.removeData(0); myDoughnutChart.resize(); diff --git a/chartjs/chart.d.ts b/chartjs/chart.d.ts index a73ecc94e..9da7245f6 100644 --- a/chartjs/chart.d.ts +++ b/chartjs/chart.d.ts @@ -113,8 +113,9 @@ interface LinearInstance extends ChartInstance { interface CircularInstance extends ChartInstance { getSegmentsAtEvent: (event: Event) => {}[]; update: () => void; - addData: (valuesArray: CircularChartData[], index: number) => void; + addData: (valuesArray: CircularChartData, index?: number) => void; removeData: (index: number) => void; + segments: Array; } interface LineChartOptions extends ChartOptions { diff --git a/chosen/chosen.jquery.d.ts b/chosen/chosen.jquery.d.ts index 890b4221e..1c9507339 100644 --- a/chosen/chosen.jquery.d.ts +++ b/chosen/chosen.jquery.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Chosen.JQuery 0.9 +// Type definitions for Chosen.JQuery 1.4.2 // Project: http://harvesthq.github.com/chosen/ // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -8,18 +8,23 @@ interface ChosenOptions { allow_single_deselect?: boolean; - disable_search_threshold?: number; disable_search?: boolean; + disable_search_threshold?: number; + enable_split_word_search?: boolean; + inherit_select_classes?: boolean; + max_selected_options?: number; + no_results_text?: string; + placeholder_text_multiple?: string; + placeholder_text_single?: string; search_contains?: boolean; single_backstroke_delete?: boolean; - max_selected_options?: number; - placeholder_text_multiple?: string; - placeholder_text?: string; - placeholder_text_single?: string; - no_results_text?: string; + width?: number; + display_disabled_options?: boolean; + display_selected_options?: boolean; + include_group_label_in_selected?: boolean; } interface JQuery { chosen(): JQuery; chosen(options: ChosenOptions): JQuery; -} \ No newline at end of file +} diff --git a/circular-json/circular-json-tests.ts b/circular-json/circular-json-tests.ts new file mode 100644 index 000000000..d3f2e0951 --- /dev/null +++ b/circular-json/circular-json-tests.ts @@ -0,0 +1,31 @@ +/// + +import CircularJSON = require('circular-json'); + +var replacer = (key: any, val: any) => { + return val; +} + +var replacerArray = ['a', 'x']; + +// implements JSON interface +var json_obj: JSON = CircularJSON; + +CircularJSON.parse('{"a":"b"}'); + +CircularJSON.parse('{"a":"b"}', replacer); + +// just stringify a value +CircularJSON.stringify({a: 'b'}); + +// do replacements for part of the object +CircularJSON.stringify({a: 'b'}, replacer); +CircularJSON.stringify({a: 'b'}, replacerArray); + +// add whitespace to the output +CircularJSON.stringify({a: 'b'}, replacer, 5); +CircularJSON.stringify({a: 'b'}, replacerArray, 5); + +// do not actually set up a re-parseable object +CircularJSON.stringify({a: 'b'}, replacer, 5, true); +CircularJSON.stringify({a: 'b'}, replacerArray, 5, true); diff --git a/circular-json/circular-json.d.ts b/circular-json/circular-json.d.ts new file mode 100644 index 000000000..2aa27e947 --- /dev/null +++ b/circular-json/circular-json.d.ts @@ -0,0 +1,15 @@ +// Type definitions for circular-json v0.1.6 +// Project: https://github.com/WebReflection/circular-json +// Definitions by: Jonathan Pevarnek +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'circular-json' { + interface ICircularJSON extends JSON { + parse(text: string, reviver?: (key: any, value: any) => any): any; + stringify(value: any, replacer?: ((key: string, value: any) => any) | any[], space?: any, placeholder?: boolean): string; + } + + var CircularJSON: ICircularJSON; + + export = CircularJSON; +} diff --git a/connect-flash/connect-flash-tests.ts b/connect-flash/connect-flash-tests.ts new file mode 100644 index 000000000..303c12647 --- /dev/null +++ b/connect-flash/connect-flash-tests.ts @@ -0,0 +1,16 @@ +/// + +import express = require('express'); +import flash = require('connect-flash'); + +var app = express(); + +app.use(flash()); +app.use(flash({ + unsafe: false +})); + +app.use(function(req: Express.Request, res: Express.Response, next: Function) { + req.flash('Message'); + req.flash('info', 'Message'); +}); diff --git a/connect-flash/connect-flash.d.ts b/connect-flash/connect-flash.d.ts new file mode 100644 index 000000000..0b8047a72 --- /dev/null +++ b/connect-flash/connect-flash.d.ts @@ -0,0 +1,22 @@ +// Type definitions for connect-flash +// Project: https://github.com/jaredhanson/connect-flash +// Definitions by: Andreas Gassmann +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Express { + export interface Request { + flash(message: string): any; + flash(event: string, message: string): any; + } +} + +declare module "connect-flash" { + import express = require('express'); + interface IConnectFlashOptions { + unsafe?: boolean; + } + function e(options?: IConnectFlashOptions): express.RequestHandler; + export = e; +} diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index a846dbfa8..bdc7509b7 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -2656,4 +2656,18 @@ function multiTest() { .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); -} \ No newline at end of file +} + +// Tests miscellaneous keyboard events +function keyboardEventsTest() { + var keyPressed: string; + d3.select("body").on("keydown", () => { + if (d3.event.metaKey) { + keyPressed = "meta"; + } else if (d3.event.ctrlKey) { + keyPressed = "ctrl"; + } else if (d3.event.altKey) { + keyPressed = "alt"; + } + }); +} diff --git a/d3/d3.d.ts b/d3/d3.d.ts index b00d808ee..b71610f94 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -57,7 +57,9 @@ declare module D3 { x: number; y: number; keyCode: number; - altKey: any; + altKey?: boolean; + ctrlKey?: boolean; + metaKey?: boolean; type: string; } @@ -1371,7 +1373,20 @@ declare module D3 { (number:number): ForceLayout; (accessor: (d: any, index: number) => number): ForceLayout; }; - + /** + * If distance is specified, sets the maximum distance over which + * charge forces are applied. If distance is not specified, returns + * the current maximum charge distance, which defaults to infinity. + * Specifying a finite charge distance improves the performance of + * the force layout and produces a more localized layout; + * distance-limited charge forces are especially useful in + * conjunction with custom gravity. + */ + chargeDistance: { + (): number; + (distance: number): ForceLayout; + (accessor: (d: any, index: number) => number): ForceLayout; + }; theta: { (): number; (number:number): ForceLayout; @@ -1952,13 +1967,13 @@ declare module D3 { /** * Get the interpolation accessor. */ - (): string; + (): string | ((points: number[][]) => string); /** * Set the interpolation accessor. * * @param interpolate The interpolation mode */ - (interpolate: string): Line; + (interpolate: string | ((points: number[][]) => string)): Line; }; /** * Get or set the cardinal spline tension. @@ -2248,13 +2263,13 @@ declare module D3 { /** * Get the interpolation accessor. */ - (): string; + (): string | ((points: number[][]) => string); /** * Set the interpolation accessor. * * @param interpolate The interpolation mode */ - (interpolate: string): Area; + (interpolate: string | ((points: number[][]) => string)): Area; }; /** * Get or set the cardinal spline tension. diff --git a/datejs/datejs-tests.ts b/datejs/datejs-tests.ts index 9cb5eabbc..0ed60d2d3 100644 --- a/datejs/datejs-tests.ts +++ b/datejs/datejs-tests.ts @@ -2,19 +2,16 @@ /// function tests() { - // TypeScript alias - var DateJS: IDateJSStatic = Date; - - // What date is next thursday? - DateJS.today().next().thursday(); + // What date is next thursday? + Date.today().next().thursday(); // Add 3 days to Today - DateJS.today().add(3).days(); + Date.today().add(3).days(); // Is today Friday? - DateJS.today().is().friday(); + Date.today().is().friday(); - var is = DateJS.today().is(); + var is = Date.today().is(); // Number fun (3).days().ago(); @@ -24,22 +21,22 @@ function tests() { n.months().fromNow(); // Set to 8:30 AM on the 15th day of the month - DateJS.today().set({ day: 15, hour: 8, minute: 30 }); + Date.today().set({ day: 15, hour: 8, minute: 30 }); - DateJS.today().is().january(); - DateJS.today().is().november(); - DateJS.today().add(1).day().is().saturday(); + Date.today().is().january(); + Date.today().is().november(); + Date.today().add(1).day().is().saturday(); // Convert text into Date - DateJS.parse('today'); - DateJS.parse('t + 5 d'); // today + 5 days - DateJS.parse('next thursday'); - DateJS.parse('February 20th 1973'); - DateJS.parse('Thu, 1 July 2004 22:30:00'); + Date.parse('today'); + Date.parse('t + 5 d'); // today + 5 days + Date.parse('next thursday'); + Date.parse('February 20th 1973'); + Date.parse('Thu, 1 July 2004 22:30:00'); - var future: IDateJS = DateJS.today().add(2).months(); - var someDate: IDateJS = DateJS.today().next().april().add(2).days(); + var future: IDateJS = Date.today().add(2).months(); + var someDate: IDateJS = Date.today().next().april().add(2).days(); someDate.same().week(future); // true|false; someDate.same().day(); // true|false; - DateJS.today().toObject().day; + Date.today().toObject().day; } \ No newline at end of file diff --git a/datejs/datejs.d.ts b/datejs/datejs.d.ts index 5c4034bc5..c0b7ad510 100644 --- a/datejs/datejs.d.ts +++ b/datejs/datejs.d.ts @@ -1,8 +1,11 @@ -// Type definitions for DateJS +// Type definitions for DateJS // Project: http://www.datejs.com/ // Definitions by: David Khristepher Santos // Definitions: https://github.com/borisyankov/DefinitelyTyped +//NOTE: This definition file is for the library located at http://datejs.googlecode.com/svn/ and documented at https://code.google.com/p/datejs/wiki/APIDocumentation +//That version of the library is more recent than the one provided at https://code.google.com/p/datejs/downloads/list, which has a slightly different API + /** Defines a structure to be used in the add and set instance methods */ interface IDateJSLiteral { milliseconds: number; @@ -15,13 +18,13 @@ interface IDateJSLiteral { } /** DateJS Public Static Methods */ -interface IDateJSStatic extends IDateJS { +interface DateConstructor { /** Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM) */ - today(): IDateJS; + today(): Date; /** Compares the first date to the second date and returns an number indication of their relative values. -1 = this is lessthan date. 0 = values are equal. 1 = this is greaterthan date. */ - compare(date1: IDateJS, date2: IDateJS): number; + compare(date1: Date, date2: Date): number; /** Compares the first Date object to the second Date object and returns true if they are equal. */ - equals(date1: IDateJS, date2?: IDateJS): boolean; + equals(date1: Date, date2?: Date): boolean; /** Gets the day number (0-6) if given a culture-specific string which is a valid full or abbreviated day name. */ getDayNumberFromName(dayName: string): number; /** Gets the month number (0-11) if given a culture-specific string which is a valid full or abbreviated month name. */ @@ -35,11 +38,11 @@ interface IDateJSStatic extends IDateJS { /** Gets the timezone offset if given a culture-specific string which is a valid full or abbreviated timezone name and a boolean indicating whether daylight savings time is in effect. */ getTimezoneOffset(timezoneAbbreviation?: string, isDayLightSavingsTime?: boolean): number; /** Converts the specified string value into its JavaScript Date equivalent using culture-specific format information. */ - parse(dateString: string): IDateJS; + parse(dateString: string): Date; /** Converts the specified string value into its JavaScript Date equivalent using the specified format. The format of the string value must match one of the supplied formats exactly. */ - parseExact(dateString: string, formatString: string): IDateJS; + parseExact(dateString: string, formatString: string): Date; /** Converts the specified string value into its JavaScript Date equivalent using the specified formats (array). The format of the string value must match one of the supplied formats exactly. */ - parseExact(dateString: string, formatArray: string[]): IDateJS; + parseExact(dateString: string, formatArray: string[]): Date; /** Validates the number is within an acceptable range for the days in a month [0-MaxDaysInMonth]. */ validateDay(day: number, fullYear: number, monthNumber: number): boolean; /** Validates the number is within an acceptable range for hours[0 - 23].Returns true if within range, otherwise false. */ @@ -57,45 +60,45 @@ interface IDateJSStatic extends IDateJS { } /** DateJS Public Instance Methods */ -interface IDateJS extends Date { +interface Date { /** Adds(or subtracts) to the value of the year, month, day, hour, minute, second, millisecond of the date instance using given configuration object. Positive and Negative values allowed. */ - add(config?: IDateJSLiteral): IDateJS; + add(config?: IDateJSLiteral): Date; /** Adds the specified number of milliseconds to this instance. */ - addMilliseconds(milliseconds: number): IDateJS; + addMilliseconds(milliseconds: number): Date; /** Adds the specified number of seconds to this instance given the number of seconds to add.The number can be positive or negative. */ - addSeconds(seconds: number): IDateJS; + addSeconds(seconds: number): Date; /** Adds the specified number of minutes to this instance given the number of minutes to add.The number can be positive or negative. */ - addMinutes(minutes: number): IDateJS; + addMinutes(minutes: number): Date; /** Adds the specified number of hours to this instance given the number of hours to add.The number can be positive or negative. */ - addHours(hours: number): IDateJS; + addHours(hours: number): Date; /** Adds the specified number of days to this instance.The number can be positive or negative. */ - addDays(days: number): IDateJS; + addDays(days: number): Date; /** Adds the specified number of weeks to this instance given the number of weeks to add.The number can be positive or negative. */ - addWeeks(weeks: number): IDateJS; + addWeeks(weeks: number): Date; /** Adds the specified number of months to this instance given the number of months to add.The number can be positive or negative. */ - addMonths(months: number): IDateJS; + addMonths(months: number): Date; /** Adds the specified number of years to this instance given the number of years to add.The number can be positive or negative. */ - addYears(years: number): IDateJS; + addYears(years: number): Date; /** Resets the time of this Date object to 12:00 AM(00:00), which is the start of the day. */ - clearTime(): IDateJS; + clearTime(): Date; /** Resets the time of this Date object to the current time('now'). */ - setTimeToNow(): IDateJS; + setTimeToNow(): Date; /** Returns a new Date object that is an exact date and time copy of the original instance. */ - clone(): IDateJS; + clone(): Date; /** Determines if this instance is between a range of two dates or equal to either the start or end dates. */ - between(startDate: IDateJS, endDate: IDateJS): boolean; + between(startDate: Date, endDate: Date): boolean; /** Compares this instance to a Date object and returns an number indication of their relative values. -1 = this is lessthan date. 0 = values are equal. 1 = this is greaterthan date. */ - compareTo(date: IDateJS): number; + compareTo(date: Date): number; /** Compares this instance to another Date object and returns true if they are equal, otherwise false. */ - equals(date: IDateJS): boolean; + equals(date: Date): boolean; /** Determines if this date occurs after the date to compare to. */ - isAfter(date: IDateJS): boolean; + isAfter(date: Date): boolean; /** Determines if this date occurs before the date to compare to. */ - isBefore(date: IDateJS): boolean; + isBefore(date: Date): boolean; /** Determines if the current Date instance occurs on the same Date as the supplied 'date'. */ - isToday(date: IDateJS): boolean; + isToday(date: Date): boolean; /** Returns the number of milliseconds between this date and date. */ - getElapsed(date: IDateJS): number; + getElapsed(date: Date): number; /** Get the Ordinal day (numeric day number) of the year, adjusted for leap year. Returns 1 through 365 (366 in leap years) */ getOrdinalNumber(): number; /** Get the timezone abbreviation of the current date. */ @@ -107,30 +110,35 @@ interface IDateJS extends Date { /** Get the ISO 8601 week number. Week one ("01") is the week which contains the first Thursday of the year. Monday is considered the first day of the week. */ getISOWeek(): string; /** Moves the date to Monday of the week set. Week one (1) is the week which contains the first Thursday of the year. */ - setWeek(week: number): IDateJS; + setWeek(week: number): Date; /** Indicates whether Daylight Saving Time is observed in the current time zone. */ hasDaylightSavingTime(): boolean; /** Indicates whether this Date instance is within the Daylight Saving Time range for the current time zone. */ isDaylightSavingTime(): boolean; - /** Move to the next or previous dayOfWeek. Whether to move into the future (+1) or past(-1) is controlled by the optional direction parameter. */ - moveToDayOfWeek(dayOfWeek: number, direction: number): IDateJS; + /** Move to the next or previous dayOfWeek. Whether to move into the future (+1) or past(-1) is controlled by the optional direction parameter. */ + moveToDayOfWeek(dayOfWeek: number, direction: number): Date; /** Moves the date to the first day of the month. */ - moveToFirstDayOfMonth(): IDateJS; + moveToFirstDayOfMonth(): Date; /** Moves the date to the last day of the month. */ - moveToLastDayOfMonth(): IDateJS; + moveToLastDayOfMonth(): Date; /** Move to the next or previous month.Whether to move into the future(+1) or past(-1) is controlled by the optional direction parameter. */ - moveToMonth(month: number, direction: number): IDateJS; + moveToMonth(month: number, direction: number): Date; /** Moves the date to the next nth occurrence of the dayOfWeek starting from the beginning of the month. The number (-1) is a magic number and will return the last occurrence of the dayOfWeek in the month. */ - moveToNthOccurrence(dayOfWeek: number, occurrence: number): IDateJS; + moveToNthOccurrence(dayOfWeek: number, occurrence: number): Date; /** Set the value of year, month, day, hour, minute, second, millisecond of date instance using given configuration object. */ - set(config: IDateJSLiteral): IDateJS; + set(config: IDateJSLiteral): Date; /** Set the timezone for the current date using a culture - specific timezone abbreviation("PST").Note that in most JavaScript implementations, this will appear to change the time since the timezone is always based on the locale. */ - setTimezone(timezoneAbbreviation: string): IDateJS; + setTimezone(timezoneAbbreviation: string): Date; /** Set the timezone for the current date using an offset(-0700).Note that in most JavaScript implementations, this will appear to change the time since the timezone is always based on the locale. */ - setTimezoneOffset(timezoneOffset: number): IDateJS; + setTimezoneOffset(timezoneOffset: number): Date; /** Converts the current date instance into a string with an ISO 8601 format.The date is converted to it's UTC value. As per the ISO 8601 specification, the string will be wrapped with double quotation marks ("). */ toISOString(): string; /** Converts the value of the current Date object to its equivalent string representation.Use format argument to specify format(optional).See FormatSpecifiers for more info. */ toString(format?: string): string; } + +//NOTE: IDateJSStatic and IDateJS are provided here solely for backwards compatability with previous versions of this particular definition file (datejs.d.ts.) +//DO NOT use them in new code (and it is strongly suggested you remove their use in any existing code); simply use the Javascript Date class instead. +interface IDateJS extends Date { } +interface IDateJSStatic extends DateConstructor { } \ No newline at end of file diff --git a/datejs/sugarpak.d.ts b/datejs/sugarpak.d.ts index b52e6cf31..3a30d7f6c 100644 --- a/datejs/sugarpak.d.ts +++ b/datejs/sugarpak.d.ts @@ -1,4 +1,4 @@ -// Type definitions for DateJS - SugarPak Extensions +// Type definitions for DateJS - SugarPak Extensions // Project: http://www.datejs.com/ // Definitions by: David Khristepher Santos // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,67 +7,67 @@ declare module sugarpak { export interface IAddOrientation { - millisecond(): IDateJS; - second(): IDateJS; - minute(): IDateJS; - hour(): IDateJS; - day(): IDateJS; - week(): IDateJS; - month(): IDateJS; - year(): IDateJS; + millisecond(): Date; + second(): Date; + minute(): Date; + hour(): Date; + day(): Date; + week(): Date; + month(): Date; + year(): Date; - milliseconds(): IDateJS; - seconds(): IDateJS; - minutes(): IDateJS; - hours(): IDateJS; - days(): IDateJS; - weeks(): IDateJS; - months(): IDateJS; - years(): IDateJS; + milliseconds(): Date; + seconds(): Date; + minutes(): Date; + hours(): Date; + days(): Date; + weeks(): Date; + months(): Date; + years(): Date; } export interface IOrientation extends IAddOrientation { - monday(): IDateJS; - tuesday(): IDateJS; - wednesday(): IDateJS; - thursday(): IDateJS; - friday(): IDateJS; - saturday(): IDateJS; - sunday(): IDateJS; + monday(): Date; + tuesday(): Date; + wednesday(): Date; + thursday(): Date; + friday(): Date; + saturday(): Date; + sunday(): Date; - mon(): IDateJS; - tue(): IDateJS; - wed(): IDateJS; - thu(): IDateJS; - fri(): IDateJS; - sat(): IDateJS; - sun(): IDateJS; + mon(): Date; + tue(): Date; + wed(): Date; + thu(): Date; + fri(): Date; + sat(): Date; + sun(): Date; - january(): IDateJS; - february(): IDateJS; - march(): IDateJS; - april(): IDateJS; - may(): IDateJS; - june(): IDateJS; - july(): IDateJS; - august(): IDateJS; - september(): IDateJS; - october(): IDateJS; - november(): IDateJS; - december(): IDateJS; + january(): Date; + february(): Date; + march(): Date; + april(): Date; + may(): Date; + june(): Date; + july(): Date; + august(): Date; + september(): Date; + october(): Date; + november(): Date; + december(): Date; - jan(): IDateJS; - feb(): IDateJS; - mar(): IDateJS; - apr(): IDateJS; + jan(): Date; + feb(): Date; + mar(): Date; + apr(): Date; // may - jun(): IDateJS; - jul(): IDateJS; - aug(): IDateJS; - sep(): IDateJS; - oct(): IDateJS; - nov(): IDateJS; - dec(): IDateJS; + jun(): Date; + jul(): Date; + aug(): Date; + sep(): Date; + oct(): Date; + nov(): Date; + dec(): Date; } export interface IPredicate { @@ -116,30 +116,30 @@ declare module sugarpak { weekday(): boolean; - day(date?: IDateJS): boolean; - week(date?: IDateJS): boolean; - month(date?: IDateJS): boolean; - year(date?: IDateJS): boolean; + day(date?: Date): boolean; + week(date?: Date): boolean; + month(date?: Date): boolean; + year(date?: Date): boolean; } export interface IDatePartComparer { - millisecond(date?: IDateJS): boolean; - second(date?: IDateJS): boolean; - minute(date?: IDateJS): boolean; - hour(date?: IDateJS): boolean; - day(date?: IDateJS): boolean; - week(date?: IDateJS): boolean; - month(date?: IDateJS): boolean; - year(date?: IDateJS): boolean; + millisecond(date?: Date): boolean; + second(date?: Date): boolean; + minute(date?: Date): boolean; + hour(date?: Date): boolean; + day(date?: Date): boolean; + week(date?: Date): boolean; + month(date?: Date): boolean; + year(date?: Date): boolean; } export interface IDateElementEvaluator { - ago(): IDateJS; - before(): IDateJS; - fromNow(): IDateJS; - after(): IDateJS; + ago(): Date; + before(): Date; + fromNow(): Date; + after(): Date; } export interface IDateElement { @@ -178,10 +178,10 @@ declare module sugarpak { } -interface IDateJS { +interface Date { add(n: number): sugarpak.IAddOrientation; - at(time: string): IDateJS; - at(time: sugarpak.ITimeLiteral): IDateJS; + at(time: string): Date; + at(time: sugarpak.ITimeLiteral): Date; is(): sugarpak.IPredicate; next(): sugarpak.IOrientation; last(): sugarpak.IOrientation; @@ -199,7 +199,7 @@ interface IDateJS { toObject(): sugarpak.IDateLiteral; } -interface IDateJSStatic { +interface DateConstructor { /** Contains the day-of-week value for Monday */ MONDAY: number; /** Contains the day-of-week value for Tuesday */ @@ -215,57 +215,57 @@ interface IDateJSStatic { /** Contains the day-of-week value for Sunday */ SUNDAY: number; /** Instantiates a DateJS object from a literal */ - fromObject(date: sugarpak.IDateLiteral): IDateJS; + fromObject(date: sugarpak.IDateLiteral): Date; next(): sugarpak.IOrientation; last(): sugarpak.IOrientation; prev(): sugarpak.IOrientation; previous(): sugarpak.IOrientation; - january(): IDateJS; - february(): IDateJS; - march(): IDateJS; - april(): IDateJS; - may(): IDateJS; - june(): IDateJS; - july(): IDateJS; - august(): IDateJS; - september(): IDateJS; - october(): IDateJS; - november(): IDateJS; - december(): IDateJS; + january(): Date; + february(): Date; + march(): Date; + april(): Date; + may(): Date; + june(): Date; + july(): Date; + august(): Date; + september(): Date; + october(): Date; + november(): Date; + december(): Date; - monday(): IDateJS; - tuesday(): IDateJS; - wednesday(): IDateJS; - thursday(): IDateJS; - friday(): IDateJS; - saturday(): IDateJS; - sunday(): IDateJS; + monday(): Date; + tuesday(): Date; + wednesday(): Date; + thursday(): Date; + friday(): Date; + saturday(): Date; + sunday(): Date; - mon(): IDateJS; - tue(): IDateJS; - wed(): IDateJS; - thu(): IDateJS; - fri(): IDateJS; - sat(): IDateJS; - sun(): IDateJS; + mon(): Date; + tue(): Date; + wed(): Date; + thu(): Date; + fri(): Date; + sat(): Date; + sun(): Date; - jan(): IDateJS; - feb(): IDateJS; - mar(): IDateJS; - apr(): IDateJS; + jan(): Date; + feb(): Date; + mar(): Date; + apr(): Date; // may - jun(): IDateJS; - jul(): IDateJS; - aug(): IDateJS; - sep(): IDateJS; - oct(): IDateJS; - nov(): IDateJS; - dec(): IDateJS; + jun(): Date; + jul(): Date; + aug(): Date; + sep(): Date; + oct(): Date; + nov(): Date; + dec(): Date; } interface Number extends sugarpak.IDateElement { - // extend the Number type with all the IDateJS goodness + // extend the Number type with all the Date goodness } \ No newline at end of file diff --git a/dompurify/dompurify-tests.ts b/dompurify/dompurify-tests.ts new file mode 100644 index 000000000..d9d6e0bd6 --- /dev/null +++ b/dompurify/dompurify-tests.ts @@ -0,0 +1,8 @@ +/// + +import dompurify = require('dompurify'); + +dompurify.sanitize(''); +dompurify.addHook('beforeSanitizeElements', (el, data, config) => { + return el; +}); diff --git a/dompurify/dompurify.d.ts b/dompurify/dompurify.d.ts new file mode 100644 index 000000000..b1f24b00e --- /dev/null +++ b/dompurify/dompurify.d.ts @@ -0,0 +1,15 @@ +// Type definitions for DOM Purify +// Project: https://github.com/cure53/DOMPurify +// Definitions by: Dave Taylor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface IDOMPurify { + sanitize(s:string):string; + addHook(hook:string, cb:(currentNode:Element, data:any, config:any) => Element):void; +} + +declare var DOMPurify:IDOMPurify; + +declare module 'dompurify' { + export = DOMPurify; +} diff --git a/easy-session/easy-session-tests.ts b/easy-session/easy-session-tests.ts new file mode 100644 index 000000000..2053b634c --- /dev/null +++ b/easy-session/easy-session-tests.ts @@ -0,0 +1,63 @@ +/// +/// +/// + +import express = require('express'); +import session = require('express-session'); +import cookieParser = require('cookie-parser'); +import easySession = require('easy-session'); // Require the module : line 1 + +var app = express(); + +app.use(cookieParser('secreet')); +app.use(session({ + secret: 'keyboard cat', + resave: false, + saveUninitialized: true +})); +app.use(easySession.main(session)); + +app.get('/login', function (req, res, next) { + req.session.login('user', {email: 'email'}, function (err) { + if(err) { + res.send(500); + return; + } + res.send(200); + }); +}); + +app.post('/logout', function (req, res, next) { + req.session.logout(function (err) { + if(err) { + res.send(500); + return; + } + res.send(200); + }); +}); + +app.get('/isloggedin', function (req, res, next) { + res.send(req.session.isLoggedIn('user')); +}); + +app.get('/isfresh', function (req, res, next) { + res.send(req.session.isFresh()); +}); + +app.get('/hasrole', function (req, res, next) { + res.send(req.session.hasRole('user')); +}); + +app.post('/setrole', function (req, res, next) { + req.session.setRole(req.query.role); + res.send(200); +}); + +app.get('/getrole', function (req, res, next) { + res.send(req.session.getRole()); +}); + +app.use(easySession.isLoggedIn()); +app.use(easySession.isFresh()); +app.use(easySession.checkRole('user')); \ No newline at end of file diff --git a/easy-session/easy-session.d.ts b/easy-session/easy-session.d.ts new file mode 100644 index 000000000..8300d8503 --- /dev/null +++ b/easy-session/easy-session.d.ts @@ -0,0 +1,41 @@ +// Type definitions for easy-session +// Project: https://github.com/DeadAlready/node-easy-session +// Definitions by: Karl Düüna +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Express { + interface ErrorCallback { + (err?: any): void; + } + export interface Session { + login(callback: Function): void; + login(extend: Object, callback: ErrorCallback): void; + login(role: string, callback: ErrorCallback): void; + login(role: string, extend: Object, callback: ErrorCallback): void; + logout(callback: ErrorCallback): void; + isLoggedIn(role?: string): boolean; + isGuest(): boolean; + isFresh(): boolean; + setRole(role: string): Session; + getRole(): string; + hasRole(role: string): boolean; + } +} + +declare module "easy-session" { + import express = require('express'); + + interface SessionOptions { + ipCheck?: boolean; + uaCheck?: boolean; + freshTimeout?: number; + maxFreshTimeout?: number; + } + + export function main(session: any, options?: SessionOptions): express.RequestHandler; + export function isLoggedIn(errorCallback?: Function): express.RequestHandler; + export function isFresh(errorCallback?: Function): express.RequestHandler; + export function checkRole(role: string, errorCallback?: Function): express.RequestHandler; +} \ No newline at end of file diff --git a/ember/ember.d.ts b/ember/ember.d.ts index 22cbb8ab5..636a7af68 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -444,7 +444,7 @@ declare module Ember { static metaForProperty(key: string): {}; static isClass: boolean; static isMethod: boolean; - static initializer(arguments?: ApplicationInitializerArguments): void; + static initializer(args?: ApplicationInitializerArguments): void; /** Call advanceReadiness after any asynchronous setup logic has completed. Each call to deferReadiness must be matched by a call to advanceReadiness @@ -1318,9 +1318,9 @@ declare module Ember { Creates an instance of the class. @param arguments A hash containing values with which to initialize the newly instantiated object. **/ - static create(arguments?: {}): T; + static create(args: {}): T; detect(obj: any): boolean; - reopen(arguments?: {}): T; + reopen(args?: {}): T; } class MutableArray implements Array, MutableEnumberable { addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; @@ -1581,17 +1581,17 @@ declare module Ember { /** Creates a subclass of the Object class. **/ - static extend(arguments?: CoreObjectArguments): T; - static extend(mixins? : Mixin, arguments?: CoreObjectArguments): T; + static extend(args?: CoreObjectArguments): T; + static extend(mixins? : Mixin, args?: CoreObjectArguments): T; /** Creates an instance of the class. @param arguments A hash containing values with which to initialize the newly instantiated object. **/ - static create(arguments?: {}): T; + static create(args?: {}): T; /** Equivalent to doing extend(arguments).create(). If possible use the normal create method instead. **/ - static createWithMixins(arguments?: {}): T; + static createWithMixins(args?: {}): T; static detect(obj: any): boolean; static detectInstance(obj: any): boolean; /** @@ -1608,13 +1608,13 @@ declare module Ember { Augments a constructor's prototype with additional properties and functions. To add functions and properties to the constructor itself, see reopenClass. **/ - static reopen(arguments?: {}): T; + static reopen(args?: {}): T; /** Augments a constructor's own properties and functions. To add functions and properties to instances of a constructor by extending the constructor's prototype see reopen. **/ - static reopenClass(arguments?: {}): T; + static reopenClass(args?: {}): T; static isClass: boolean; static isMethod: boolean; addObserver: ModifyObserver; diff --git a/esprima/esprima-tests.ts b/esprima/esprima-tests.ts index d2635a404..f1a0f7ad9 100644 --- a/esprima/esprima-tests.ts +++ b/esprima/esprima-tests.ts @@ -1,27 +1,12 @@ +/// /// import esprima = require('esprima'); -import Syntax = esprima.Syntax; var token: esprima.Token; -var options: esprima.Options; -var comment: Syntax.Comment; -var program: Syntax.Program; -var statement: Syntax.Statement; -var expression: Syntax.Expression; -var property: Syntax.Property; -var identifier: Syntax.Identifier; -var literal: Syntax.Literal; -var switchCase: Syntax.SwitchCase; -var catchClause: Syntax.CatchClause; -var variableDeclaratorOrExpression: Syntax.VariableDeclaratorOrExpression; -var literalOrIdentifier: Syntax.LiteralOrIdentifier; -var blockStatementOrExpression: Syntax.BlockStatementOrExpression; -var identifierOrExpression: Syntax.IdentifierOrExpression; -var any: any; +var comment: esprima.Comment; +var program: ESTree.Program; var string: string; -var boolean: boolean; -var number: number; // esprima string = esprima.version; @@ -34,171 +19,5 @@ token = esprima.tokenize('code', {range: true})[0]; string = token.type; string = token.value; -// Program -string = program.type; -statement = program.body[0]; -comment = program.comments[0] - -// Location -number = program.loc.start.line; -number = program.loc.start.column; -number = program.loc.end.line; -number = program.loc.end.column; -number = program.range[0]; - // Comment string = comment.value; - -// Statement -// BlockStatement -var blockStatement: Syntax.BlockStatement; -string = blockStatement.type; -statement = blockStatement.body[0]; -comment = blockStatement.leadingComments[0]; -comment = blockStatement.trailingComments[0]; - -// ExpressionStatement -var expressionStatement: Syntax.ExpressionStatement; -expression = expressionStatement.expression; - -// IfStatement -var ifStatement: Syntax.IfStatement; -expression = ifStatement.test; -statement = ifStatement.consequent; -statement = ifStatement.alternate; - -// LabeledStatement -var labeledStatement: Syntax.LabeledStatement; -identifier = labeledStatement.label; -statement = labeledStatement.body; - -// WithStatement -var withStatement: Syntax.WithStatement; -expression = withStatement.object; - -// SwitchStatement -var switchStatement: Syntax.SwitchStatement; -expression = switchStatement.discriminant; -switchCase = switchStatement.cases[0]; -boolean = switchStatement.lexical; - -// ReturnStatement -var returnStatement: Syntax.ReturnStatement; -expression = returnStatement.argument; - -// TryStatement -var tryStatement: Syntax.TryStatement; -blockStatement = tryStatement.block; -catchClause = tryStatement.handler; -catchClause = tryStatement.guardedHandlers[0]; -blockStatement = tryStatement.finalizer; - -// ForStatement -var forStatement: Syntax.ForStatement; -variableDeclaratorOrExpression = forStatement.init; -expression = forStatement.update; - -// ForInStatement -var forInStatement: Syntax.ForInStatement; -variableDeclaratorOrExpression = forInStatement.left; -expression = forInStatement.right; -boolean = forInStatement.each; - -// Expression -// ArrayExpression -var arrayExpression: Syntax.ArrayExpression; -string = arrayExpression.type; -expression = arrayExpression.elements[0]; - -// ObjectExpression -var objectExpression: Syntax.ObjectExpression; -property = objectExpression.properties[0]; -string = property.type; -literalOrIdentifier = property.key; -expression = property.value; -string = property.kind; - -// FunctionExpression -var functionExpression: Syntax.FunctionExpression; -identifier = functionExpression.id; -identifier = functionExpression.params[0]; -expression = functionExpression.defaults[0]; -identifier = functionExpression.rest; -blockStatementOrExpression = functionExpression.body; -boolean = functionExpression.generator; -boolean = functionExpression.expression; - -// SequenceExpression -var sequenceExpression: Syntax.SequenceExpression; -expression = sequenceExpression.expressions[0] - -// UnaryExpression -var unaryExpression: Syntax.UnaryExpression; -string = unaryExpression.operator; -boolean = unaryExpression.prefix; - -// BinaryExpression -var binaryExpression: Syntax.BinaryExpression; -expression = binaryExpression.left; -expression = binaryExpression.right; - -// ConditionalExpression -var conditionalExpression: Syntax.ConditionalExpression; -expression = conditionalExpression.test; -expression = conditionalExpression.alternate; -expression = conditionalExpression.consequent; - -// NewExpression -var newExpression: Syntax.NewExpression; -expression = newExpression.callee; -expression = newExpression.arguments[0]; - -// CallExpression -var callExpression: Syntax.CallExpression; -expression = callExpression.callee; -expression = callExpression.arguments[0]; - -// MemberExpression -var memberExpression: Syntax.MemberExpression; -expression = memberExpression.object; -identifierOrExpression = memberExpression.property; -boolean = memberExpression.computed; - -// Declarations -var functionDeclaration: Syntax.FunctionDeclaration; -identifier = functionDeclaration.id; -var params:Syntax.Identifier[] = functionDeclaration.params; -var defaults:Syntax.Expression[] = functionDeclaration.defaults; -identifier = functionDeclaration.rest; -var body:Syntax.BlockStatementOrExpression = functionDeclaration.body; -boolean = functionDeclaration.generator; -boolean = functionDeclaration.expression; - -var variableDeclaration: Syntax.VariableDeclaration; -var declarations:Syntax.VariableDeclarator[] = variableDeclaration.declarations; -string = variableDeclaration.kind; // "var" | "let" | "const" - -var variableDeclarator: Syntax.VariableDeclarator; -identifier = variableDeclarator.id; // Pattern -expression = variableDeclarator.init; - -// Clauses -// SwitchCase -string = switchCase.type; -expression = switchCase.test; -statement = switchCase.consequent[0]; - -// CatchClause -string = catchClause.type; -identifier = catchClause.param; -expression = catchClause.guard; -blockStatement = catchClause.body; - -// Misc -// Identifier -string = identifier.type; -string = identifier.name; - -// Literal -string = literal.type; -any = literal.value; diff --git a/esprima/esprima.d.ts b/esprima/esprima.d.ts index d62bb09bb..10e37a530 100644 --- a/esprima/esprima.d.ts +++ b/esprima/esprima.d.ts @@ -1,18 +1,24 @@ -// Type definitions for Esprima v1.2.0 +// Type definitions for Esprima v2.1.0 // Project: http://esprima.org -// Definitions by: teppeis +// Definitions by: teppeis , RReverser // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module esprima { - var version: string; - function parse(code: string, options?: Options): Syntax.Program; - function tokenize(code: string, options?: Options): Array; + var version: string + function parse(code: string, options?: Options): ESTree.Program + function tokenize(code: string, options?: Options): Array interface Token { type: string value: string } + interface Comment extends ESTree.Node { + value: string + } + interface Options { loc?: boolean range?: boolean @@ -23,244 +29,6 @@ declare module esprima { tolerant?: boolean source?: boolean } - - module Syntax { - // Node - interface Node { - type: string - loc?: LineLocation - range?: number[] - leadingComments?: Comment[] - trailingComments?: Comment[] - } - interface LineLocation { - start: Position - end: Position - } - interface Position { - line: number - column: number - } - - // Comment - interface Comment extends Node { - value: string - } - - // Program - interface Program extends Node { - body: Statement[] - comments?: Comment[] - } - - // Function - interface Function extends Node { - id: Identifier // | null - params: Identifier[] - defaults: Expression[] - rest: Identifier // | null - body: BlockStatementOrExpression - generator: boolean - expression: boolean - } - interface BlockStatementOrExpression extends BlockStatement, Expression { - } - - // Statement - interface Statement extends Node { - } - interface EmptyStatement extends Statement { - } - interface BlockStatement extends Statement { - body: Statement[] - } - interface ExpressionStatement extends Statement { - expression: Expression - } - interface IfStatement extends Statement { - test: Expression - consequent: Statement - alternate: Statement - } - interface LabeledStatement extends Statement { - label: Identifier - body: Statement - } - interface BreakStatement extends Statement { - label: Identifier // | null - } - interface ContinueStatement extends Statement { - label: Identifier // | null - } - interface WithStatement extends Statement { - object: Expression - body: Statement - } - interface SwitchStatement extends Statement { - discriminant: Expression - cases: SwitchCase[] - lexical: boolean - } - interface ReturnStatement extends Statement { - argument: Expression // | null - } - interface ThrowStatement extends Statement { - argument: Expression - } - interface TryStatement extends Statement { - block: BlockStatement - handler: CatchClause // | null - guardedHandlers: CatchClause[] - finalizer: BlockStatement // | null - } - interface WhileStatement extends Statement { - test: Expression - body: Statement - } - interface DoWhileStatement extends Statement { - body: Statement - test: Expression - } - interface ForStatement extends Statement { - init: VariableDeclaratorOrExpression // | null - test: Expression // | null - update: Expression // | null - body: Statement - } - interface ForInStatement extends Statement { - left: VariableDeclaratorOrExpression - right: Expression - body: Statement - each: boolean - } - interface VariableDeclaratorOrExpression extends VariableDeclarator, Expression { - } - interface DebuggerStatement extends Statement { - } - interface StatementOrList extends Array, Statement { - } - - // Declaration - interface Declaration extends Statement { - } - interface FunctionDeclaration extends Declaration { - id: Identifier - params: Identifier[] // Pattern - defaults: Expression[] - rest: Identifier - body: BlockStatementOrExpression - generator: boolean - expression: boolean - } - interface VariableDeclaration extends Declaration { - declarations: VariableDeclarator[] - kind: string // "var" | "let" | "const" - } - interface VariableDeclarator extends Node { - id: Identifier // Pattern - init: Expression - } - - // Expression - interface Expression extends Node { // | Pattern - } - //interface Expression extends - // ThisExpression, ArrayExpression, ObjectExpression, FunctionExpression, - // ArrowFunctionExpression, SequenceExpression, UnaryExpression, BinaryExpression, - // AssignmentExpression, UpdateExpression, LogicalExpression, ConditionalExpression, - // NewExpression, CallExpression, MemberExpression { - //} - interface ThisExpression extends Expression { - } - interface ArrayExpression extends Expression { - elements: Expression[] // [ Expression | null ] - } - interface ObjectExpression extends Expression { - properties: Property[] - } - interface Property extends Node { - key: LiteralOrIdentifier // Literal | Identifier - value: Expression - kind: string // "init" | "get" | "set" - } - interface LiteralOrIdentifier extends Literal, Identifier { - } - interface FunctionExpression extends Function, Expression { - } - interface ArrowFunctionExpression extends Function, Expression { - } - interface SequenceExpression extends Expression { - expressions: Expression[] - } - interface UnaryExpression extends Expression { - operator: string // UnaryOperator - prefix: boolean - argument: Expression - } - interface BinaryExpression extends Expression { - operator: string // BinaryOperator - left: Expression - right: Expression - } - interface AssignmentExpression extends Expression { - operator: string // AssignmentOperator - left: Expression - right: Expression - } - interface UpdateExpression extends Expression { - operator: string // UpdateOperator - argument: Expression - prefix: boolean - } - interface LogicalExpression extends Expression { - operator: string // LogicalOperator - left: Expression - right: Expression - } - interface ConditionalExpression extends Expression { - test: Expression - alternate: Expression - consequent: Expression - } - interface NewExpression extends Expression { - callee: Expression - arguments: Expression[] - } - interface CallExpression extends Expression { - callee: Expression - arguments: Expression[] - } - interface MemberExpression extends Expression { - object: Expression - property: IdentifierOrExpression // Identifier | Expression - computed: boolean - } - interface IdentifierOrExpression extends Identifier, Expression { - } - - // Pattern - // interface Pattern extends Node { - // } - - // Clauses - interface SwitchCase extends Node { - test: Expression - consequent: Statement[] - } - interface CatchClause extends Node { - param: Identifier // Pattern - guard: Expression - body: BlockStatement - } - - // Misc - interface Identifier extends Node, Expression { // | Pattern - name: string - } - interface Literal extends Node, Expression { - value: any // string | boolean | null | number | RegExp - } - } } declare module "esprima" { diff --git a/estree/estree-tests.ts b/estree/estree-tests.ts new file mode 100644 index 000000000..bbf16586d --- /dev/null +++ b/estree/estree-tests.ts @@ -0,0 +1,177 @@ +/// + +var program: ESTree.Program; +var statement: ESTree.Statement; +var expression: ESTree.Expression; +var property: ESTree.Property; +var identifier: ESTree.Identifier; +var literal: ESTree.Literal; +var switchCase: ESTree.SwitchCase; +var catchClause: ESTree.CatchClause; +var pattern: ESTree.Pattern; +var assignmentPattern: ESTree.AssignmentPattern; +var variableDeclaratorOrExpression: ESTree.VariableDeclaration | ESTree.Expression; +var literalOrIdentifier: ESTree.Literal | ESTree.Identifier; +var blockStatementOrExpression: ESTree.BlockStatement | ESTree.Expression; +var identifierOrExpression: ESTree.Expression; +var any: any; +var string: string; +var boolean: boolean; +var number: number; + +// Program +string = program.type; +statement = program.body[0]; + +// Location +number = program.loc.start.line; +number = program.loc.start.column; +number = program.loc.end.line; +number = program.loc.end.column; +number = program.range[0]; + +// Statement +// BlockStatement +var blockStatement: ESTree.BlockStatement; +string = blockStatement.type; +statement = blockStatement.body[0]; + +// ExpressionStatement +var expressionStatement: ESTree.ExpressionStatement; +expression = expressionStatement.expression; + +// IfStatement +var ifStatement: ESTree.IfStatement; +expression = ifStatement.test; +statement = ifStatement.consequent; +statement = ifStatement.alternate; + +// LabeledStatement +var labeledStatement: ESTree.LabeledStatement; +identifier = labeledStatement.label; +statement = labeledStatement.body; + +// WithStatement +var withStatement: ESTree.WithStatement; +expression = withStatement.object; + +// SwitchStatement +var switchStatement: ESTree.SwitchStatement; +expression = switchStatement.discriminant; +switchCase = switchStatement.cases[0]; +boolean = switchStatement.lexical; + +// ReturnStatement +var returnStatement: ESTree.ReturnStatement; +expression = returnStatement.argument; + +// TryStatement +var tryStatement: ESTree.TryStatement; +blockStatement = tryStatement.block; +catchClause = tryStatement.handler; +blockStatement = tryStatement.finalizer; + +// ForStatement +var forStatement: ESTree.ForStatement; +variableDeclaratorOrExpression = forStatement.init; +expression = forStatement.update; + +// ForInStatement +var forInStatement: ESTree.ForInStatement; +variableDeclaratorOrExpression = forInStatement.left; +expression = forInStatement.right; + +// Expression +// ArrayExpression +var arrayExpression: ESTree.ArrayExpression; +string = arrayExpression.type; +expression = arrayExpression.elements[0]; + +// ObjectExpression +var objectExpression: ESTree.ObjectExpression; +property = objectExpression.properties[0]; +string = property.type; +expression = property.key; +expression = property.value; +string = property.kind; + +// FunctionExpression +var functionExpression: ESTree.FunctionExpression; +identifier = functionExpression.id; +assignmentPattern = functionExpression.params[0]; +pattern = assignmentPattern.left; +expression = assignmentPattern.right; +blockStatementOrExpression = functionExpression.body; +boolean = functionExpression.generator; + +// SequenceExpression +var sequenceExpression: ESTree.SequenceExpression; +expression = sequenceExpression.expressions[0] + +// UnaryExpression +var unaryExpression: ESTree.UnaryExpression; +string = unaryExpression.operator; +boolean = unaryExpression.prefix; + +// BinaryExpression +var binaryExpression: ESTree.BinaryExpression; +expression = binaryExpression.left; +expression = binaryExpression.right; + +// ConditionalExpression +var conditionalExpression: ESTree.ConditionalExpression; +expression = conditionalExpression.test; +expression = conditionalExpression.alternate; +expression = conditionalExpression.consequent; + +// NewExpression +var newExpression: ESTree.NewExpression; +expression = newExpression.callee; +expression = newExpression.arguments[0]; + +// CallExpression +var callExpression: ESTree.CallExpression; +expression = callExpression.callee; +expression = callExpression.arguments[0]; + +// MemberExpression +var memberExpression: ESTree.MemberExpression; +expression = memberExpression.object; +identifierOrExpression = memberExpression.property; +boolean = memberExpression.computed; + +// Declarations +var functionDeclaration: ESTree.FunctionDeclaration; +identifier = functionDeclaration.id; +var params:ESTree.Pattern[] = functionDeclaration.params; +var body:ESTree.BlockStatement | ESTree.Expression = functionDeclaration.body; +boolean = functionDeclaration.generator; + +var variableDeclaration: ESTree.VariableDeclaration; +var declarations:ESTree.VariableDeclarator[] = variableDeclaration.declarations; +string = variableDeclaration.kind; // "var" | "let" | "const" + +var variableDeclarator: ESTree.VariableDeclarator; +pattern = variableDeclarator.id; // Pattern +expression = variableDeclarator.init; + +// Clauses +// SwitchCase +string = switchCase.type; +expression = switchCase.test; +statement = switchCase.consequent[0]; + +// CatchClause +string = catchClause.type; +pattern = catchClause.param; +expression = catchClause.guard; +blockStatement = catchClause.body; + +// Misc +// Identifier +string = identifier.type; +string = identifier.name; + +// Literal +string = literal.type; +any = literal.value; diff --git a/estree/estree.d.ts b/estree/estree.d.ts new file mode 100644 index 000000000..329396b7c --- /dev/null +++ b/estree/estree.d.ts @@ -0,0 +1,369 @@ +// Type definitions for ESTree AST specification +// Project: https://github.com/estree/estree +// Definitions by: RReverser +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module ESTree { + interface Node { + type: string; + loc?: SourceLocation; + range?: [number, number]; + } + + interface SourceLocation { + source?: string; + start: Position; + end: Position; + } + + interface Position { + line: number; + column: number; + } + + interface Program extends Node { + body: Array; + sourceType: string; + } + + interface Function extends Node { + id?: Identifier; + params: Array; + body: BlockStatement | Expression; + generator: boolean; + } + + interface Statement extends Node {} + + interface EmptyStatement extends Statement {} + + interface BlockStatement extends Statement { + body: Array; + } + + interface ExpressionStatement extends Statement { + expression: Expression; + } + + interface IfStatement extends Statement { + test: Expression; + consequent: Statement; + alternate?: Statement; + } + + interface LabeledStatement extends Statement { + label: Identifier; + body: Statement; + } + + interface BreakStatement extends Statement { + label?: Identifier; + } + + interface ContinueStatement extends Statement { + label?: Identifier; + } + + interface WithStatement extends Statement { + object: Expression; + body: Statement; + } + + interface SwitchStatement extends Statement { + discriminant: Expression; + cases: Array; + lexical: boolean; + } + + interface ReturnStatement extends Statement { + argument?: Expression; + } + + interface ThrowStatement extends Statement { + argument: Expression; + } + + interface TryStatement extends Statement { + block: BlockStatement; + handler?: CatchClause; + finalizer?: BlockStatement; + } + + interface WhileStatement extends Statement { + test: Expression; + body: Statement; + } + + interface DoWhileStatement extends Statement { + body: Statement; + test: Expression; + } + + interface ForStatement extends Statement { + init?: VariableDeclaration | Expression; + test?: Expression; + update?: Expression; + body: Statement; + } + + interface ForInStatement extends Statement { + left: VariableDeclaration | Expression; + right: Expression; + body: Statement; + } + + interface DebuggerStatement extends Statement {} + + interface Declaration extends Statement {} + + interface FunctionDeclaration extends Function, Declaration { + id: Identifier; + } + + interface VariableDeclaration extends Declaration { + declarations: Array; + kind: string; + } + + interface VariableDeclarator extends Node { + id: Pattern; + init?: Expression; + } + + interface Expression extends Node {} + + interface ThisExpression extends Expression {} + + interface ArrayExpression extends Expression { + elements: Array; + } + + interface ObjectExpression extends Expression { + properties: Array; + } + + interface Property extends Node { + key: Expression; + value: Expression; + kind: string; + method: boolean; + shorthand: boolean; + computed: boolean; + } + + interface FunctionExpression extends Function, Expression {} + + interface SequenceExpression extends Expression { + expressions: Array; + } + + interface UnaryExpression extends Expression { + operator: UnaryOperator; + prefix: boolean; + argument: Expression; + } + + interface BinaryExpression extends Expression { + operator: BinaryOperator; + left: Expression; + right: Expression; + } + + interface AssignmentExpression extends Expression { + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; + } + + interface UpdateExpression extends Expression { + operator: UpdateOperator; + argument: Expression; + prefix: boolean; + } + + interface LogicalExpression extends Expression { + operator: LogicalOperator; + left: Expression; + right: Expression; + } + + interface ConditionalExpression extends Expression { + test: Expression; + alternate: Expression; + consequent: Expression; + } + + interface CallExpression extends Expression { + callee: Expression | Super; + arguments: Array; + } + + interface NewExpression extends CallExpression {} + + interface MemberExpression extends Expression, Pattern { + object: Expression | Super; + property: Expression; + computed: boolean; + } + + interface Pattern extends Node {} + + interface SwitchCase extends Node { + test?: Expression; + consequent: Array; + } + + interface CatchClause extends Node { + param: Pattern; + guard: any; + body: BlockStatement; + } + + interface Identifier extends Node, Expression, Pattern { + name: string; + } + + interface Literal extends Node, Expression { + value?: string | boolean | number | RegExp; + } + + interface RegexLiteral extends Literal { + regex: { + pattern: string; + flags: string; + }; + } + + type UnaryOperator = string; + + type BinaryOperator = string; + + type LogicalOperator = string; + + type AssignmentOperator = string; + + type UpdateOperator = string; + + interface ForOfStatement extends ForInStatement {} + + interface Super extends Node {} + + interface SpreadElement extends Node { + argument: Expression; + } + + interface ArrowFunctionExpression extends Function, Expression { + expression: boolean; + } + + interface YieldExpression extends Expression { + argument?: Expression; + } + + interface TemplateLiteral extends Expression { + quasis: Array; + expressions: Array; + } + + interface TaggedTemplateExpression extends Expression { + tag: Expression; + quasi: TemplateLiteral; + } + + interface TemplateElement extends Node { + tail: boolean; + value: { + cooked: string; + value: string; + }; + } + + interface AssignmentProperty extends Property { + value: Pattern; + kind: string; + method: boolean; + } + + interface ObjectPattern extends Pattern { + properties: Array; + } + + interface ArrayPattern extends Pattern { + elements: Array; + } + + interface RestElement extends Pattern { + argument: Pattern; + } + + interface AssignmentPattern extends Pattern { + left: Pattern; + right: Expression; + } + + interface Class extends Node { + id?: Identifier; + superClass: Expression; + body: ClassBody; + } + + interface ClassBody extends Node { + body: Array; + } + + interface MethodDefinition extends Node { + key: Identifier; + value: FunctionExpression; + kind: string; + computed: boolean; + static: boolean; + } + + interface ClassDeclaration extends Class, Declaration { + id: Identifier; + } + + interface ClassExpression extends Class, Expression {} + + interface MetaProperty extends Expression { + meta: Identifier; + property: Identifier; + } + + interface ImportDeclaration extends Node { + specifiers: Array; + source: Literal; + } + + interface ImportSpecifier { + imported: Identifier; + local: Identifier; + } + + interface ImportDefaultSpecifier { + local: Identifier; + } + + interface ImportNamespaceSpecifier { + local: Identifier; + } + + interface ExportNamedDeclaration extends Node { + declaration?: Declaration; + specifiers: Array; + source?: Literal; + } + + interface ExportSpecifier { + exported: Identifier; + local: Identifier; + } + + interface ExportDefaultDeclaration extends Node { + declaration: Declaration | Expression; + } + + interface ExportAllDeclaration extends Node { + source: Literal; + } +} \ No newline at end of file diff --git a/express-debug/express-debug-tests.ts b/express-debug/express-debug-tests.ts new file mode 100644 index 000000000..6f702856e --- /dev/null +++ b/express-debug/express-debug-tests.ts @@ -0,0 +1,21 @@ +/// + +import express = require('express'); +import debug = require('express-debug'); +var app = express(); + +debug(app, { + depth: 4, + theme: 'public/css/debug.css', + extra_panels: [{ + name: 'mypanel', + template: '/absolute/path/to/mypanel.jade', + process: function(locals) { + return { locals: { mypanel: true, }}; + } + }], + panels: ['locals', 'request', 'session'], + path: '/express-debug', + extra_attrs: '', + sort: false, +}); diff --git a/express-debug/express-debug.d.ts b/express-debug/express-debug.d.ts new file mode 100644 index 000000000..d185f5c69 --- /dev/null +++ b/express-debug/express-debug.d.ts @@ -0,0 +1,83 @@ +// Type definitions for express-debug 1.1.1 +// Project: https://github.com/devoidfury/express-debug +// Definitions by: Federico Bond +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* =================== USAGE =================== + + import debug = require('express-debug'); + debug(app, options); + + =============================================== */ + +/// + +declare module "express-debug" { + import express = require('express'); + + interface CustomPanel { + name: string; + + template: string; + + process(locals: any): any; + + standalone?: boolean; + + initialize?(req: express.Request): void; + + finalize?(req: express.Request): void; + + pre_render?(req: express.Request): void; + + post_render?(req: express.Request): void; + + options?: any; + } + + /** + * Node.js middleware for serving a favicon. + */ + function debug(app: express.Application, settings?: { + /** + * How deep to recurse through printed objects. This is the default unless the + * print_obj function is passed an options object with a 'depth' property. + */ + depth?: number; + + /** + * Absolute path to a css file to include and override EDT's default css. + */ + theme?: string; + + /** + * Additional panels to show. + */ + extra_panels?: CustomPanel[]; + + /** + * Allows changing the default panel. + */ + panels?: string[]; + + /** + * Path to render standalone express-debug. + */ + path?: string; + + /** + * If you need to add arbitrary attributes to the containing element of EDT, + * this allows you to. + */ + extra_attrs?: string; + + /** + * Global option to determine sort order of printed object values. false for + * default order, true for basic default sort, or a function to use for sort. + */ + sort?: boolean | ((a: number, b: number) => number); + + }): void; + + export = debug; +} diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index eb85899c4..3ba451c8a 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1345,6 +1345,55 @@ declare module google.maps { } export module places { + + export class AutocompleteService extends MVCObject { + constructor(); + getPlacePredictions(request: AutocompletionRequest, callback: (result: AutocompletePrediction[], status: PlacesServiceStatus) => void): void; + getQueryPredictions(request: QueryAutocompletionRequest, callback: (result: QueryAutocompletePrediction[], status: PlacesServiceStatus) => void): void; + } + + export interface AutocompletionRequest { + input: string; + bounds?: LatLngBounds; + componentRestrictions?: ComponentRestrictions; + location?: LatLng; + offset?: number; + radius?: number; + types?: string[]; + } + + export interface QueryAutocompletionRequest { + input: string; + bounds?: LatLngBounds; + location?: LatLng; + offset?: number; + radius?: number; + } + + export interface AutocompletePrediction { + description: string; + matched_substrings: PredictionSubstring[]; + place_id: string; + terms: PredictionTerm[]; + types: string[] + } + + export interface PredictionTerm { + offset: number; + value: string; + } + + export interface PredictionSubstring { + length: number; + offset: number; + } + + export interface QueryAutocompletePrediction { + description: string; + matched_substrings: PredictionSubstring[]; + place_id: string; + terms: PredictionTerm[]; + } export class Autocomplete extends MVCObject { constructor (inputField: HTMLInputElement, opts?: AutocompleteOptions); diff --git a/grecaptcha/grecaptcha-tests.ts b/grecaptcha/grecaptcha-tests.ts new file mode 100644 index 000000000..cfc86e71b --- /dev/null +++ b/grecaptcha/grecaptcha-tests.ts @@ -0,0 +1,21 @@ +/// + +var params: ReCaptchaV2.Parameters = { + "sitekey": "mySuperSecretKey", + "theme": "black", // no type-checking here. + "type": "image", + "tabindex": 5, + "callback": (response: string) => { }, + "expired-callback": () => { }, +} + +var id1: number = grecaptcha.render("foo"); +var id2: number = grecaptcha.render("foo", params); +var id3: number = grecaptcha.render(document.getElementById("foo")); +var id4: number = grecaptcha.render(document.getElementById("foo"), params); + +// response takes a number and returns a string +var response1: string = grecaptcha.getResponse(id1); + +// reset takes a number +grecaptcha.reset(id1); diff --git a/grecaptcha/grecaptcha.d.ts b/grecaptcha/grecaptcha.d.ts new file mode 100644 index 000000000..e246aaf17 --- /dev/null +++ b/grecaptcha/grecaptcha.d.ts @@ -0,0 +1,67 @@ +// Type definitions for Google Recaptcha v2 +// Project: https://www.google.com/recaptcha +// Definitions by: Kristof Mattei +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var grecaptcha: ReCaptchaV2.ReCaptcha; + +declare module ReCaptchaV2 +{ + class ReCaptcha + { + /** + * Renders the container as a reCAPTCHA widget and returns the ID of the newly created widget. + * @param container The HTML element to render the reCAPTCHA widget. Specify either the ID of the container (string) or the DOM element itself. + * @param parameters An object containing parameters as key=value pairs, for example, {"sitekey": "your_site_key", "theme": "light"}. See @see render parameters. + * @return the ID of the newly created widget. + **/ + render(container: (string | HTMLElement), parameters?: Parameters): number; + /** + * Resets the reCAPTCHA widget. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + **/ + reset(opt_widget_id?: number): void; + /** + * Gets the response for the reCAPTCHA widget. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + * @return the response of the reCAPTCHA widget. + **/ + getResponse(opt_widget_id?: number): string; + } + + interface Parameters + { + /** + * Your sitekey. + **/ + sitekey: string; + /** + * Optional. The color theme of the widget. + * Accepted values: "light", "dark" + * @default "light" + **/ + theme?: string; + /** + * Optional. The type of CAPTCHA to serve. + * Accepted values: "audio ", "image" + * @default "image" + **/ + type?: string; + /** + * Optional. The tabindex of the widget and challenge. + * If other elements in your page use tabindex, it should be set to make user navigation easier. + **/ + tabindex?: number; + /** + * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. + * The user's response, g-recaptcha-response, will be the input for your callback function. + **/ + callback?: (response: string) => void; + /** + * Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. + **/ + // Notice to the reader + // I need to surround this object with quotes, this will however break intellisense in VS 2013. + "expired-callback"?: () => void; + } +} diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index 058903637..11ad81d2d 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -21,6 +21,12 @@ plugin.register.attributes = { version: "1.0.0" }; +// optional options parameter +server.register({}, function (err) {}); + +// optional options.routes.vhost parameter +server.register({}, { select: 'api', routes: { prefix: '/prefix' } }, function (err) {}); + //server.pack.register(plugin, (err: Object) => { // if (err) { throw err; } //}); @@ -76,5 +82,18 @@ server.route([{ } }]); +// config.validate parameters should be optional +server.route([{ + method: 'GET', + path: '/hello2', + handler: function(request: Hapi.Request, reply: Function) { + reply('hello world2'); + }, + config: { + validate: { + } + } +}]); + // Start the server server.start(); diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 61a2ef2d5..de8dba6b8 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -147,11 +147,11 @@ declare module "hapi" { }; /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ - mime: any; + mime?: any; /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ - minimal: boolean; + minimal?: boolean; /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ - plugins: IDictionary; + plugins?: IDictionary; } @@ -568,7 +568,7 @@ declare module "hapi" { optionsthe server validation options. next(err, value)the callback function called when validation is completed. */ - headers: boolean | IJoi | IValidationFunction; + headers?: boolean | IJoi | IValidationFunction; /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: @@ -579,7 +579,7 @@ declare module "hapi" { valuethe object containing the path parameters. optionsthe server validation options. next(err, value)the callback function called when validation is completed. */ - params: boolean | IJoi | IValidationFunction; + params?: boolean | IJoi | IValidationFunction; /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: trueany query parameters allowed (no validation performed).This is the default. falseno query parameters allowed. @@ -588,7 +588,7 @@ declare module "hapi" { valuethe object containing the query parameters. optionsthe server validation options. next(err, value)the callback function called when validation is completed. */ - query: boolean | IJoi | IValidationFunction; + query?: boolean | IJoi | IValidationFunction; /** validation rules for an incoming request payload (request body).Values allowed: trueany payload allowed (no validation performed).This is the default. falseno payload allowed. @@ -597,9 +597,9 @@ declare module "hapi" { valuethe object containing the payload object. optionsthe server validation options. next(err, value)the callback function called when validation is completed. */ - payload: boolean | IJoi | IValidationFunction; + payload?: boolean | IJoi | IValidationFunction; /** an optional object with error fields copied into every validation error response. */ - errorFields: any; + errorFields?: any; /** determines how to handle invalid requests.Allowed values are: 'error'return a Bad Request (400) error response.This is the default value. 'log'log the error but continue processing the request. @@ -609,9 +609,9 @@ declare module "hapi" { replythe continuation reply interface. sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). errorthe error object prepared for the client response (including the validation function error under error.data). */ - failAction: string | IRouteFailFunction; + failAction?: string | IRouteFailFunction; /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ - options: any; + options?: any; }; /** define timeouts for processing durations: */ timeout?: { @@ -726,7 +726,7 @@ declare module "hapi" { a relative or absolute file path string (relative paths are resolved based on the route files configuration). a function with the signature function(request) which returns the relative or absolute file path. an object with the following options */ - file: string | IRequestHandler |IFileHandlerConfig; + file?: string | IRequestHandler |IFileHandlerConfig; /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. @@ -738,7 +738,7 @@ declare module "hapi" { redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ - directory: { + directory?: { path: string |Array | IRequestHandler | IRequestHandler>; index?: boolean; listing?: boolean; @@ -748,7 +748,7 @@ declare module "hapi" { defaultExtension?: string; }; proxy?: IProxyHandlerConfig; - view: string | { + view?: string | { template: string; context: { payload: any; @@ -757,7 +757,7 @@ declare module "hapi" { pre: any; } }; - config: { + config?: { handler: any; bind: any; app: any; @@ -2051,11 +2051,13 @@ declare module "hapi" { register(plugins: any|any[], options: { select: string|string[]; routes: { - prefix: string; vhost: string|string[] + prefix: string; vhost?: string|string[] }; } , callback: (err: any) => void):void; + register(plugins: any|any[], callback: (err: any) => void):void; + /**server.render(template, context, [options], callback) Utilizes the server views manager to render a template where: template - the template filename and path, relative to the views manager templates path (path or relativeTo). diff --git a/he/he-tests.ts b/he/he-tests.ts new file mode 100644 index 000000000..395eb94ef --- /dev/null +++ b/he/he-tests.ts @@ -0,0 +1,52 @@ +/// + +import he = require('he'); + +function main() { + var result: string; + + result = he.encode('foo \xa9 bar \u2260 baz qux'); + // 'foo © bar ≠ baz qux' + + he.encode('foo \0 bar'); + // 'foo \0 bar' + + // Passing an `options` object to `encode`, to explicitly disallow named references: + he.encode('foo \xa9 bar \u2260 baz qux', { + 'useNamedReferences': false + }); + + he.encode('foo \xa9 bar \u2260 baz qux', { + 'encodeEverything': true + }); + + he.encode('foo \xa9 bar \u2260 baz qux', { + 'encodeEverything': true, + 'useNamedReferences': true + }); + + he.encode('\x01', { + 'strict': false + }); + // '' + + he.encode('foo © and & ampersand', { + 'allowUnsafeSymbols': true + }); + + // Override the global default setting: + he.encode.options.useNamedReferences = true; + + he.decode('foo © bar ≠ baz 𝌆 qux'); + + he.decode('foo&bar', { + 'isAttributeValue': false + }); + + he.decode('foo&bar', { + 'strict': false + }); + + he.decode.options.isAttributeValue = true; + he.escape(''); +} diff --git a/he/he.d.ts b/he/he.d.ts new file mode 100644 index 000000000..6c96840c2 --- /dev/null +++ b/he/he.d.ts @@ -0,0 +1,114 @@ +// Type definitions for he v0.5.0 +// Project: https://github.com/mathiasbynens/he +// Definitions by: Simon Edwards +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// he - "HTML Entities" - A high quality pair of HTML encode and decode functions. + +declare module "he" { + + var version: string; + + interface EncodeOptions { + /** + * The default value for the useNamedReferences option is false. This + * means that encode() will not use any named character references + * (e.g. ©) in the output — hexadecimal escapes (e.g. ©) will + * be used instead. Set it to true to enable the use of named references. + */ + useNamedReferences?: boolean; + + /** + * The default value for the encodeEverything option is false. This means + * that encode() will not use any character references for printable ASCII + * symbols that don’t need escaping. Set it to true to encode every symbol + * in the input string. When set to true, this option takes precedence over + * allowUnsafeSymbols (i.e. setting the latter to true in such a case has + * no effect). + */ + encodeEverything?: boolean; + + /** + * The default value for the strict option is false. This means that + * encode() will encode any HTML text content you feed it, even if it + * contains any symbols that cause parse errors. To throw an error when such + * invalid HTML is encountered, set the strict option to true. This option + * makes it possible to use he as part of HTML parsers and HTML validators. + */ + strict?: boolean; + + /** + * The default value for the allowUnsafeSymbols option is false. This means + * that characters that are unsafe for use in HTML content (&, <, >, ", ', + * and `) will be encoded. When set to true, only non-ASCII characters will + * be encoded. If the encodeEverything option is set to true, this option + * will be ignored. + */ + allowUnsafeSymbols?: boolean; + } + + interface Encode { + /** + * Encode a string of text + * + * This function takes a string of text and encodes (by default) any symbols + * that aren’t printable ASCII symbols and &, <, >, ", ', and `, replacing + * them with character references. + * + * As long as the input string contains allowed code points only, the return + * value of this function is always valid HTML. Any (invalid) code points + * that cannot be represented using a character reference in the input are + * not encoded. + */ + (text: string, options?: EncodeOptions): string; + + options: EncodeOptions; + } + var encode: Encode; + + interface DecodeOptions { + /** + * The default value for the isAttributeValue option is false. This means + * that decode() will decode the string as if it were used in a text + * context in an HTML document. HTML has different rules for parsing + * character references in attribute values — set this option to true to + * treat the input string as if it were used as an attribute value. + */ + isAttributeValue?: boolean; + + /** + * The default value for the strict option is false. This means that + * decode() will decode any HTML text content you feed it, even if it + * contains any entities that cause parse errors. To throw an error when + * such invalid HTML is encountered, set the strict option to true. This + * option makes it possible to use he as part of HTML parsers and HTML + * validators. + */ + strict?: boolean; + } + + interface Decode { + /** + * Decode a string of HTML text + * + * This function takes a string of HTML and decodes any named and numerical + * character references in it using the algorithm described in section + * 12.2.4.69 of the HTML spec. + */ + (html: string, options?: DecodeOptions): string; + + options: DecodeOptions; + } + var decode: Decode; + + /** + * Escape XML entities + * + * This function takes a string of text and escapes it for use in text + * contexts in XML or HTML documents. Only the following characters are + * escaped: &, <, >, ", ', and `. + */ + function escape(text: string): string; + + var unescape: Decode; +} diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index ef0572303..8e3365eaf 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -1,6 +1,6 @@ /// -// tests based on http://jasmine.github.io/2.0/introduction.html +// tests based on http://jasmine.github.io/2.2/introduction.html describe("A suite", function () { it("contains spec with an expectation", function () { @@ -248,7 +248,8 @@ describe("Pending specs", function () { it("can be declared by calling 'pending' in the spec body", function () { expect(true).toBe(false); - pending(); + pending(); // without reason + pending('this is why it is pending'); }); }); diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index 3727f8839..64936f442 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine 2.1 +// Type definitions for Jasmine 2.2 // Project: http://jasmine.github.io/ // Definitions by: Boris Yankov , Theodore Brown , David Pärsson // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -18,7 +18,7 @@ declare function xit(expectation: string, assertion?: () => void, timeout?: numb declare function xit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; /** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ -declare function pending(): void; +declare function pending(reason?: string): void; declare function beforeEach(action: () => void, timeout?: number): void; declare function beforeEach(action: (done: () => void) => void, timeout?: number): void; diff --git a/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts b/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts new file mode 100644 index 000000000..7d23caddf --- /dev/null +++ b/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts @@ -0,0 +1,23 @@ +/// +/// + +var foo = new $.JsonRpcClient({ ajaxUrl: '/backend/jsonrpc' }); +foo.call( + 'bar', ['A parameter', 'B parameter'], + function (result) { alert('Foo bar answered: ' + result.my_answer); }, + function (error) { console.log('There was an error', error); } +); + + +var foo = new $.JsonRpcClient({ ajaxUrl: '/backend/jsonrpc' }); +foo.batch( + function (batch) { + batch.call('bar', ['A parameter', 'B parameter'], function () { }, function () { }); + batch.call('baz', { parameters: 'could be object' }, function () { }, function () { }); + }, + function (all_result_array) { alert('All done.'); }, + function (error_data) { alert('Error in batch response.'); } + ); + +var foo = new $.JsonRpcClient({ ajaxUrl: '/backend/jsonrpc', socketUrl: 'ws://example.com/' }); +foo.call('bar', ['param'], function () { }, function () { }); \ No newline at end of file diff --git a/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts new file mode 100644 index 000000000..de008dc09 --- /dev/null +++ b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts @@ -0,0 +1,97 @@ +// Type definitions for jquery.jsonrpc 0.7.0 +// Project: https://github.com/Textalk/jquery.jsonrpcclient.js +// Definitions by: Maksim Karelov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JsonRpcClientOptions extends JQueryAjaxSettings { + ajaxUrl?: string; + headers?: {[key:string]: any}; + sockerUrl?: string; + onmessage?: () => void; + onopen?: () => void; + onclose?: () => void; + onerror?: () => void; + getSockect?: (onmessageCb: () => void) => WebSocket; +} + +interface JsonRpcClient { + /** + * @fn call + * @memberof JsonRpcClient + * + * @param {string} method The method to run on JSON-RPC server. + * @param {object|array} params The params; an array or object. + * @param {function} successCb A callback for successful request. + * @param {function} errorCb A callback for error. + * + * @return {object} Returns the deferred object that $.ajax returns or {null} for websockets + */ + call(method: string, params: Object | Array, successCb: (result: any) => void, errorCb: (result: any) => void): JQueryDeferred; + + /** + * Notify sends a command to the server that won't need a response. In http, there is probably + * an empty response - that will be dropped, but in ws there should be no response at all. + * + * This is very similar to call, but has no id and no handling of callbacks. + * + * @fn notify + * @memberof JsonRpcClient + * + * @param {string} method The method to run on JSON-RPC server. + * @param {object|array} params The params; an array or object. + * + * @return {object} Returns the deferred object that $.ajax returns or {null} for websockets + */ + notify(method: string, params: Object | Array): JQueryDeferred; + + /** + * Make a batch-call by using a callback. + * + * The callback will get an object "batch" as only argument. On batch, you can call the methods + * "call" and "notify" just as if it was a normal JsonRpcClient object, and all calls will be + * sent as a batch call then the callback is done. + * + * @fn batch + * @memberof JsonRpcClient + * + * @param {function} callback This function will get a batch handler to run call and notify on. + * @param {function} allDoneCb A callback function to call after all results have been handled. + * @param {function} errorCb A callback function to call if there is an error from the server. + * Note, that batch calls should always get an overall success, and the + * only error + */ + batch(callback: (batch: JsonRpcClient) => void, allDoneCb: (result: any) => void, errorCb: (error: any) => void): void; +} + +interface JsonRpcClientFactory { + /** + * @fn new + * @memberof JsonRpcClient + * + * @param {object} options An object stating the backends: + * ajaxUrl A url (relative or absolute) to a http(s) backend. + * headers An object that will be passed along to $.ajax in options.headers + * xhrFields An object that will be passed along to $.ajax in options.xhrFields + * socketUrl A url (relative of absolute) to a ws(s) backend. + * onmessage A socket message handler for other messages (non-responses). + * onopen A socket onopen handler. (Not used for custom getSocket.) + * onclose A socket onclose handler. (Not used for custom getSocket.) + * onerror A socket onerror handler. (Not used for custom getSocket.) + * getSocket A function returning a WebSocket or null. + * It must take an onmessage_cb and bind it to the onmessage event + * (or chain it before/after some other onmessage handler). + * Or, it could return null if no socket is available. + * The returned instance must have readyState <= 1, and if less than 1, + * react to onopen binding. + * timeout (optional) A number of ms to wait before timing out and failing a + * call. If specified a setTimeout will be used to keep track of calls + * made through a websocket. + */ + new (options?: JsonRpcClientOptions): JsonRpcClient; +} + +interface JQueryStatic { + JsonRpcClient: JsonRpcClientFactory; +} \ No newline at end of file diff --git a/jquery.dataTables/jquery.dataTables-1.9.4.d.ts b/jquery.dataTables/jquery.dataTables-1.9.4.d.ts new file mode 100755 index 000000000..9884b78e2 --- /dev/null +++ b/jquery.dataTables/jquery.dataTables-1.9.4.d.ts @@ -0,0 +1,479 @@ +// Type definitions for JQuery DataTables 1.9.4 +// Project: http://www.datatables.net +// Definitions by: Armin Sander +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// missing: +// - Static methods that are defined in JQueryStatic.fn are not typed. +// - Plugin and extension definitions are not typed. + +interface JQuery +{ + dataTable(param? :DataTables.Options) : DataTables.DataTable; +} + +declare module DataTables +{ + export interface DataTable + { + /// Perform a jQuery selector action on the table's TR elements (from the tbody) and return the resulting jQuery object. + $(selector:string, opts?:RowParams): JQuery; + $(selector:Node[], opts?:RowParams): JQuery; + $(selector:JQuery, opts?:RowParams): JQuery; + + /// Almost identical to $ in operation, but in this case returns the data for the matched rows. + _(selector:string, opts?:RowParams): any[]; + _(selector:Node[], opts?:RowParams): any[]; + _(selector:JQuery, opts?:RowParams): any[]; + + /// Add a single new row or multiple rows of data to the table. + fnAddData(data:any, redraw?:boolean) : number[]; + + /// This function will make DataTables recalculate the column sizes. + fnAdjustColumnSizing(redraw? : boolean) : void; + + /// Quickly and simply clear a table + fnClearTable(redraw? : boolean) : void; + + /// The exact opposite of 'opening' a row, this function will close any rows which are currently 'open'. + fnClose(node: Node) : number; + + /// Remove a row for the table + fnDeleteRow(index: number, callback?: () => void, redraw?: boolean) : any[]; + fnDeleteRow(tr: Node, callback?: () => void, redraw?: boolean) : any[]; + + /// Restore the table to it's original state in the DOM by removing all of DataTables enhancements, + /// alterations to the DOM structure of the table and event listeners. + fnDestroy(remove?: boolean) : void; + + /// Redraw the table + fnDraw(complete? : boolean) : void; + + /// Filter the input based on data + fnFilter(input: string, column? : number, regex?: boolean, smart? : boolean, showGlobal?: boolean, caseInsensitive? : boolean) : void; + + /// Get the data for the whole table, an individual row or an individual cell based on the provided parameters. + fnGetData(row?: Node, col? : number) : any; + fnGetData(row?: number, col? : number) : any; + + /// Get an array of the TR nodes that are used in the table's body. + fnGetNodes(row? : number) : any; // Node[] | Node + + /// Get the array indexes of a particular cell from it's DOM element and column index including hidden columns + fnGetPosition(node: Node) : any; // number | number[] + + /// Check to see if a row is 'open' or not. + fnIsOpen(tr: Node) : boolean; + + /// This function will place a new row directly after a row which is currently on display on the page, + /// with the HTML contents that is passed into the function. + fnOpen(node: Node, html: string, clazz: string) : Node; + fnOpen(node: Node, html: Node, clazz: string) : Node; + fnOpen(node: Node, html: JQuery, clazz: string) : Node; + + /// Change the pagination - provides the internal logic for pagination in a simple API function. + fnPageChange(action: string, redraw?: boolean) : void; + fnPageChange(page: number, redraw?: boolean) : void; + + /// Show a particular column + fnSetColumnVis(column: number, show: boolean, redraw?: boolean) : void; + + /// Get the settings for a particular table for external manipulation + fnSettings() : Settings; + + /// Sort the table by a particular column + fnSort(col: number) : void; + fnSort(col: any[][]) : void; + + /// Attach a sort listener to an element for a given column + fnSortListener(node: Node, column: number, callback? : () => void): void; + + /// Update a table cell or row - this method will accept either a single value to update the cell with, + /// an array of values with one element for each column or an object in the same format as the original data source. + fnUpdate(data: any, row: Node, column?:number, redraw?: boolean, action? : boolean) : number; + fnUpdate(data: any, dataIndex: number, column?:number, redraw?: boolean, action? : boolean) : number; + + /// Provide a common method for plug-ins to check the version of DataTables being used, + /// in order to ensure compatibility. + fnVersionCheck(version: string) : boolean; + } + + export interface Static + { + /// Provide a common method for plug-ins to check the version of DataTables being used, + /// in order to ensure compatibility. + fnVersionCheck(version: string) : boolean; + + /// Check if a TABLE node is a DataTable table already or not. + fnIsDataTable(table: Node) : boolean; + + /// Get all DataTable tables that have been initialised. + fnTables(visible? : boolean) : Node[]; + } + + export interface RowParams + { + /// Select TR elements that meet the current filter criterion ("applied") or all TR elements (i.e. no filter). + filter?: string; + + /// Order of the TR elements in the processed array. + /// Can be either 'current', whereby the current sorting of the table is used, or + /// 'original' whereby the original order the data was read into the table is used. + order?: string; + + /// Limit the selection to the currently displayed page + /// ("current") or not ("all"). If 'current' is given, then order is assumed to be + /// 'current' and filter is 'applied', regardless of what they might be given as. + page?: string; + } + + export interface Options + { + aaData?: any[]; + aaSorting?: any[]; + aaSortingFixed?: any[]; + ajax?: any; + aLengthMenu?: any[]; + aoColumns?: ColumnOptions[]; + aoColumnDefs?: ColumnDef[]; + aoSearchCols?: any[]; + asStripClasses?: string[]; + bAutoWidth?: boolean; + bDeferRender?: boolean; + bDestroy?: boolean; + bFilter?: boolean; + bInfo?: boolean; + bJQueryUI?: boolean; + bLengthChange?: boolean; + bPaginate?: boolean; + bProcessing?: boolean; + bRetrieve?: boolean; + bScrollAutoCss?: boolean; + bScrollCollapse?: boolean; + bScrollInfinite?: boolean; + bServerSide?: boolean; + bSort?: boolean; + bSortCellsTop?: boolean; + bSortClasses?: boolean; + bStateSave?: boolean; + fnCookieCallback?: CookieCallback; + fnCreatedRow?: RowCreatedCallback; + fnDrawCallback?: DrawCallback; + fnFooterCallback?: FooterCallback; + fnFormatNumber?: FormatNumber; + fnHeaderCallback?: HeaderCallback; + fnInfoCallback?: InfoCallback; + fnInitComplete?: InitComplete; + fnPreDrawCallback?: PreDrawCallback; + fnRowCallback?: RowCallback; + + fnStateLoadCallback?: StateLoadCallback; + fnStateLoadParams?: StateLoadParams; + fnStateLoaded?: StateLoaded; + fnStateSaveCallback?: StateSaveCallback; + fnStateSaveParams?: StateSaveParams; + iCookieDuration?: number; + iDeferLoading?: any; + iDisplayLength?: number; + iDisplayStart?: number; + iScrollLoadGap?: number; + iTabIndex?: number; + oLanguage?: LanguageOptions; + oSearch?: any; + sAjaxDataProp?: string; + sAjaxSource?: string; + sCookiePrefix?: string; + sDom?: string; + sPaginationType?: string; + sScrollX?: string; + sScrollXInner?: string; + sScrollY?: string; + sServerMethod? : string; + } + + export interface LanguageOptions + { + oAria? : AriaOptions; + oPaginate? : PaginateOptions; + sEmptyTable?: string; + sInfo?: string; + sInfoEmpty?: string; + sInfoFiltered?: string; + sInfoPostFix?: string; + sInfoThousands?: string; + sLengthMenu?: string; + sLoadingRecords?: string; + sProcessing?: string; + sSearch?: string; + sUrl?: string; + sZeroRecords?: string; + } + + export interface AriaOptions + { + sSortAscending?: string; + sSortDescending?: string; + } + + export interface PaginateOptions + { + sFirst?: string; + sLast?: string; + sNext?: string; + sPrevious?: string; + } + + export interface ColumnOptions + { + aDataSort?: number[]; + asSorting?: string[]; + bSearchable? : boolean; + bSortable? : boolean; + bVisible? : boolean; + _bAutoType? : boolean; + fnCreatedCell?: CreatedCell; + iDataSort?: number; + mData?: any; + mRender?: any; + sCellType?: string; + sClass?: string; + sContentPadding?: string; + sDefaultContent?: string; + sName?: string; + sSortDataType?: string; + sSortingClass?: string; + sTitle?: string; + sType?: string; + sWidth?: string; + } + + export interface ColumnDef extends ColumnOptions + { + aTargets: any[]; + } + + export interface Settings + { + oFeatures : Features; + oScroll: ScrollingSettings; + oLanguage : { fnInfoCallback : InfoCallback; }; + oBrowser : { bScrollOversize : boolean; }; + aanFeatures: Node[][]; + aoData: Row[]; + aiDisplay: number[]; + aiDisplayMaster: number[]; + aoColumns: Column[]; + aoHeader: any[]; + aoFooter: any[]; + asDataSearch: string[]; + oPreviousSearch: any; + aoPreSearchCols: any[]; + aaSorting: any[][]; + aaSortingFixed: any[][]; + asStripeClasses: string[]; + asDestroyStripes: string[]; + sDestroyWidth: number; + aoRowCallback: RowCallback[]; + aoHeaderCallback: HeaderCallback[]; + aoFooterCallback: FooterCallback[]; + aoDrawCallback: DrawCallback[]; + aoRowCreatedCallback: RowCreatedCallback[]; + aoPreDrawCallback: PreDrawCallback[]; + aoInitComplete: InitComplete[]; + aoStateSaveParams: StateSaveParams[]; + aoStateLoadParams: StateLoadParams[]; + aoStateLoaded: StateLoaded[]; + sTableId: string; + nTable: Node; + nTHead: Node; + nTFoot: Node; + nTBody: Node; + nTableWrapper: Node; + bDeferLoading: boolean; + bInitialized: boolean; + aoOpenRows: any[]; + sDom: string; + sPaginationType: string; + iCookieDuration: number; + sCookiePrefix: string; + fnCookieCallback: CookieCallback; + aoStateSave: StateSaveCallback[]; + aoStateLoad: StateLoadCallback[]; + oLoadedState: any; + sAjaxSource: string; + sAjaxDataProp: string; + bAjaxDataGet: boolean; + jqXHR: any; + fnServerData: any; + aoServerParams: any[]; + sServerMethod: string; + fnFormatNumber: FormatNumber; + aLengthMenu: any[]; + iDraw: number; + bDrawing: boolean; + iDrawError: number; + _iDisplayLength: number; + _iDisplayStart: number; + _iDisplayEnd: number; + _iRecordsTotal: number; + _iRecordsDisplay: number; + bJUI: boolean; + oClasses: any; + bFiltered: boolean; + bSorted: boolean; + bSortCellsTop: boolean; + oInit: any; + aoDestroyCallback: any[]; + fnRecordsTotal: () => number; + fnRecordsDisplay: () => number; + fnDisplayEnd: () => number; + oInstance : any; + sInstance: string; + iTabIndex: number; + nScrollHead: Node; + nScrollFoot: Node; + } + + export interface Features + { + bAutoWidth: boolean; + bDeferRender: boolean; + bFilter: boolean; + bInfo: boolean; + bLengthChange: boolean; + bPaginate: boolean; + bProcessing: boolean; + bServerSide: boolean; + bSort: boolean; + bSortClasses: boolean; + bStateSave: boolean; + } + + export interface ScrollingSettings + { + bAutoCss : boolean; + bCollapse: boolean; + bInfinite: boolean; + iBarWidth: number; + iLoadGap: number; + sX: string; + sY: string; + } + + export interface Row + { + nTr: Node; + _aData: any; + _aSortData: any[]; + _anHidden: Node[]; + _sRowStripe: string; + } + + export interface Column + { + aDataSort: any; + asSorting: string[]; + bSearchable : boolean; + bSortable : boolean; + bVisible : boolean; + _bAutoType : boolean; + fnCreatedCell: CreatedCell; + fnGetData: (data: any, specific: string) => any; + fnSetData: (data: any, value: any) => void; + mData: any; + mRender: any; + nTh: Node; + nIf: Node; + sClass: string; + sContentPadding: string; + sDefaultContent: string; + sName: string; + sSortDataType: string; + sSortingClass: string; + sSortingClassJUI: string; + sTitle: string; + sType: string; + sWidth: string; + sWidthOrig: string; + } + + export interface CookieCallback + { + (name: string, data: any, expires: string, path: string, cookie: string) : void; + } + + export interface RowCreatedCallback + { + (row: Node, data: any[], dataIndex: number) : void; + } + + export interface DrawCallback + { + (settings: Settings) : void; + } + + export interface FooterCallback + { + (foot: Element, data: any[], start:number, end:number, display: number[]) : void; + } + + export interface FormatNumber + { + (toFormat: number) : string; + } + + export interface HeaderCallback + { + (head: Element, data: any[], start:number, end:number, display: number[]) : void; + } + + export interface InfoCallback + { + (settings: Settings, start: number, end: number, max:number, total: number, pre: string) : string; + } + + export interface InitComplete + { + (settings: Settings, json: any) : void; + } + + export interface PreDrawCallback + { + (settings: Settings) : boolean; + } + + export interface RowCallback + { + (row : Settings, data: any[], displayIndex: number, displayIndexFull: number) : void; + } + + export interface StateLoadCallback + { + (settings: Settings) : any; + } + + export interface StateLoadParams + { + (settings: Settings, data: any) : void; + } + + export interface StateLoaded + { + (settings: Settings, data: any) : void; + } + + export interface StateSaveCallback + { + (settings: any, data:any) : void; + } + + export interface StateSaveParams + { + (settings: any, data:any) : void; + } + + export interface CreatedCell + { + (nTd: Node, cellData: any, rowData: any, row: number, col: number) : void; + } +} diff --git a/jquery.dataTables/jquery.dataTables-tests.ts b/jquery.dataTables/jquery.dataTables-tests.ts index d3fe178c3..c90b40d09 100755 --- a/jquery.dataTables/jquery.dataTables-tests.ts +++ b/jquery.dataTables/jquery.dataTables-tests.ts @@ -1,1445 +1,890 @@ -/// -/// - -// http://www.datatables.net/api - -// $ - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Highlight every second row - oTable.$('tr:odd').css('backgroundColor', 'blue'); -} ); - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Filter to rows with 'Webkit' in them, add a background colour and then - // remove the filter, thus highlighting the 'Webkit' rows only. - oTable.fnFilter('Webkit'); - oTable.$('tr', {"filter": "applied"}).css('backgroundColor', 'blue'); - oTable.fnFilter(''); -} ); - -// _ - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Get the data from the first row in the table - var data = oTable._('tr:first'); - - // Do something useful with the data - alert( "First cell is: "+data[0] ); -} ); - - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Filter to 'Webkit' and get all data for - oTable.fnFilter('Webkit'); - var data = oTable._('tr', {"filter": "applied"}); - - // Do something with the data - alert( data.length+" rows matched the filter" ); -} ); - -// fnAddData - -var giCount = 2; - -$(document).ready(function() { - $('#example').dataTable(); -} ); - -function fnClickAddRow() { - $('#example').dataTable().fnAddData( [ - giCount+".1", - giCount+".2", - giCount+".3", - giCount+".4" ] - ); - - giCount++; -} - -// fnAdjustColumnSizing - -$(document).ready(function() { - var oTable = $('#example').dataTable( { - "sScrollY": "200px", - "bPaginate": false - } ); - - $(window).bind('resize', function () { - oTable.fnAdjustColumnSizing(); - } ); -} ); - -// fnClearTable - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...) - oTable.fnClearTable(); -} ); - -// fnClose - -$(document).ready(function() { - var oTable; - - // 'open' an information row when a row is clicked on - $('#example tbody tr').click( function () { - if ( oTable.fnIsOpen(this) ) { - oTable.fnClose( this ); - } else { - oTable.fnOpen( this, "Temporary row opened", "info_row" ); - } - } ); - - oTable = $('#example').dataTable(); -} ); - -// fnDeleteRow - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Immediately remove the first row - oTable.fnDeleteRow( 0 ); -} ); - -// fnDestroy - -$(document).ready(function() { - // This example is fairly pointless in reality, but shows how fnDestroy can be used - var oTable = $('#example').dataTable(); - oTable.fnDestroy(); -} ); - -// fnDraw - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Re-draw the table - you wouldn't want to do it here, but it's an example :-) - oTable.fnDraw(); -} ); - -// fnFilter - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Sometime later - filter... - oTable.fnFilter( 'test string' ); -} ); - -// fnGetData - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - oTable.$('tr').click( function () { - var data = oTable.fnGetData( this ); - // ... do something with the array / object of data for the row - } ); -} ); - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - oTable.$('td').click( function () { - var sData = oTable.fnGetData( this ); - alert( 'The cell clicked on had the value of '+sData ); - } ); -} ); - -// fnGetNodes - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Get the nodes from the table - var nNodes = oTable.fnGetNodes( ); -} ); - -// fnGetPosition - -$(document).ready(function() { - $('#example tbody td').click( function () { - // Get the position of the current data from the node - var aPos = oTable.fnGetPosition( this ); - - // Get the data array for this row - var aData = oTable.fnGetData( aPos[0] ); - - // Update the data array and return the value - aData[ aPos[1] ] = 'clicked'; - this.innerHTML = 'clicked'; - } ); - - // Init DataTables - var oTable = $('#example').dataTable(); -} ); - -// fnIsOpen - -$(document).ready(function() { - var oTable; - - // 'open' an information row when a row is clicked on - $('#example tbody tr').click( function () { - if ( oTable.fnIsOpen(this) ) { - oTable.fnClose( this ); - } else { - oTable.fnOpen( this, "Temporary row opened", "info_row" ); - } - } ); - - oTable = $('#example').dataTable(); -} ); - -// fnOpen - -$(document).ready(function() { - var oTable; - - // 'open' an information row when a row is clicked on - $('#example tbody tr').click( function () { - if ( oTable.fnIsOpen(this) ) { - oTable.fnClose( this ); - } else { - oTable.fnOpen( this, "Temporary row opened", "info_row" ); - } - } ); - - oTable = $('#example').dataTable(); -} ); - -// fnPageChange - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - oTable.fnPageChange( 'next' ); -} ); - -// fnSetColumnVis - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Hide the second column after initialisation - oTable.fnSetColumnVis( 1, false ); -} ); - -// fnSettings - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - var oSettings = oTable.fnSettings(); - - // Show an example parameter from the settings - alert("" + oSettings._iDisplayStart); -} ); - -// fnSort - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Sort immediately with columns 0 and 1 - oTable.fnSort( [ [0,'asc'], [1,'asc'] ] ); -} ); - -// fnSortListener - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Sort on column 1, when 'sorter' is clicked on - oTable.fnSortListener( document.getElementById('sorter'), 1 ); -} ); - -// fnUpdate - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell - oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], 1 ); // Row -} ); - -// fnVersionCheck - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - oTable.fnVersionCheck( '1.9.0'); -} ); - -// http://datatables.net/usage/features - -$(document).ready( function () { - $('#example').dataTable( { - "bAutoWidth": false - } ); -} ); - -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/arrays.txt", - "bDeferRender": true - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bFilter": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bInfo": false - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bJQueryUI": true - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bLengthChange": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bPaginate": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bProcessing": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bScrollInfinite": true, - "bScrollCollapse": true, - "sScrollY": "200px" - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "xhr.php" - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bSort": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bSortClasses": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bStateSave": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollX": "100%", - "bScrollCollapse": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollY": "200px", - "bPaginate": false - } ); -} ); - -// http://datatables.net/usage/options - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollY": "200px", - "bPaginate": false - } ); - - // Some time later.... - $('#example').dataTable( { - "bFilter": false, - "bDestroy": true - } ); -} ); - -$(document).ready( function() { - initTable(); - tableActions(); -} ); - -function initTable () -{ - return $('#example').dataTable( { - "sScrollY": "200px", - "bPaginate": false, - "bRetrieve": true - } ); -} - -function tableActions () -{ - var oTable = initTable(); - // perform API operations with oTable -} - -$(document).ready( function() { - $('#example').dataTable( { - "bScrollAutoCss": false, - "sScrollY": "200px" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollY": "200", - "bScrollCollapse": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bSortCellsTop": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "iCookieDuration": 60*60*24 // 1 day - } ); -} ); - -// 57 records available in the table, no filtering applied -$(document).ready( function() { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "scripts/server_processing.php", - "iDeferLoading": 57 - } ); -} ); - - -// 57 records after filtering, 100 without filtering (an initial filter applied) -$(document).ready( function() { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "scripts/server_processing.php", - "iDeferLoading": [ 57, 100 ], - "oSearch": { - "sSearch": "my_filter" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "iDisplayLength": 50 - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "iDisplayStart": 20 - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "bScrollInfinite": true, - "bScrollCollapse": true, - "sScrollY": "200px", - "iScrollLoadGap": 50 - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "iTabIndex": 1 - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oSearch": {"sSearch": "Initial search"} - } ); -} ) - -// Get data from { "data": [...] } -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/data.txt", - "sAjaxDataProp": "data" - } ); -} ); - - -// Get data from { "data": { "inner": [...] } } -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/data.txt", - "sAjaxDataProp": "data.inner" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php" - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "sCookiePrefix": "my_datatable_" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sDom": '<"top"i>rt<"bottom"flp><"clear">' - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sPaginationType": "full_numbers" - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollX": "100%", - "sScrollXInner": "110%" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "scripts/post.php", - "sServerMethod": "POST" - } ); -} ); - -// http://datatables.net/usage/callbacks - -$(document).ready( function () { - $('#example').dataTable( { - "fnCookieCallback": function (sName, oData, sExpires, sPath) { - // Customise oData or sName or whatever else here - return sName + "="+JSON.stringify(oData)+"; expires=" + sExpires +"; path=" + sPath; - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnCreatedRow": function( nRow, aData, iDataIndex ) { - // Bold the grade for all 'A' grade browsers - if ( aData[4] == "A" ) - { - $('td:eq(4)', nRow).html( 'A' ); - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnDrawCallback": function( oSettings ) { - alert( 'DataTables has redrawn the table' ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnFooterCallback": function( nFoot, aData, iStart, iEnd, aiDisplay ) { - ( (nFoot.getElementsByTagName('th')[0])).innerHTML = "Starting index is "+iStart; - } - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "fnFormatNumber": function ( iIn ) { - if ( iIn < 1000 ) { - return iIn.toString(); - } else { - var - s=(iIn+""), - a=s.split(""), out="", - iLen=s.length; - - for ( var i=0 ; i nHead.getElementsByTagName('th')[0]).innerHTML = "Displaying "+(iEnd-iStart)+" records"; - } - } ); -} ) - -$('#example').dataTable( { - "fnInfoCallback": function( oSettings, iStart, iEnd, iMax, iTotal, sPre ) { - return iStart +" to "+ iEnd; - } -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnInitComplete": function(oSettings, json) { - alert( 'DataTables has finished its initialisation.' ); - } - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "fnPreDrawCallback": function( oSettings ) { - if ( $('#test').val() == 1 ) { - return false; - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { - // Bold the grade for all 'A' grade browsers - if ( aData[4] == "A" ) - { - $('td:eq(4)', nRow).html( 'A' ); - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bProcessing": true, - "bServerSide": true, - "sAjaxSource": "xhr.php", - "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { - oSettings.jqXHR = $.ajax( { - "dataType": 'json', - "type": "POST", - "url": sSource, - "data": aoData, - "success": fnCallback - } ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bProcessing": true, - "bServerSide": true, - "sAjaxSource": "scripts/server_processing.php", - "fnServerParams": function ( aoData ) { - aoData.push( { "name": "more_data", "value": "my_value" } ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateLoad": function (oSettings) { - var o; - - // Send an Ajax request to the server to get the data. Note that - // this is a synchronous request. - $.ajax( { - "url": "/state_load", - "async": false, - "dataType": "json", - "success": function (json) { - o = json; - } - } ); - - return o; - } - } ); -} ); - -// Remove a saved filter, so filtering is never loaded -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateLoadParams": function (oSettings, oData) { - oData.oSearch.sSearch = ""; - } - } ); -} ); - - -// Disallow state loading by returning false -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateLoadParams": function (oSettings, oData) { - return false; - } - } ); -} ); - -// Show an alert with the filtering value that was saved -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateLoaded": function (oSettings, oData) { - alert( 'Saved filter was: '+oData.oSearch.sSearch ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateSave": function (oSettings, oData) { - // Send an Ajax request to the server with the state object - $.ajax( { - "url": "/state_save", - "data": oData, - "dataType": "json", - "method": "POST", - "success": function () {} - } ); - } - } ); -} ); - -// Remove a saved filter, so filtering is never saved -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateSaveParams": function (oSettings, oData) { - oData.oSearch.sSearch = ""; - } - } ); -} ); - -// http://datatables.net/usage/columns - -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] }, - { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] }, - { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] } - ] - } ); -} ); - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "aDataSort": [ 0, 1 ] }, - { "aDataSort": [ 1, 0 ] }, - { "aDataSort": [ 2, 3, 4 ] }, - null, - null - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "asSorting": [ "asc" ], "aTargets": [ 1 ] }, - { "asSorting": [ "desc", "asc", "asc" ], "aTargets": [ 2 ] }, - { "asSorting": [ "desc" ], "aTargets": [ 3 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - null, - { "asSorting": [ "asc" ] }, - { "asSorting": [ "desc", "asc", "asc" ] }, - { "asSorting": [ "desc" ] }, - null - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "bSearchable": false, "aTargets": [ 0 ] } - ] } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "bSearchable": false }, - null, - null, - null, - null - ] } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "bSortable": false, "aTargets": [ 0 ] } - ] } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "bSortable": false }, - null, - null, - null, - null - ] } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "bVisible": false, "aTargets": [ 0 ] } - ] } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "bVisible": false }, - null, - null, - null, - null - ] } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ { - "aTargets": [3], - "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) { - if ( sData == "1.7" ) { - $(nTd).css('color', 'blue') - } - } - } ] - }); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "iDataSort": 1, "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "iDataSort": 1 }, - null, - null, - null, - null - ] - } ); -} ); - -// Read table data from objects -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/deep.txt", - "aoColumns": [ - { "mData": "engine" }, - { "mData": "browser" }, - { "mData": "platform.inner" }, - { "mData": "platform.details.0" }, - { "mData": "platform.details.1" } - ] - } ); -} ); - - -// Using mData as a function to provide different information for -// sorting, filtering and display. In this case, currency (price) -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "aoColumnDefs": [ { - "aTargets": [ 0 ], - "mData": function ( source, type, val ) { - if (type === 'set') { - source.price = val; - // Store the computed dislay and filter values for efficiency - source.price_display = val=="" ? "" : "$"+val; - source.price_filter = val=="" ? "" : "$"+val+" "+val; - return; - } - else if (type === 'display') { - return source.price_display; - } - else if (type === 'filter') { - return source.price_filter; - } - // 'sort', 'type' and undefined all just use the integer - return source.price; - } - } ] - } ); -} ); - -// Create a comma separated list from an array of objects -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/deep.txt", - "aoColumns": [ - { "mData": "engine" }, - { "mData": "browser" }, - { - "mData": "platform", - "mRender": "[, ].name" - } - ] - } ); -} ); - - -// Use as a function to create a link from the data source -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "aoColumnDefs": [ { - "aTargets": [ 0 ], - "mData": "download_link", - "mRender": function ( data, type, full ) { - return 'Download'; - } - } ] - } ); -} ); - -// Make the first column use TH cells -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "aoColumnDefs": [ { - "aTargets": [ 0 ], - "sCellType": "th" - } ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sClass": "my_class", "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sClass": "my_class" }, - null, - null, - null, - null - ] - } ); -} ); - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - null, - null, - null, - { - "sContentPadding": "mmm" - } - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { - "mData": null, - "sDefaultContent": "Edit", - "aTargets": [ -1 ] - } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - null, - null, - null, - { - "mData": null, - "sDefaultContent": "Edit" - } - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sName": "engine", "aTargets": [ 0 ] }, - { "sName": "browser", "aTargets": [ 1 ] }, - { "sName": "platform", "aTargets": [ 2 ] }, - { "sName": "version", "aTargets": [ 3 ] }, - { "sName": "grade", "aTargets": [ 4 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sName": "engine" }, - { "sName": "browser" }, - { "sName": "platform" }, - { "sName": "version" }, - { "sName": "grade" } - ] - } ); -} ); - -/* - -This test does not compile, because - for some hard to find reason - the compiler is missing the aTargets -property of the second element. - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sSortDataType": "dom-text", "aTargets": [ 2, 3 ] }, - { "sType": "numeric", "aTargets": [ 3 ] }, - { "sSortDataType": "dom-select", "aTargets": [ 4 ] }, - { "sSortDataType": "dom-checkbox", "aTargets": [ 5 ] } - ] - } ); -} ); - -*/ - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - null, - null, - { "sSortDataType": "dom-text" }, - { "sSortDataType": "dom-text", "sType": "numeric" }, - { "sSortDataType": "dom-select" }, - { "sSortDataType": "dom-checkbox" } - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sTitle": "My column title", "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sTitle": "My column title" }, - null, - null, - null, - null - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sType": "html", "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sType": "html" }, - null, - null, - null, - null - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sWidth": "20%", "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sWidth": "20%" }, - null, - null, - null, - null - ] - } ); -} ); - -// http://www.datatables.net/usage/i18n - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oAria": { - "sSortAscending": " - click/return to sort ascending" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oAria": { - "sSortDescending": " - click/return to sort descending" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oPaginate": { - "sFirst": "First page" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oPaginate": { - "sLast": "Last page" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oPaginate": { - "sNext": "Next page" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oPaginate": { - "sPrevious": "Previous page" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sEmptyTable": "No data available in table" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfo": "Got a total of _TOTAL_ entries to show (_START_ to _END_)" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfoEmpty": "No entries to show" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfoFiltered": " - filtering from _MAX_ records" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfoPostFix": "All records shown are derived from real information." - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfoThousands": "'" - } - } ); -} ); - -// Language change only -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sLengthMenu": "Display _MENU_ records" - } - } ); -} ); - - -// Language and options change -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sLengthMenu": 'Display records' - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sLoadingRecords": "Please wait - loading..." - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sProcessing": "DataTables is currently busy" - } - } ); -} ); - -// Input text box will be appended at the end automatically -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sSearch": "Filter records:" - } - } ); -} ); - - -// Specify where the filter should appear -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sSearch": "Apply filter _INPUT_ to table" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sUrl": "http://www.sprymedia.co.uk/dataTables/lang.txt" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sZeroRecords": "No records to display" - } - } ); -} ); - -// http://www.datatables.net/usage/server-side - -$(document).ready( function () { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "xhr.php" - } ); -} ); - -// POST data to server -$(document).ready( function() { - $('#example').dataTable( { - "bProcessing": true, - "bServerSide": true, - "sAjaxSource": "xhr.php", - "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { - oSettings.jqXHR = $.ajax( { - "dataType": 'json', - "type": "POST", - "url": sSource, - "data": aoData, - "success": fnCallback - } ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bProcessing": true, - "bServerSide": true, - "sAjaxSource": "scripts/server_processing.php", - "fnServerParams": function ( aoData ) { - aoData.push( { "name": "more_data", "value": "my_value" } ); - } - } ); -} ); - -// Get data from { "data": [...] } -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/data.txt", - "sAjaxDataProp": "data" - } ); -} ); - - -// Get data from { "data": { "inner": [...] } } -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/data.txt", - "sAjaxDataProp": "data.inner" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php" - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "scripts/post.php", - "sServerMethod": "POST" - } ); -} ); +/// +/// + +$(document).ready(function () { + //#region "Language" + + var lang: DataTables.LanguageSettings = { + "emptyTable": "No data available in table", + "info": "Showing _START_ to _END_ of _TOTAL_ entries", + "infoEmpty": "Showing 0 to 0 of 0 entries", + "infoFiltered": "(filtered from _MAX_ total entries)", + "infoPostFix": "", + "thousands": ",", + "lengthMenu": "Show _MENU_ entries", + "loadingRecords": "Loading...", + "processing": "Processing...", + "search": "Search:", + "zeroRecords": "No matching records found", + "paginate": { + "first": "First", + "last": "Last", + "next": "Next", + "previous": "Previous" + }, + "aria": { + "sortAscending": ": activate to sort column ascending", + "sortDescending": ": activate to sort column descending" + } + }; + + //#endregion "Language" + + //#region "Column" + + var colCreatedCellFunc: DataTables.FunctionColumnCreatedCell = function (cell, cellData, rowData, rowIndex, colIndex) { + + } + + var colDataObject: DataTables.ObjectColumnData = { + _: "phone", + filter: "phone_filter", + display: "phone_display", + sort: "asc" + }; + + var colDataFunc: DataTables.FunctionColumnData = function (row, type, set, meta) { + }; + + var colRenderObject: DataTables.ObjectColumnRender = { + _: "phone", + filter: "phone_filter", + display: "phone_display", + sort: "asc" + }; + + var colRenderFunc: DataTables.FunctionColumnRender = function (data, type, row, meta) { + + }; + + var col: DataTables.ColumnSettings = + { + cellType: "th", + className: "css", + contentPadding: "mmmm", + createdCell: colCreatedCellFunc, + data: 1, + defaultContent: "edit", + name: "name", + orderable: true, + orderData: 10, + orderDataType: "dom-checkbox", + orderSequence: ['asc', 'desc'], + render: 1, + searchable: true, + title: "title", + visible: true, + width: "200px" + } + col = + { + data: "", + orderData: [10, 11, 20], + render: "", + } + col = + { + data: colDataObject, + render: colRenderObject, + } + col = + { + data: colDataFunc, + render: colRenderFunc, + } + + //#endregion "Column" + + //#region "ColumnDef" + + var colDef: DataTables.ColumnDefsSettings = + { + targets: 1, + cellType: "th", + className: "css", + contentPadding: "mmmm", + createdCell: colCreatedCellFunc, + data: 1, + defaultContent: "edit", + name: "name", + orderable: true, + orderData: 10, + orderDataType: "dom-checkbox", + orderSequence: ['asc', 'desc'], + render: 1, + searchable: true, + title: "title", + visible: true, + width: "200px" + }; + + colDef = + { + targets: "2", + cellType: "th", + }; + + colDef = + { + targets: ["2", 5], + cellType: "th", + }; + + //#endregion "ColumnDef" + + //#region "Callbacks" + + var createRowFunc: DataTables.FunctionCreateRow = function (row, data, dataIndex) { }; + var drawCallbackFunc: DataTables.FunctionDrawCallback = function (settings) { }; + var footerCallbackFunc: DataTables.FunctionFooterCallback = function (tfoot, data, start, end, display) { }; + var formatNumberFunc: DataTables.FunctionFormatNumber = function (toForm) { }; + var headerCallbackFunc: DataTables.FunctionHeaderCallback = function (thead, data, start, end, display) { }; + var infoCallbackFunc: DataTables.FunctionInfoCallback = function (settings, start, end, total, pre) { }; + var initCallbackFunc: DataTables.FunctionInitComplete = function (settings, json) { }; + var preDrawFunc: DataTables.FunctionPreDrawCallback = function (settings) { }; + var rowCallbackFunc: DataTables.FunctionRowCallback = function (row, data) { }; + var stateLoadCallbackFunc: DataTables.FunctionStateLoadCallback = function (settings) { }; + var stateLoadedCallbackFunc: DataTables.FunctionStateLoaded = function (settings, data) { }; + var stateSaveCallbackFunc: DataTables.FunctionStateSaveCallback = function (settings, data) { }; + var stateSaveParamsFunc: DataTables.FunctionStateSaveParams = function (settings, data) { }; + + //#endregion "Callbacks + + //#region "Ajax" + + var ajaxFunc: DataTables.FunctionAjax = function (data, callback, settings) { }; + + var ajaxDataFunc: DataTables.FunctionAjaxData = function (data) { + return data; + }; + + ajaxDataFunc = function (data) { + return ""; + }; + + //#endregion "Ajax" + + //#region "Settings" + + var config: DataTables.Settings = + { + // columns + columns: [ + col, + null, + col, + null, + col, + col + ], + columnDefs: [ + null, + colDef, + colDef, + null, + ], + // Data + ajax: "url", + data: {}, + // Features + autoWidth: true, + deferRender: true, + info: true, + jQueryUI: false, + lengthChange: true, + ordering: true, + paging: true, + scrollX: true, + scrollY: "200px", + searching: true, + serverSide: true, + stateSave: true, + // Options + deferLoading: 10, + destroy: true, + displayStart: 1, + dom: "lrtip", + lengthMenu: [1, 2, 3, 4], + orderCellsTop: true, + orderClasses: true, + order: [[0, 'asc'], [1, 'asc']], + orderFixed: [[0, 'asc'], [1, 'asc']], + orderMulti: true, + pageLength: 10, + pagingType: "simple", + retrieve: true, + renderer: "bootstrap", + scrollCollapse: true, + search: true, + searchCols: [{ "search": "", "smart": true, "regex": false, "caseInsensitive": true }], + searchDelay: 10, + stateDuration: 10, + tabIndex: 10, + }; + + + config = + { + ajax: ajaxFunc, + deferLoading: [10, 100], + lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], + order: [0, 'asc'], + orderFixed: [[0, 'asc'], [1, 'asc']], + renderer: { + header: "bootstrap", + pageButton: "jqueryui" + }, + search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + searchCols: [ + null, + { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + { "search": "" }, + { "search": "", "smart": true }, + null + ], + }; + + config = + { + ajax: { + data: {}, + dataSrc: "", + }, + }; + + config = + { + ajax: { + data: ajaxDataFunc, + dataSrc: function (data) { }, + }, + }; + + //#endregion "Settings" + + //#region "Init" + + var dt = $('#example').DataTable(); + dt = $('#example1').DataTable(config); + dt = $('#example1').DataTable(config); + dt.$('tr:odd').css('backgroundColor', 'blue'); + + //#endregion "Init" + + //#region "Methods-Ajax" + + var json = dt.ajax.json(); + + var params = dt.ajax.params(); + + var reload = dt.ajax.reload(); + reload = dt.ajax.reload(function () { }); + reload = dt.ajax.reload(function () { }, true); + var test = reload.$(""); + + var url = dt.ajax.url(); + dt.ajax.url("url"); + dt.ajax.url("url").load(); + + //#endregion "Methods-Ajax" + + //#region "Methods-Core" + + var clear = dt.clear(); + clear.$(""); + + var data = dt.data(); + data.$(""); + + var destroy = dt.destroy(); + destroy = dt.destroy(true); + destroy.$(""); + + var draw = dt.draw(); + draw = dt.draw(true); + draw.$(""); + + var off = dt.off("event"); + off = dt.off("event", function () { }); + off.$(""); + + var on = dt.on("event", function () { }); + on.$(""); + + var one = dt.one("event", function () { }); + one.$(""); + + var order_get = dt.order(); + var order_set = dt.order([0, "asc"]); + order_set = dt.order([0, "asc"], [1, "desc"]); // TODO: Fíx that + order_set = dt.order([[0, "asc"], [1, "desc"]]); + + var orderListerner = order_set.order.listener("node", 1, function () { }); + + var page_get = dt.page(); + var page_set = dt.page(1); + page_set = dt.page("next"); + + var page = dt.page.info(); + page = { + "page": 1, + "pages": 6, + "start": 10, + "end": 20, + "length": 10, + "recordsTotal": 57, + "recordsDisplay": 57 + }; + + var page_len_get = dt.page.len(); + var page_len_set = dt.page.len(10); + + var search_get = dt.search(); + var search_set = dt.search("searchStr"); + search_set = dt.search("searchStr", true); + search_set = dt.search("searchStr", true, false); + search_set = dt.search("searchStr", true, false, false); + + var settings = dt.settings(); + + var state = dt.state(); + state = { "time": 1423772610230, "start": 0, "length": 25, "order": [[0, "asc"]], "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, "columns": [{ "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }] }; + state = dt.state.loaded(); + + var state_clear = dt.state.clear(); + state_clear.$(""); + + var state_save = dt.state.save(); + state_save.$(""); + + //#endregion "Methods-Core" + + var modifier: DataTables.ObjectSelectorModifier = { + order: "current", + search: "none", + page: "all", + }; + + //#region "Methods-Cell" + + var cells = dt.cells(); + cells = dt.cells(":contains('Not shipped')"); + cells = dt.cells(function () { }); + cells = dt.cells($("")); + cells = dt.cells({}); + cells = dt.cells(":contains('Not shipped')r", modifier); + cells = dt.cells("row-selector", "cells-selector", modifier); + + var cells_cache = cells.cache("search"); + // Create the select list and search operation + var select = $('') + .appendTo( + dt.column(colIdx).footer() + ) + .on('change', function () { + dt + .column(colIdx) + .search($(this).val()) + .draw(); + }); + + // Get the search data for the first column and add to the select list + dt + .column(colIdx) + .cache('search') + .sort() + .unique() + .each(function (d) { + select.append($('')); + }); + }); + + var columns_data = columns.data(); + $('#listData').html( + dt + .columns(0) + .data() + .eq(0) // Reduce the 2D array into a 1D array of data + .sort() // Sort data alphabetically + .unique() // Reduce to unique values + .join('
') + ); + + //var idx = dt + // .columns('.check') + // .data() + // .eq(0) // Reduce the 2D array into a 1D array of data + // .indexOf('Yes'); + + var columns_dataSrc = columns.dataSrc(); + //alert('Data source: ' + dt.columns([0, 1]).dataSrc().join(' ')); + + var columns_footer = columns.footer(); + var columns_header = columns.header(); + var columns_indexes = columns.indexes(); + columns_indexes = columns.indexes("visibile"); + var columns_nodes = columns.nodes(); + dt + .columns('.ready') + .nodes() + //.flatten() // Reduce to a 1D array + //.to$() // Convert to a jQuery object + //.addClass('highlight'); + + var columns_search_get = columns.search(); + var columns_search_set = columns.search("string"); + columns_search_set = columns.search("string", true); + columns_search_set = columns.search("string", true, false); + columns_search_set = columns.search("string", true, false, true); + + var columns_visible_get = columns.visible(); + var columns_visible_set = columns.visible(false); + columns_visible_set = columns.visible(false, true); + // Hide a column + dt.column(1).visible(false); + dt.columns([0, 1, 2, 3]).visible(false, false); + dt.columns.adjust().draw(false); // adjust column sizing and redraw + + var columns_adjust = dt.columns.adjust(); + + var column = dt.column("selector"); + column = dt.column("selector", modifier); + + dt.column(0).visible(false); + + $('#example tbody').on('click', 'td', function () { + var visIdx = $(this).index(); + var dataIdx = dt.column.index('fromVisible', visIdx); + + alert('Column data index: ' + dataIdx + ', and visible index: ' + visIdx); + }); + + var column_cache = column.cache("order"); + // Create the select list and search operation + var select = $('') + .appendTo( + dt.column(colIdx).footer() + ) + .on('change', function () { + dt + .column(colIdx) + .search($(this).val()) + .draw(); + }); + + // Get the search data for the first column and add to the select list + dt + .column(colIdx) + .cache('search') + .sort() + .unique() + .each(function (d) { + select.append($('')); + }); + }); + + var column_visible_get = column.visible(); + var column_visible_set = column.visible(false); + column_visible_set = column.visible(false, true); + alert('Column index 0 is ' + + (dt.column(0).visible() === true ? 'visible' : 'not visible') + ); + for (var i = 0; i < 4; i++) { + dt.column(i).visible(false, false); + } + dt.columns.adjust().draw(false); // adjust column sizing and redraw + + //#endregion "Methods-Column" + + //#region "Methods-Row" + + var row_1 = dt.row("selector"); + var row_2 = dt.row("selector").child.hide(); + var row_3 = dt.row("selector").child.isShown(); + var row_4 = dt.row("selector").child.remove(); + var row_5 = dt.row("selector").child.show(); + var row_6 = dt.row("selector").child(); + var row_7 = dt.row("selector").child(false); + var row_8 = dt.row("selector").child(false).hide(); + var row_9 = dt.row("selector").child("data"); + var row_10 = dt.row("selector").child("data").remove(); + var row_11 = dt.row("selector").child("data", "css").show(); + var row_12 = dt.row("selector").child.remove(); + var row_13 = dt.row("selector").child.show(); + var row_14 = dt.row.add({}); + var row_15 = dt.row("selector").invalidate(); + var row_16 = dt.row("selector").invalidate("auto"); + var row_17 = dt.row("selector").data(); + var row_18 = dt.row("selector").data({}); + var row_19 = dt.row("selector").index(); + var row_20 = dt.row("selector").node(); + var row_21 = dt.row("selector").remove(); + + var rows_1 = dt.rows(); + var rows_2 = dt.rows().remove(); + var rows_3 = dt.rows("selector"); + var rows_4 = dt.rows("selector").cache("type"); + var rows_5 = dt.rows("selector").data(); + var rows_6 = dt.rows("selector").data({}); + var rows_7 = dt.rows("selector").indexes(); + var rows_8 = dt.rows("selector").invalidate(); + var rows_9 = dt.rows("selector").invalidate("auto"); + var rows_10 = dt.rows("selector").indexes(); + var rows_11 = dt.rows("selector").remove(); + var rows_12 = dt.rows("selector").nodes(); + var rows_13 = dt.rows.add([{}, {}]); + + var table3 = $('#example').DataTable(); + table3.row.add({ + "name": "Tiger Nixon", + "position": "System Architect", + "salary": "$3,120", + "start_date": "2011/04/25", + "office": "Edinburgh", + "extn": "5421" + }).draw(); + + var table4 = $('#example').DataTable(); + table4.row.add([{ + "name": "Tiger Nixon", + "position": "System Architect", + "salary": "$3,120", + "start_date": "2011/04/25", + "office": "Edinburgh", + "extn": "5421" + }, { + "name": "Garrett Winters", + "position": "Director", + "salary": "$5,300", + "start_date": "2011/07/25", + "office": "Edinburgh", + "extn": "8422" + }]) + .draw(); + + var pupil: any; + var table5 = $('#example').DataTable(); + table5.rows.add([ + pupil, + pupil, + pupil, + ]) + .draw(); + //.nodes() + //.to$() + //.addClass('new'); + + $('#example tbody').on('click', 'td.details-control', function () { + var tr = $(this).parents('tr'); + var row = dt.row(tr); + + if (row.child.isShown()) { + // This row is already open - close it + row.child.hide(); + tr.removeClass('shown'); + } + else { + // Open this row (the format() function would return the data to be shown) + row.child("").show(); + tr.addClass('shown'); + } + }); + + dt.row(':eq(0)').child([ + 'First child row', + 'Second child row', + 'Third child row' + ]) + .show(); + + dt.rows().eq(0).each(function (rowIdx) { + dt + .row(rowIdx) + .child( + $( + '' + + '' + rowIdx + '.1' + + '' + rowIdx + '.2' + + '' + rowIdx + '.3' + + '' + rowIdx + '.4' + + '' + ) + ) + .show(); + }); + + $('#example tbody').on('click', 'td.details-control', function () { + var tr = $(this).parents('tr'); + var row = dt.row(tr); + + if (row.child.isShown()) { + // This row is already open - close it + row.child.hide(); + tr.removeClass('shown'); + } + else { + // Open this row (the format() function would return the data to be shown) + row.child("").show(); + tr.addClass('shown'); + } + }); + + $('#example tbody').on('click', 'td.details-control', function () { + var tr = $(this).parents('tr'); + var row = dt.row(tr); + + if (row.child.isShown()) { + // This row is already open - remove it + row.child.remove(); + tr.removeClass('shown'); + } + else { + // Open this row (the format() function would return the data to be shown) + row.child("").show(); + tr.addClass('shown'); + } + }); + + //#endregion "Methods-Row" + + //#region "Methods-Table" + + var tables = dt.tables(); + tables = dt.tables("selector"); + + var tables_body = tables.body(); + var tables_containers = tables.containers(); + var tables_footer = tables.footer(); + var tables_header = tables.header(); + var tables_nodes = tables.nodes(); + + var table = dt.table("selector"); + + var table_body = table.body(); + var table_container = table.container(); + var table_footer = table.footer(); + var table_header = table.header(); + var table_node = table.node(); + + //#endregion "Methods-Table" + + //#region "Methods-Util" + + //#endregion "Methods-Util" +}); diff --git a/jquery.dataTables/jquery.dataTables.d.ts b/jquery.dataTables/jquery.dataTables.d.ts index 9884b78e2..cbcb1c025 100755 --- a/jquery.dataTables/jquery.dataTables.d.ts +++ b/jquery.dataTables/jquery.dataTables.d.ts @@ -1,479 +1,1828 @@ -// Type definitions for JQuery DataTables 1.9.4 -// Project: http://www.datatables.net -// Definitions by: Armin Sander -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// missing: -// - Static methods that are defined in JQueryStatic.fn are not typed. -// - Plugin and extension definitions are not typed. - -interface JQuery -{ - dataTable(param? :DataTables.Options) : DataTables.DataTable; -} - -declare module DataTables -{ - export interface DataTable - { - /// Perform a jQuery selector action on the table's TR elements (from the tbody) and return the resulting jQuery object. - $(selector:string, opts?:RowParams): JQuery; - $(selector:Node[], opts?:RowParams): JQuery; - $(selector:JQuery, opts?:RowParams): JQuery; - - /// Almost identical to $ in operation, but in this case returns the data for the matched rows. - _(selector:string, opts?:RowParams): any[]; - _(selector:Node[], opts?:RowParams): any[]; - _(selector:JQuery, opts?:RowParams): any[]; - - /// Add a single new row or multiple rows of data to the table. - fnAddData(data:any, redraw?:boolean) : number[]; - - /// This function will make DataTables recalculate the column sizes. - fnAdjustColumnSizing(redraw? : boolean) : void; - - /// Quickly and simply clear a table - fnClearTable(redraw? : boolean) : void; - - /// The exact opposite of 'opening' a row, this function will close any rows which are currently 'open'. - fnClose(node: Node) : number; - - /// Remove a row for the table - fnDeleteRow(index: number, callback?: () => void, redraw?: boolean) : any[]; - fnDeleteRow(tr: Node, callback?: () => void, redraw?: boolean) : any[]; - - /// Restore the table to it's original state in the DOM by removing all of DataTables enhancements, - /// alterations to the DOM structure of the table and event listeners. - fnDestroy(remove?: boolean) : void; - - /// Redraw the table - fnDraw(complete? : boolean) : void; - - /// Filter the input based on data - fnFilter(input: string, column? : number, regex?: boolean, smart? : boolean, showGlobal?: boolean, caseInsensitive? : boolean) : void; - - /// Get the data for the whole table, an individual row or an individual cell based on the provided parameters. - fnGetData(row?: Node, col? : number) : any; - fnGetData(row?: number, col? : number) : any; - - /// Get an array of the TR nodes that are used in the table's body. - fnGetNodes(row? : number) : any; // Node[] | Node - - /// Get the array indexes of a particular cell from it's DOM element and column index including hidden columns - fnGetPosition(node: Node) : any; // number | number[] - - /// Check to see if a row is 'open' or not. - fnIsOpen(tr: Node) : boolean; - - /// This function will place a new row directly after a row which is currently on display on the page, - /// with the HTML contents that is passed into the function. - fnOpen(node: Node, html: string, clazz: string) : Node; - fnOpen(node: Node, html: Node, clazz: string) : Node; - fnOpen(node: Node, html: JQuery, clazz: string) : Node; - - /// Change the pagination - provides the internal logic for pagination in a simple API function. - fnPageChange(action: string, redraw?: boolean) : void; - fnPageChange(page: number, redraw?: boolean) : void; - - /// Show a particular column - fnSetColumnVis(column: number, show: boolean, redraw?: boolean) : void; - - /// Get the settings for a particular table for external manipulation - fnSettings() : Settings; - - /// Sort the table by a particular column - fnSort(col: number) : void; - fnSort(col: any[][]) : void; - - /// Attach a sort listener to an element for a given column - fnSortListener(node: Node, column: number, callback? : () => void): void; - - /// Update a table cell or row - this method will accept either a single value to update the cell with, - /// an array of values with one element for each column or an object in the same format as the original data source. - fnUpdate(data: any, row: Node, column?:number, redraw?: boolean, action? : boolean) : number; - fnUpdate(data: any, dataIndex: number, column?:number, redraw?: boolean, action? : boolean) : number; - - /// Provide a common method for plug-ins to check the version of DataTables being used, - /// in order to ensure compatibility. - fnVersionCheck(version: string) : boolean; - } - - export interface Static - { - /// Provide a common method for plug-ins to check the version of DataTables being used, - /// in order to ensure compatibility. - fnVersionCheck(version: string) : boolean; - - /// Check if a TABLE node is a DataTable table already or not. - fnIsDataTable(table: Node) : boolean; - - /// Get all DataTable tables that have been initialised. - fnTables(visible? : boolean) : Node[]; - } - - export interface RowParams - { - /// Select TR elements that meet the current filter criterion ("applied") or all TR elements (i.e. no filter). - filter?: string; - - /// Order of the TR elements in the processed array. - /// Can be either 'current', whereby the current sorting of the table is used, or - /// 'original' whereby the original order the data was read into the table is used. - order?: string; - - /// Limit the selection to the currently displayed page - /// ("current") or not ("all"). If 'current' is given, then order is assumed to be - /// 'current' and filter is 'applied', regardless of what they might be given as. - page?: string; - } - - export interface Options - { - aaData?: any[]; - aaSorting?: any[]; - aaSortingFixed?: any[]; - ajax?: any; - aLengthMenu?: any[]; - aoColumns?: ColumnOptions[]; - aoColumnDefs?: ColumnDef[]; - aoSearchCols?: any[]; - asStripClasses?: string[]; - bAutoWidth?: boolean; - bDeferRender?: boolean; - bDestroy?: boolean; - bFilter?: boolean; - bInfo?: boolean; - bJQueryUI?: boolean; - bLengthChange?: boolean; - bPaginate?: boolean; - bProcessing?: boolean; - bRetrieve?: boolean; - bScrollAutoCss?: boolean; - bScrollCollapse?: boolean; - bScrollInfinite?: boolean; - bServerSide?: boolean; - bSort?: boolean; - bSortCellsTop?: boolean; - bSortClasses?: boolean; - bStateSave?: boolean; - fnCookieCallback?: CookieCallback; - fnCreatedRow?: RowCreatedCallback; - fnDrawCallback?: DrawCallback; - fnFooterCallback?: FooterCallback; - fnFormatNumber?: FormatNumber; - fnHeaderCallback?: HeaderCallback; - fnInfoCallback?: InfoCallback; - fnInitComplete?: InitComplete; - fnPreDrawCallback?: PreDrawCallback; - fnRowCallback?: RowCallback; - - fnStateLoadCallback?: StateLoadCallback; - fnStateLoadParams?: StateLoadParams; - fnStateLoaded?: StateLoaded; - fnStateSaveCallback?: StateSaveCallback; - fnStateSaveParams?: StateSaveParams; - iCookieDuration?: number; - iDeferLoading?: any; - iDisplayLength?: number; - iDisplayStart?: number; - iScrollLoadGap?: number; - iTabIndex?: number; - oLanguage?: LanguageOptions; - oSearch?: any; - sAjaxDataProp?: string; - sAjaxSource?: string; - sCookiePrefix?: string; - sDom?: string; - sPaginationType?: string; - sScrollX?: string; - sScrollXInner?: string; - sScrollY?: string; - sServerMethod? : string; - } - - export interface LanguageOptions - { - oAria? : AriaOptions; - oPaginate? : PaginateOptions; - sEmptyTable?: string; - sInfo?: string; - sInfoEmpty?: string; - sInfoFiltered?: string; - sInfoPostFix?: string; - sInfoThousands?: string; - sLengthMenu?: string; - sLoadingRecords?: string; - sProcessing?: string; - sSearch?: string; - sUrl?: string; - sZeroRecords?: string; - } - - export interface AriaOptions - { - sSortAscending?: string; - sSortDescending?: string; - } - - export interface PaginateOptions - { - sFirst?: string; - sLast?: string; - sNext?: string; - sPrevious?: string; - } - - export interface ColumnOptions - { - aDataSort?: number[]; - asSorting?: string[]; - bSearchable? : boolean; - bSortable? : boolean; - bVisible? : boolean; - _bAutoType? : boolean; - fnCreatedCell?: CreatedCell; - iDataSort?: number; - mData?: any; - mRender?: any; - sCellType?: string; - sClass?: string; - sContentPadding?: string; - sDefaultContent?: string; - sName?: string; - sSortDataType?: string; - sSortingClass?: string; - sTitle?: string; - sType?: string; - sWidth?: string; - } - - export interface ColumnDef extends ColumnOptions - { - aTargets: any[]; - } - - export interface Settings - { - oFeatures : Features; - oScroll: ScrollingSettings; - oLanguage : { fnInfoCallback : InfoCallback; }; - oBrowser : { bScrollOversize : boolean; }; - aanFeatures: Node[][]; - aoData: Row[]; - aiDisplay: number[]; - aiDisplayMaster: number[]; - aoColumns: Column[]; - aoHeader: any[]; - aoFooter: any[]; - asDataSearch: string[]; - oPreviousSearch: any; - aoPreSearchCols: any[]; - aaSorting: any[][]; - aaSortingFixed: any[][]; - asStripeClasses: string[]; - asDestroyStripes: string[]; - sDestroyWidth: number; - aoRowCallback: RowCallback[]; - aoHeaderCallback: HeaderCallback[]; - aoFooterCallback: FooterCallback[]; - aoDrawCallback: DrawCallback[]; - aoRowCreatedCallback: RowCreatedCallback[]; - aoPreDrawCallback: PreDrawCallback[]; - aoInitComplete: InitComplete[]; - aoStateSaveParams: StateSaveParams[]; - aoStateLoadParams: StateLoadParams[]; - aoStateLoaded: StateLoaded[]; - sTableId: string; - nTable: Node; - nTHead: Node; - nTFoot: Node; - nTBody: Node; - nTableWrapper: Node; - bDeferLoading: boolean; - bInitialized: boolean; - aoOpenRows: any[]; - sDom: string; - sPaginationType: string; - iCookieDuration: number; - sCookiePrefix: string; - fnCookieCallback: CookieCallback; - aoStateSave: StateSaveCallback[]; - aoStateLoad: StateLoadCallback[]; - oLoadedState: any; - sAjaxSource: string; - sAjaxDataProp: string; - bAjaxDataGet: boolean; - jqXHR: any; - fnServerData: any; - aoServerParams: any[]; - sServerMethod: string; - fnFormatNumber: FormatNumber; - aLengthMenu: any[]; - iDraw: number; - bDrawing: boolean; - iDrawError: number; - _iDisplayLength: number; - _iDisplayStart: number; - _iDisplayEnd: number; - _iRecordsTotal: number; - _iRecordsDisplay: number; - bJUI: boolean; - oClasses: any; - bFiltered: boolean; - bSorted: boolean; - bSortCellsTop: boolean; - oInit: any; - aoDestroyCallback: any[]; - fnRecordsTotal: () => number; - fnRecordsDisplay: () => number; - fnDisplayEnd: () => number; - oInstance : any; - sInstance: string; - iTabIndex: number; - nScrollHead: Node; - nScrollFoot: Node; - } - - export interface Features - { - bAutoWidth: boolean; - bDeferRender: boolean; - bFilter: boolean; - bInfo: boolean; - bLengthChange: boolean; - bPaginate: boolean; - bProcessing: boolean; - bServerSide: boolean; - bSort: boolean; - bSortClasses: boolean; - bStateSave: boolean; - } - - export interface ScrollingSettings - { - bAutoCss : boolean; - bCollapse: boolean; - bInfinite: boolean; - iBarWidth: number; - iLoadGap: number; - sX: string; - sY: string; - } - - export interface Row - { - nTr: Node; - _aData: any; - _aSortData: any[]; - _anHidden: Node[]; - _sRowStripe: string; - } - - export interface Column - { - aDataSort: any; - asSorting: string[]; - bSearchable : boolean; - bSortable : boolean; - bVisible : boolean; - _bAutoType : boolean; - fnCreatedCell: CreatedCell; - fnGetData: (data: any, specific: string) => any; - fnSetData: (data: any, value: any) => void; - mData: any; - mRender: any; - nTh: Node; - nIf: Node; - sClass: string; - sContentPadding: string; - sDefaultContent: string; - sName: string; - sSortDataType: string; - sSortingClass: string; - sSortingClassJUI: string; - sTitle: string; - sType: string; - sWidth: string; - sWidthOrig: string; - } - - export interface CookieCallback - { - (name: string, data: any, expires: string, path: string, cookie: string) : void; - } - - export interface RowCreatedCallback - { - (row: Node, data: any[], dataIndex: number) : void; - } - - export interface DrawCallback - { - (settings: Settings) : void; - } - - export interface FooterCallback - { - (foot: Element, data: any[], start:number, end:number, display: number[]) : void; - } - - export interface FormatNumber - { - (toFormat: number) : string; - } - - export interface HeaderCallback - { - (head: Element, data: any[], start:number, end:number, display: number[]) : void; - } - - export interface InfoCallback - { - (settings: Settings, start: number, end: number, max:number, total: number, pre: string) : string; - } - - export interface InitComplete - { - (settings: Settings, json: any) : void; - } - - export interface PreDrawCallback - { - (settings: Settings) : boolean; - } - - export interface RowCallback - { - (row : Settings, data: any[], displayIndex: number, displayIndexFull: number) : void; - } - - export interface StateLoadCallback - { - (settings: Settings) : any; - } - - export interface StateLoadParams - { - (settings: Settings, data: any) : void; - } - - export interface StateLoaded - { - (settings: Settings, data: any) : void; - } - - export interface StateSaveCallback - { - (settings: any, data:any) : void; - } - - export interface StateSaveParams - { - (settings: any, data:any) : void; - } - - export interface CreatedCell - { - (nTd: Node, cellData: any, rowData: any, row: number, col: number) : void; - } -} +// Type definitions for JQuery DataTables 1.10.5 +// Project: http://www.datatables.net +// Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// missing: +// - Static methods that are defined in JQueryStatic.fn are not typed. +// - Plugin and extension definitions are not typed. +// - Some return types are not fully wokring + +/// + +interface JQuery { + DataTable(param?: DataTables.Settings): DataTables.DataTable; +} + +//TODO: Wrong, as jquery.d.ts has no interface for fn +//interface JQueryStatic { +// dataTable: DataTables.StaticFunctions; +//} + +declare module DataTables { + export interface DataTable extends DataTableCore { + /** + * Get the data for the whole table. + */ + data(): DataTable; + + /** + * Order Methods / Object + */ + order: OrderMethods; + + //#region "Cell/Cells" + + /** + * Select the cell found by a cell selector + * + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cell(cellSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], modifier?: ObjectSelectorModifier): CellMethods; + + /** + * Select the cell found by a cell selector + * + * @param rowSelector Row selector. + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cell(rowSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], cellSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], modifier?: ObjectSelectorModifier): CellMethods; + + /** + * Select all cells + * + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cells(modifier?: ObjectSelectorModifier): CellsMethods; + + /** + * Select cells found by a cell selector + * + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cells(cellSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], modifier?: ObjectSelectorModifier): CellsMethods; + + /** + * Select cells found by both row and column selectors + * + * @param rowSelector Row selector. + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cells(rowSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], cellSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], modifier?: ObjectSelectorModifier): CellsMethods; + //#endregion "Cell/Cells" + + //#region "Column/Columns" + + /** + * Column Methods / Object + */ + column: ColumnMethodsModel; + + /** + * Columns Methods / Object + */ + columns: ColumnsMethodsModel; + + //#endregion "Column/Columns" + + //#region "Row/Rows" + + /** + * Row Methode / Object + */ + row: RowMethodsModel + + /** + * Rows Methods / Object + */ + rows: RowsMethodsModel + + //#endregion "Row/Rows" + + //#region "Table/Tables" + + /** + * Select a table based on a selector from the API's context + * + * @param tableSelector Table selector. + */ + table(tableSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[]): TableMethods; + + /** + * Select all tables + */ + tables(): TablesMethods; + + /** + * Select tables based on the given selector + * + * @param tableSelector Table selector. + */ + tables(tableSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[]): TablesMethods; + + //#endregion "Table/Tables" + } + + export interface DataTables extends DataTableCore { + [index: number]: DataTable; + } + + interface ObjectSelectorModifier { + /** + * The order modifier provides the ability to control which order the rows are processed in. + * Values: 'current', 'applied', 'index', 'original' + */ + order?: string; + + /** + * The search modifier provides the ability to govern which rows are used by the selector using the search options that are applied to the table. + * Values: 'none', 'applied', 'removed' + */ + search?: string; + + /** + * The page modifier allows you to control if the selector should consider all data in the table, regardless of paging, or if only the rows in the currently disabled page should be used. + * Values: 'all', 'current' + */ + page?: string; + } + + //#region "Namespaces" + + //#region "core-methods" + + interface DataTableCore extends UtilityMethods { + /** + * Get jquery object + */ + $(selector: string | Node | Node[]| JQuery, modifier?: ObjectSelectorModifier): JQuery; + + ///// Almost identical to $ in operation, but in this case returns the data for the matched rows. + //_(selector: string | Node | Node[] | JQuery, modifier?: ObjectSelectorModifier): JQuery; + + /** + * Ajax Methods + */ + ajax: AjaxMethodModel; + + /** + * Clear the table of all data. + */ + clear(): DataTable; + + /** + * Destroy the DataTables in the current context. + * + * @param remove Completely remove the table from the DOM (true) or leave it in the DOM in its original plain un-enhanced HTML state (default, false). + */ + destroy(remove?: boolean): DataTable; + + /** + * Destroy the DataTables in the current context. + * + * @param reset Reset (default) or hold the current paging position. A full re-sort and re-filter is performed when this method is called, which is why the pagination reset is the default action. + */ + draw(reset?: boolean): DataTable; + + /** + * Table events removal. + * + * @param event Event name to remove. + * @param callback Specific callback function to remove if you want to unbind a single event listener. + */ + off(event: string, callback?: Function): DataTable; + + /** + * Table events listener. + * + * @param event Event to listen for. + * @param callback Specific callback function to remove if you want to unbind a single event listener. + */ + on(event: string, callback: Function): DataTable; + + /** + * Listen for a table event once and then remove the listener. + * + * @param event Event to listen for. + * @param callback Specific callback function to remove if you want to unbind a single event listener. + */ + one(event: string, callback: Function): DataTable; + + /** + * Page Methods / Object + */ + page: PageMethods; + + /** + * Get current search + */ + search(): string; + + /** + * Search for data in the table. + * + * @param input Search string to apply to the table. + * @param regex Treat as a regular expression (true) or not (default, false). + * @param smart Perform smart search. + * @param caseInsen Do case-insensitive matching (default, true) or not (false). + */ + search(input: string, regex?: boolean, smart?: boolean, caseInsen?: boolean): DataTable; + + /** + * Obtain the table's settings object + */ + settings(): DataTable; + + /** + * Page Methods / Object + */ + state: StateMethods; + } + + //#region "ajax-methods" + + interface AjaxMethods extends DataTable { + /** + * Reload the table data from the Ajax data source. + * + * @param callback Function which is executed when the data as been reloaded and the table fully redrawn. + * @param resetPaging Reset (default action or true) or hold the current paging position (false). + */ + load(callback?: Function, resetPaging?: boolean): DataTable; + } + + interface AjaxMethodModel { + /** + * Get the latest JSON data obtained from the last Ajax request DataTables made + */ + json(): Object; + + /** + * Get the data submitted by DataTables to the server in the last Ajax request + */ + params(): Object; + + /** + * Reload the table data from the Ajax data source. + * + * @param callback Function which is executed when the data as been reloaded and the table fully redrawn. + * @param resetPaging Reset (default action or true) or hold the current paging position (false). + */ + reload(callback?: Function, resetPaging?: boolean): DataTable; + + /** + * Reload the table data from the Ajax data source + */ + url(): string; + + /** + * Reload the table data from the Ajax data source + * + * @param url URL to set to be the Ajax data source for the table. + */ + url(url: string): AjaxMethods; + } + + //#endregion "ajax-methods" + + //#region "order-methods" + + interface OrderMethods { + /** + * Get the ordering applied to the table. + */ + (): (string | number)[][]; + + /** + * Set the ordering applied to the table. + * + * @param order Order Model + */ + (order?: (string | number)[]): DataTable; + (order?: (string | number)[][]): DataTable; + (order: (string | number)[], ...args: any[]): DataTable; + + /** + * Add an ordering listener to an element, for a given column. + * + * @param node Selector + * @param column Column index + * @param callback Callback function + */ + listener(node: string | Node | JQuery, column: number, callback: Function): DataTable; + } + //#endregion "order-methods" + + //#region "page-methods" + + interface PageMethods { + /** + * Get the current page of the table. + */ + (): number; + + /** + * Set the current page of the table. + * + * @param page Index or 'first', 'next', 'previous', 'last' + */ + (page: number | string): DataTable; + + /** + * Get paging information about the table + */ + info(): PageMethodeModelInfoReturn; + + /** + * Get the table's page length. + */ + len(): number; + + /** + * Set the table's page length. + * + * @param length Page length to set. use -1 to show all records. + */ + len(length: number): DataTable; + } + + interface PageMethodeModelInfoReturn { + page: number; + pages: number; + start: number; + end: number; + length: number; + recordsTotal: number; + recordsDisplay: number; + } + + //#endregion "page-methods" + + //#region "state-methods" + + interface StateMethods { + /** + * Get the last saved state of the table + */ + (): StateReturnModel; + + /** + * Clear the saved state of the table. + */ + clear(): DataTable; + + /** + * Get the table state that was loaded during initialisation. + */ + loaded(): StateReturnModel; + + /** + * Trigger a state save. + */ + save(): DataTable; + } + + interface StateReturnModel { + time: number; + start: number; + length: number; + order: (string | number)[][]; + search: SearchSettings; + columns: StateReturnModelColumns[]; + } + + interface StateReturnModelColumns { + search: SearchSettings; + visible: boolean; + } + + //#endregion "state-methods" + + //#endregion "core-methods" + + //#region "util-methods" + + interface UtilityMethods { + /** + * Concatenate two or more API instances together + * + * @param a API instance to concatenate to the initial instance. + * @param b Additional API instance(s) to concatenate to the initial instance. + */ + concat(a: Object, ...b: Object[]): DataTable; + + /** + * Iterate over the contents of the API result set. + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with three parameters + */ + each(fn: Function): DataTable; + + /** + * Reduce an Api instance to a single context and result set. + * + * @param idx Index to select + */ + eq(idx: number): DataTable; + + /** + * Iterate over the result set of an API instance and test each item, creating a new instance from those items which pass. + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with three parameters. + */ + filter(fn: Function): DataTable; + + /** + * Flatten a 2D array structured API instance to a 1D array structure. + */ + flatten(): DataTable; + + /** + * Find the first instance of a value in the API instance's result set. + * + * @param value Value to find in the instance's result set. + */ + indexOf(value: any): number; + + /** + * Join the elements in the result set into a string. + * + * @param separator The string that will be used to separate each element of the result set. + */ + join(separator: string): string; + + /** + * Find the last instance of a value in the API instance's result set. + * + * @param value Value to find in the instance's result set. + */ + lastIndexOf(value: any): number; + + /** + * Number of elements in an API instance's result set. + */ + length: number; + + /** + * Iterate over the result set of an API instance, creating a new API instance from the values returned by the callback. + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with three parameters. + */ + map(fn: Function): DataTable; + + /** + * Iterate over the result set of an API instance, creating a new API instance from the values retrieved from the original elements. + * + * @param property Object property name to use from the element in the original result set for the new result set. + */ + pluck(property: number | string): DataTable; + + /** + * Remove the last item from an API instance's result set. + */ + pop(): any; + + /** + * Add one or more items to the end of an API instance's result set. + * + * @param value_1 Item to add to the API instance's result set. + */ + push(value_1: any | any[], ...value_2: any[]): number; + + /** + * Apply a callback function against and accumulator and each element in the Api's result set (left-to-right). + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with four parameters. + * @param initialValue Value to use as the first argument of the first call to the fn callback. + */ + reduce(fn: Function, initialValue?: any): any; + + /** + * Apply a callback function against and accumulator and each element in the Api's result set (right-to-left). + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with four parameters. + * @param initialValue Value to use as the first argument of the first call to the fn callback. + */ + reduceRight(fn: Function, initialValue?: any): any; + + /** + * Reverse the result set of the API instance and return the original array. + */ + reverse(): DataTable; + + /** + * Remove the first item from an API instance's result set. + */ + shift(): any; + + /** + * Sort the elements of the API instance's result set. + * + * @param fn This is a standard Javascript sort comparison function. It accepts two parameters. + */ + sort(fn?: Function): DataTable; + + /** + * Modify the contents of an Api instance's result set, adding or removing items from it as required. + * + * @param index Index at which to start modifying the Api instance's result set. + * @param howMany Number of elements to remove from the result set. + * @param value_1 Item to add to the result set at the index specified by the first parameter. + */ + splice(index: number, howMany: number, value_1?: any | any[], ...value_2: any[]): any[]; + + /** + * Convert the API instance to a jQuery object, with the objects from the instance's result set in the jQuery result set. + */ + to$(): JQuery; + + /** + * Create a native Javascript array object from an API instance. + */ + toArray(): any[]; + + /** + * Convert the API instance to a jQuery object, with the objects from the instance's result set in the jQuery result set. + */ + toJQuery(): JQuery; + + /** + * Create a new API instance containing only the unique items from a the elements in an instance's result set. + */ + unique(): DataTable; + + /** + * Add one or more items to the start of an API instance's result set. + * + * @param value_1 Item to add to the API instance's result set. + */ + unshift(value_1: any | any[], ...value_2: any[]): number; + } + + //#endregion "util-methods" + + interface CommonSubMethods { + /** + * Get the DataTables cached data for the selected cell + * + * @param t Specify which cache the data should be read from. Can take one of two values: search or order + */ + cache(t: string): DataTable; + } + + //#region "cell-methods" + + interface CommonCellMethods extends CommonSubMethods { + /** + * Invalidate the data held in DataTables for the selected cells + * + * @param source Data source to read the new data from. + */ + invalidate(source?: string): DataTable; + + /** + * Get data for the selected cell + * + * @param f Data type to get. This can be one of: 'display', 'filter', 'sort', 'type' + */ + render(t: string): any; + } + + interface CellMethods extends DataTableCore, CommonCellMethods { + /** + * Get data for the selected cell + */ + data(): any; + + /** + * Get data for the selected cell + * + * @param data Value to assign to the data for the cell + */ + data(data: any): DataTable; + + /** + * Get index information about the selected cell + */ + index(): CellIndexReturn; + + /** + * Get the DOM element for the selected cell + */ + node(): Node; + } + + interface CellIndexReturn { + row: number; + column: number; + columnVisible: number; + } + + interface CellsMethods extends DataTableCore, CommonCellMethods { + /** + * Get data for the selected cells + */ + data(): DataTable; + + /** + * Get index information about the selected cells + */ + indexes(): DataTable; + + /** + * Get the DOM elements for the selected cells + */ + nodes(): DataTable; + } + //#endregion "cell-methods" + + //#region "column-methods" + + interface CommonColumnMethod extends CommonSubMethods { + /** + * Get the footer th / td cell for the selected column. + */ + footer(): any; + + /** + * Get the header th / td cell for a column. + */ + header(): Node; + + /** + * Order the table, in the direction specified, by the column selected by the column()DT selector. + * + * @param direction Direction of sort to apply to the selected column - desc (descending) or asc (ascending). + */ + order(direction: string): DataTable; + + /** + * Get the visibility of the selected column. + */ + visible(): boolean; + + /** + * Set the visibility of the selected column. + * + * @param show Specify if the column should be visible (true) or not (false). + * @param redrawCalculations Indicate if DataTables should recalculate the column layout (true - default) or not (false). Typically this would be left as the default value, but it can be useful to disable when using the method in a loop - so the calculations are performed on every call as they can hamper performance. + */ + visible(show: boolean, redrawCalculations?: boolean): DataTable; + } + + interface ColumnMethodsModel { + /** + * Select the column found by a column selector + * + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (columnSelector: any, modifier?: ObjectSelectorModifier): ColumnMethods; + + /** + * Convert from the input column index type to that required. + * + * @param t The type on conversion that should take place: 'fromVisible', 'toData', 'fromData', 'toVisible' + * @param index The index to be converted + */ + index(t: string, index: number): number; + } + + interface ColumnMethods extends DataTableCore, CommonColumnMethod { + /** + * Get the data for the cells in the selected column. + */ + data(): DataTable; + + /** + * Get the data source property for the selected column + */ + dataSrc(): number | string | Function; + + /** + * Get index information about the selected cell + * + * @param t Specify if you want to get the column data index (default) or the visible index (visible). + */ + index(t?: string): DataTable; + + /** + * Obtain the th / td nodes for the selected column + */ + nodes(): DataTable[]; + } + + interface ColumnsMethodsModel { + /** + * Select all columns + * + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (modifier?: ObjectSelectorModifier): ColumnsMethods; + + /** + * Select columns found by a cell selector + * + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (columnSelector: any, modifier?: ObjectSelectorModifier): ColumnsMethods; + + /** + * Recalculate the column widths for layout. + */ + adjust(): DataTable; + } + + interface ColumnsMethods extends DataTableCore, CommonColumnMethod { + /** + * Obtain the data for the columns from the selector + */ + data(): DataTable; + + /** + * Get the data source property for the selected columns. + */ + dataSrc(): DataTable; + + /** + * Get the column indexes of the selected columns. + * + * @param t Specify if you want to get the column data index (default) or the visible index (visible). + */ + indexes(t?: string): DataTable; + + /** + * Obtain the th / td nodes for the selected columns + */ + nodes(): DataTable[][]; + } + //#endregion "column-methods" + + //#region "row-methods" + + interface CommonRowMethod extends CommonSubMethods { + /** + * Obtain the th / td nodes for the selected column + * + * @param source Data source to read the new data from. Values: 'auto', 'data', 'dom' + */ + invalidate(source?: string): DataTable; + } + + interface RowChildMethodModel { + /** + * Get the child row(s) that have been set for a parent row + */ + (): JQuery; + + /** + * Get the child row(s) that have been set for a parent row + * + * @param showRemove This parameter can be given as true or false + */ + (showRemove: boolean): RowChildMethods; + + /** + * Set the data to show in the child row(s). Note that calling this method will replace any child rows which are already attached to the parent row. + * + * @param data The data to be shown in the child row can be given in multiple different ways. + * @param className Class name that is added to the td cell node(s) of the child row(s). As of 1.10.1 it is also added to the tr row node of the child row(s). + */ + (data: (string | Node | JQuery) | (string | Node | JQuery)[], className?: string): RowChildMethods; + + /** + * Hide the child row(s) of a parent row + */ + hide(): DataTable; + + /** + * Check if the child rows of a parent row are visible + */ + isShown(): DataTable; + + /** + * Remove child row(s) from display and release any allocated memory + */ + remove(): DataTable; + + /** + * Show the child row(s) of a parent row + */ + show(): DataTable; + } + + interface RowChildMethods extends DataTableCore { + /** + * Hide the child row(s) of a parent row + */ + hide(): DataTable; + + /** + * Remove child row(s) from display and release any allocated memory + */ + remove(): DataTable; + + /** + * Make newly defined child rows visible + */ + show(): DataTable; + } + + interface RowMethodsModel { + /** + * Select a row found by a row selector + * + * @param rowSelector Row selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (rowSelector: any, modifier?: ObjectSelectorModifier): RowMethods; + + /** + * Add a new row to the table using the given data + * + * @param data Data to use for the new row. This may be an array, object or Javascript object instance, but must be in the same format as the other data in the table + */ + add(data: any[]| Object): DataTable; + } + + interface RowMethods extends DataTableCore, CommonRowMethod { + /** + * Order Methods / Object + */ + child: RowChildMethodModel; + + /** + * Get the data for the selected row + */ + data(): any[]| Object; + + /** + * Set the data for the selected row + * + * @param d Data to use for the row. + */ + data(d: any[]| Object): DataTable; + + /** + * Get the row index of the row column. + */ + index(): number; + + /** + * Obtain the tr node for the selected row + */ + node(): Node; + + /** + * Delete the selected row from the DataTable. + */ + remove(): Node; + } + + interface RowsMethodsModel { + /** + * Select all rows + * + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (modifier?: ObjectSelectorModifier): RowsMethods; + + /** + * Select rows found by a row selector + * + * @param cellSelector Row selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (rowSelector: any, modifier?: ObjectSelectorModifier): RowsMethods; + + /** + * Add new rows to the table using the data given + * + * @param data Array of data elements, with each one describing a new row to be added to the table + */ + add(data: any[]): DataTable; + } + + interface RowsMethods extends DataTableCore, CommonRowMethod { + /** + * Get the data for the rows from the selector + */ + data(): DataTable; + + /** + * Set the data for the selected row + * + * @param d Data to use for the row. + */ + data(d: any[]| Object): DataTable; + + /** + * Get the row indexes of the selected rows. + */ + indexes(): DataTable; + + /** + * Obtain the tr nodes for the selected rows + */ + nodes(): DataTable; + + /** + * Delete the selected rows from the DataTable. + */ + remove(): DataTable; + } + //#endregion "row-methods" + + //#region "table-methods" + + interface TableMethods extends DataTableCore { + /** + * Get the tfoot node for the table in the API's context + */ + footer(): Node; + + /** + * Get the thead node for the table in the API's context + */ + header(): Node; + + /** + * Get the tbody node for the table in the API's context + */ + body(): Node; + + /** + * Get the div container node for the table in the API's context + */ + container(): Node; + + /** + * Get the table node for the table in the API's context + */ + node(): Node; + } + + interface TablesMethods extends DataTableCore { + /** + * Get the tfoot nodes for the tables in the API's context + */ + footer(): DataTable; + + /** + * Get the thead nodes for the tables in the API's context + */ + header(): DataTable; + + /** + * Get the tbody nodes for the tables in the API's context + */ + body(): DataTable; + + /** + * Get the div container nodes for the tables in the API's context + */ + containers(): DataTable; + + /** + * Get the table nodes for the tables in the API's context + */ + nodes(): DataTable; + } + //#endregion "table-methods" + + //#endregion "Namespaces" + + //#region "Static-Methods" + + export interface StaticFunctions { + /** + * Check is a table node is a DataTable or not + * + * @param table Selector string for table + */ + isDataTable(table: string): boolean; + + /** + * Get all DataTables on the page + * + * @param visible Get only visible tables + */ + tables(visible?: boolean): DataTables.DataTable[]; + + /** + * Version number compatibility check function + * + * @param version Version string + */ + versionCheck(version: string): boolean; + + /** + * Utils + */ + util: StaticUtilFunctions; + + /** + * Check is a table node is a DataTable or not + * + * @param table Selector string for table + */ + Api(selector: string | Node | Node[]| JQuery): DataTables.DataTable; + } + + export interface StaticUtilFunctions { + /** + * Escape special characters in a regular expression string. Since: 1.10.4 + * + * @param str String to escape + */ + escapeRegex(str: string): string; + + /** + * Throttle the calls to a method to reduce call frequency. Since: 1.10.3 + * + * @param fn Function + * @param period ms + */ + throttle(fn: Function, period?: number): Function; + } + + //#endregion "Static-Methods" + + //#region "Settings" + + export interface Settings { + + //#region "Features" + + /** + * Feature control DataTables' smart column width handling. Since: 1.10 + */ + autoWidth?: boolean; + + /** + * Feature control deferred rendering for additional speed of initialisation. Since: 1.10 + */ + deferRender?: boolean; + + /** + * Feature control table information display field. Since: 1.10 + */ + info?: boolean; + + /** + * Use markup and classes for the table to be themed by jQuery UI ThemeRoller. Since: 1.10 + */ + jQueryUI?: boolean; + + /** + * Feature control the end user's ability to change the paging display length of the table. Since: 1.10 + */ + lengthChange?: boolean; + + /** + * Feature control ordering (sorting) abilities in DataTables. Since: 1.10 + */ + ordering?: boolean; + + /** + * Enable or disable table pagination. Since: 1.10 + */ + paging?: boolean; + + /** + * Feature control the processing indicator. Since: 1.10 + */ + processing?: boolean; + + /** + * Horizontal scrolling. Since: 1.10 + */ + scrollX?: boolean; + + /** + * Vertical scrolling. Since: 1.10 Exp: "200px" + */ + scrollY?: string; + + /** + * Feature control search (filtering) abilities Since: 1.10 + */ + searching?: boolean; + + /** + * Feature control DataTables' server-side processing mode. Since: 1.10 + */ + serverSide?: boolean; + + /** + * State saving - restore table state on page reload. Since: 1.10 + */ + stateSave?: boolean; + + //#endregion "Features" + + //#region "Data" + + /** + * Load data for the table's content from an Ajax source. Since: 1.10 + */ + ajax?: string | AjaxSettings | FunctionAjax; + + /** + * Data to use as the display data for the table. Since: 1.10 + */ + data?: Object; + + //#endregion "Data" + + //#region "Options" + + /** + * Data to use as the display data for the table. Since: 1.10 + */ + columns?: ColumnSettings[]; + + /** + * Assign a column definition to one or more columns.. Since: 1.10 + */ + columnDefs?: ColumnDefsSettings[]; + + /** + * Delay the loading of server-side data until second draw + */ + deferLoading?: number | number[]; + + /** + * Destroy any existing table matching the selector and replace with the new options. Since: 1.10 + */ + destroy?: boolean; + + /** + * Initial paging start point. Since: 1.10 + */ + displayStart?: number; + + /** + * Define the table control elements to appear on the page and in what order. Since: 1.10 + */ + dom?: string; + + /** + * Change the options in the page length select list. Since: 1.10 + */ + lengthMenu?: (number | string)[]| (number | string)[][]; + + /** + * Control which cell the order event handler will be applied to in a column. Since: 1.10 + */ + orderCellsTop?: boolean; + + /** + * Highlight the columns being ordered in the table's body. Since: 1.10 + */ + orderClasses?: boolean; + + /** + * Initial order (sort) to apply to the table. Since: 1.10 + */ + order?: (string | number)[]| (string | number)[][]; + + /** + * Ordering to always be applied to the table. Since: 1.10 + */ + orderFixed?: (string | number)[]| (string | number)[][]| Object; + + /** + * Multiple column ordering ability control. Since: 1.10 + */ + orderMulti?: boolean; + + /** + * Change the initial page length (number of rows per page). Since: 1.10 + */ + pageLength?: number; + + /** + * Pagination button display options. Basic Types: simple, simple_numbers, full, full_numbers + */ + pagingType?: string; + + /** + * Retrieve an existing DataTables instance. Since: 1.10 + */ + retrieve?: boolean + + /** + * Display component renderer types. Since: 1.10 + */ + renderer?: string | RendererSettings; + + /** + * Allow the table to reduce in height when a limited number of rows are shown. Since: 1.10 + */ + scrollCollapse?: boolean; + + /** + * Set an initial filter in DataTables and / or filtering options. Since: 1.10 + */ + search?: SearchSettings; + + /** + * Define an initial search for individual columns. Since: 1.10 + */ + searchCols?: SearchSettings[]; + + /** + * Set a throttle frequency for searching. Since: 1.10 + */ + searchDelay?: number; + + /** + * Saved state validity duration. Since: 1.10 + */ + stateDuration?: number; + + /** + * Set the zebra stripe class names for the rows in the table. Since: 1.10 + */ + stripeClasses?: string[]; + + /** + * Tab index control for keyboard navigation. Since: 1.10 + */ + tabIndex?: number; + + //#endregion "Options" + + //#region "Callbacks" + + /** + * Callback for whenever a TR element is created for the table's body. Since: 1.10 + */ + createdRow?: FunctionCreateRow; + + /** + * Function that is called every time DataTables performs a draw. Since: 1.10 + */ + drawCallback?: FunctionDrawCallback; + + /** + * Footer display callback function. Since: 1.10 + */ + footerCallback?: FunctionFooterCallback; + + /** + * Number formatting callback function. Since: 1.10 + */ + formatNumber?: FunctionFormatNumber; + + /** + * Header display callback function. Since: 1.10 + */ + headerCallback?: FunctionHeaderCallback; + + /** + * Table summary information display callback. Since: 1.10 + */ + infoCallback?: FunctionInfoCallback; + + /** + * Initialisation complete callback. Since: 1.10 + */ + initComplete?: FunctionInitComplete; + + /** + * Pre-draw callback. Since: 1.10 + */ + preDrawCallback?: FunctionPreDrawCallback; + + /** + * Row draw callback.. Since: 1.10 + */ + rowCallback?: FunctionRowCallback; + + /** + * Callback that defines where and how a saved state should be loaded. Since: 1.10 + */ + stateLoadCallback?: FunctionStateLoadCallback; + + /** + * State loaded callback. Since: 1.10 + */ + stateLoaded?: FunctionStateLoaded; + + /** + * State loaded - data manipulation callback. Since: 1.10 + */ + stateLoadParams?: FunctionStateLoadParams; + + /** + * Callback that defines how the table state is stored and where. Since: 1.10 + */ + stateSaveCallback?: FunctionStateSaveCallback; + + /** + * State save - data manipulation callback. Since: 1.10 + */ + stateSaveParams?: FunctionStateSaveParams; + + //#endregion "Callbacks" + + //#region "Language" + + language?: LanguageSettings; + + //#endregion "Language" + } + + //#region "ajax-settings" + + export interface AjaxDataRequest { + draw: number; + start: number; + length: number; + data: any; + order: AjaxDataRequestOrder[]; + columns: AjaxDataRequestColumn[]; + search: AjaxDataRequestSearch; + } + + export interface AjaxDataRequestSearch { + value: string; + regex: boolean; + } + + export interface AjaxDataRequestOrder { + column: number; + dir: string; + } + + export interface AjaxDataRequestColumn { + data: string | number; + name: string; + searchable: boolean; + orderable: boolean; + search: AjaxDataRequestSearch; + } + + export interface AjaxData { + draw: number; + recordsTotal: number; + recordsFiltered: number; + data: any; + error?: string; + } + + interface AjaxSettings extends JQueryAjaxSettings { + /** + * Add or modify data submitted to the server upon an Ajax request. Since: 1.10 + */ + data?: Object | FunctionAjaxData; + + /** + * Data property or manipulation method for table data. Since: 1.10 + */ + dataSrc?: string | Function; + } + + interface FunctionAjax { + (data: Object, callback: Function, settings: SettingsLegacy): void; + } + + interface FunctionAjaxData { + (data: Object): string | Object; + } + + //#endregion "ajax-settings" + + //#region "colunm-settings" + + export interface ColumnSettings { + /** + * Cell type to be created for a column. th/td Since: 1.10 + */ + cellType?: string; + + /** + * Class to assign to each cell in the column. Since: 1.10 + */ + className?: string; + + /** + * Add padding to the text content used when calculating the optimal with for a table. Since: 1.10 + */ + contentPadding?: string; + + /** + * Cell created callback to allow DOM manipulation. Since: 1.10 + */ + createdCell?: FunctionColumnCreatedCell; + + /** + * Class to assign to each cell in the column. Since: 1.10 + */ + data?: number | string | ObjectColumnData | FunctionColumnData; + + /** + * Set default, static, content for a column. Since: 1.10 + */ + defaultContent?: string; + + /** + * Set a descriptive name for a column. Since: 1.10 + */ + name?: string; + + /** + * Enable or disable ordering on this column. Since: 1.10 + */ + orderable?: boolean; + + /** + * Define multiple column ordering as the default order for a column. Since: 1.10 + */ + orderData?: number | number[]; + + /** + * Live DOM sorting type assignment. Since: 1.10 + */ + orderDataType?: string; + + /** + * Order direction application sequence. Since: 1.10 + */ + orderSequence?: string[]; + + /** + * Render (process) the data for use in the table. Since: 1.10 + */ + render?: number | string | ObjectColumnRender | FunctionColumnRender; + + /** + * Enable or disable filtering on the data in this column. Since: 1.10 + */ + searchable?: boolean; + + /** + * Set the column title. Since: 1.10 + */ + title?: string; + + /** + * Set the column type - used for filtering and sorting string processing. Since: 1.10 + */ + type?: string; + + /** + * Enable or disable the display of this column. Since: 1.10 + */ + visible?: boolean; + + /** + * Column width assignment. Since: 1.10 + */ + width?: string; + } + + interface ColumnDefsSettings extends ColumnSettings { + targets: string | number | (number | string)[] + } + + interface FunctionColumnCreatedCell { + (cell: Node, cellData: any, rowData: any, row: number, col: number): void; + } + + interface FunctionColumnData { + (row: any, t: string, s: any, meta: Object): void; + } + + interface ObjectColumnData { + _: string; + filter?: string; + display?: string; + type?: string; + sort?: string; + } + + interface ObjectColumnRender extends ObjectColumnData { + } + + interface FunctionColumnRender { + (data: Node, t: Node, row: Node, meta: Object): void; + } + + //#endregion "colunm-settings" + + //#region "other-settings" + + export interface RendererSettings { + header?: string; + pageButton?: string; + } + + export interface SearchSettings { + /** + * Control case-sensitive filtering option. Since: 1.10 + */ + caseInsensitive?: boolean; + + /** + * Enable / disable escaping of regular expression characters in the search term. Since: 1.10 + */ + regex?: boolean; + + /** + * Enable / disable DataTables' smart filtering. Since: 1.10 + */ + smart?: boolean; + + /** + * Set an initial filtering condition on the table. Since: 1.10 + */ + search?: string; + } + + //#endregion "other-settings" + + //#region "callback-functions" + + interface FunctionCreateRow { + (row: Node, data: any[]| Object, dataIndex: number): void; + } + + interface FunctionDrawCallback { + (settings: SettingsLegacy): void; + } + + interface FunctionFooterCallback { + (tfoot: Node, data: any[], start: number, end: number, display: any[]): void; + } + + interface FunctionFormatNumber { + (formatNumber: number): void; + } + + interface FunctionHeaderCallback { + (thead: Node, data: any[], start: number, end: number, display: any[]): void; + } + + interface FunctionInfoCallback { + (settings: SettingsLegacy, start: number, end: number, mnax: number, total: number, pre: string): void; + } + + interface FunctionInitComplete { + (settings: SettingsLegacy, json: Object): void; + } + + interface FunctionPreDrawCallback { + (settings: SettingsLegacy): void; + } + + interface FunctionRowCallback { + (row: Node, data: any[]| Object): void; + } + + interface FunctionStateLoadCallback { + (settings: SettingsLegacy): void; + } + + interface FunctionStateLoaded { + (settings: SettingsLegacy, data: Object): void; + } + + interface FunctionStateLoadParams { + (settings: SettingsLegacy, data: Object): void; + } + + interface FunctionStateSaveCallback { + (settings: SettingsLegacy, data: Object): void; + } + + interface FunctionStateSaveParams { + (settings: SettingsLegacy, data: Object): void; + } + + //#endregion "callback-functions" + + //#region "language-settings" + + interface LanguageSettings { + emptyTable: string; + info: string; + infoEmpty: string; + infoFiltered: string; + infoPostFix: string; + thousands: string; + lengthMenu: string; + loadingRecords: string; + processing: string; + search: string; + zeroRecords: string; + paginate: LanguagePaginateSettings; + aria: LanguageAriaSettings; + } + + interface LanguagePaginateSettings { + first: string; + last: string; + next: string; + previous: string; + } + + interface LanguageAriaSettings { + sortAscending: string; + sortDescending: string; + } + + //#endregion "language-settings" + + //#endregion "Settings" + + //#region "SettingsLegacy" + + interface ArrayStringNode { + [index: string]: Node; + } + + export interface SettingsLegacy { + ajax: any; + oApi: any; + oFeatures: FeaturesLegacy; + oScroll: ScrollingLegacy; + oLanguage: LanguageLegacy; // | { fnInfoCallback: FunctionInfoCallback; }; + oBrowser: { bScrollOversize: boolean; }; + aanFeatures: ArrayStringNode[][]; + aoData: RowLegacy[]; + aiDisplay: number[]; + aiDisplayMaster: number[]; + aoColumns: ColumnLegacy[]; + aoHeader: any[]; + aoFooter: any[]; + asDataSearch: string[]; + oPreviousSearch: any; + aoPreSearchCols: any[]; + aaSorting: any[][]; + aaSortingFixed: any[][]; + asStripeClasses: string[]; + asDestroyStripes: string[]; + sDestroyWidth: number; + aoRowCallback: FunctionRowCallback[]; + aoHeaderCallback: FunctionHeaderCallback[]; + aoFooterCallback: FunctionFooterCallback[]; + aoDrawCallback: FunctionDrawCallback[]; + aoRowCreatedCallback: FunctionCreateRow[]; + aoPreDrawCallback: FunctionPreDrawCallback[]; + aoInitComplete: FunctionInitComplete[]; + aoStateSaveParams: FunctionStateSaveParams[]; + aoStateLoadParams: FunctionStateLoadParams[]; + aoStateLoaded: FunctionStateLoaded[]; + sTableId: string; + nTable: Node; + nTHead: Node; + nTFoot: Node; + nTBody: Node; + nTableWrapper: Node; + bDeferLoading: boolean; + bInitialized: boolean; + aoOpenRows: any[]; + sDom: string; + sPaginationType: string; + iCookieDuration: number; + sCookiePrefix: string; + fnCookieCallback: CookieCallbackLegacy; + aoStateSave: FunctionStateSaveCallback[]; + aoStateLoad: FunctionStateLoadCallback[]; + oLoadedState: any; + sAjaxSource: string; + sAjaxDataProp: string; + bAjaxDataGet: boolean; + jqXHR: any; + fnServerData: any; + aoServerParams: any[]; + sServerMethod: string; + fnFormatNumber: FunctionFormatNumber; + aLengthMenu: any[]; + iDraw: number; + bDrawing: boolean; + iDrawError: number; + _iDisplayLength: number; + _iDisplayStart: number; + _iDisplayEnd: number; + _iRecordsTotal: number; + _iRecordsDisplay: number; + bJUI: boolean; + oClasses: any; + bFiltered: boolean; + bSorted: boolean; + bSortCellsTop: boolean; + oInit: any; + aoDestroyCallback: any[]; + fnRecordsTotal: () => number; + fnRecordsDisplay: () => number; + fnDisplayEnd: () => number; + oInstance: any; + sInstance: string; + iTabIndex: number; + nScrollHead: Node; + nScrollFoot: Node; + } + + export interface FeaturesLegacy { + bAutoWidth: boolean; + bDeferRender: boolean; + bFilter: boolean; + bInfo: boolean; + bLengthChange: boolean; + bPaginate: boolean; + bProcessing: boolean; + bServerSide: boolean; + bSort: boolean; + bSortClasses: boolean; + bStateSave: boolean; + } + + export interface ScrollingLegacy { + bAutoCss: boolean; + bCollapse: boolean; + bInfinite: boolean; + iBarWidth: number; + iLoadGap: number; + sX: string; + sY: string; + } + + export interface RowLegacy { + nTr: Node; + _aData: any; + _aSortData: any[]; + _anHidden: Node[]; + _sRowStripe: string; + } + + export interface ColumnLegacy { + aDataSort: any; + asSorting: string[]; + bSearchable: boolean; + bSortable: boolean; + bVisible: boolean; + _bAutoType: boolean; + fnCreatedCell: FunctionColumnCreatedCell; + fnGetData: (data: any, specific: string) => any; + fnSetData: (data: any, value: any) => void; + mData: any; + mRender: any; + nTh: Node; + nIf: Node; + sClass: string; + sContentPadding: string; + sDefaultContent: string; + sName: string; + sSortDataType: string; + sSortingClass: string; + sSortingClassJUI: string; + sTitle: string; + sType: string; + sWidth: string; + sWidthOrig: string; + } + + export interface CookieCallbackLegacy { + (name: string, data: any, expires: string, path: string, cookie: string): void; + } + + export interface LanguageLegacy { + oAria?: LanguageAriaLegacy; + oPaginate?: LanguagePaginateLegacy; + sEmptyTable?: string; + sInfo?: string; + sInfoEmpty?: string; + sInfoFiltered?: string; + sInfoPostFix?: string; + sInfoThousands?: string; + sLengthMenu?: string; + sLoadingRecords?: string; + sProcessing?: string; + sSearch?: string; + sUrl?: string; + sZeroRecords?: string; + } + + export interface LanguageAriaLegacy { + sSortAscending?: string; + sSortDescending?: string; + } + + export interface LanguagePaginateLegacy { + sFirst?: string; + sLast?: string; + sNext?: string; + sPrevious?: string; + } + //#endregion "SettingsLegacy" + +} \ No newline at end of file diff --git a/jquery.pickadate/jquery.pickadate.d.ts b/jquery.pickadate/jquery.pickadate.d.ts index 274f20f90..62b20bb22 100644 --- a/jquery.pickadate/jquery.pickadate.d.ts +++ b/jquery.pickadate/jquery.pickadate.d.ts @@ -39,6 +39,7 @@ interface pickadateOptions extends pickerOptions { formatSubmit?: string; // e.g. 'yyyy/mm/dd' hiddenPrefix?: string; // default undefined hiddenSuffix?: string; // default '_submit' + hiddenName?: boolean; // default undefined // Dropdown selectors selectYears?: any; // Specify the number of years selectable using an even integer - half before and half after the year in focus: @@ -223,23 +224,21 @@ interface TimePickerSetThings extends SetThings { interval?: any; } -interface PickerObject { +interface PickerObject { /** The picker's relative input element wrapped as a jQuery object. */ $node: JQuery; /** The picker's relative root holder element wrapped as a jQuery object. */ $root: JQuery; -} -interface DatePickerObject extends PickerObject { - open(withoutFocus?: boolean): DatePickerObject; - close(withFocus?: boolean): DatePickerObject; + open(withoutFocus?: boolean): TPickerObject; + close(withFocus?: boolean): TPickerObject; /** Rebuild the picker. */ - start(): DatePickerObject; + start(): TPickerObject; /** Destroy the picker. */ - stop(): DatePickerObject; + stop(): TPickerObject; /** * Refresh the picker box after adding something to the holder. @@ -247,10 +246,10 @@ interface DatePickerObject extends PickerObject { * has it’s contents re-rendered. To render the entire picker from * the root up, pass true as the first argument. */ - render(entirePicker?: boolean): DatePickerObject; + render(entirePicker?: boolean): TPickerObject; /** Clear the value in the picker's input element. */ - clear(): DatePickerObject; + clear(): TPickerObject; /** Short for picker.get('value') */ get(): string; @@ -262,19 +261,19 @@ interface DatePickerObject extends PickerObject { get(thing: 'value'): string; /** Returns the item object that is visually selected. */ - get(thing: 'select'): DatePickerItemObject; + get(thing: 'select'): TItemObject; /** Returns the item object that is visually highlighted. */ - get(thing: 'highlight'): DatePickerItemObject; + get(thing: 'highlight'): TItemObject; /** Returns the item object that sets the current view. */ - get(thing: 'view'): DatePickerItemObject; + get(thing: 'view'): TItemObject; /** Returns the item object that limits the picker's lower range. */ - get(thing: 'min'): DatePickerItemObject; + get(thing: 'min'): TItemObject; /** Returns the item object that limits the picker's upper range. */ - get(thing: 'max'): DatePickerItemObject; + get(thing: 'max'): TItemObject; /** Returns a boolean value of whether the picker is open or not. */ get(thing: 'open'): boolean; @@ -292,99 +291,29 @@ interface DatePickerObject extends PickerObject { get(thing: string, format: string): string; /** Set the properties, objects, and states to change the state of the picker. */ - set(thing: string, value?: any): DatePickerObject; - set(things: SetThings): DatePickerObject; + set(thing: string, value?: any, options?: any): TPickerObject; + set(things: TOptions, options?: any): TPickerObject; /** Bind callbacks to get fired off when the relative picker method is called. */ - on(methodName, callback: () => void ): DatePickerObject; + on(methodName, callback: () => void): TPickerObject; /** Bind multiple callbacks at once to get fired off when the relative picker method is called. */ - on(callbackObject: CallbackObject): DatePickerObject; + on(callbackObject: CallbackObject): TPickerObject; /** Trigger callbacks that have been queued up using the the on method. */ - trigger(event: string): DatePickerObject; + trigger(event: string): TPickerObject; } -interface TimePickerObject extends PickerObject { - open(withoutFocus?: boolean): TimePickerObject; - close(withFocus?: boolean): TimePickerObject; - - /** Rebuild the picker. */ - start(): TimePickerObject; - - /** Destroy the picker. */ - stop(): TimePickerObject; - - /** - * Refresh the picker box after adding something to the holder. - * By default, only the "face" of the picker (i.e. the box element) - * has it’s contents re-rendered. To render the entire picker from - * the root up, pass true as the first argument. - */ - render(entirePicker?: boolean): TimePickerObject; - - /** Clear the value in the picker's input element. */ - clear(): TimePickerObject; - - /** Short for picker.get('value') */ - get(): string; - - /** Get the properties, objects, and states that make up the current state of the picker. */ - get(thing: string): any; - - /** Returns the string value of the picker's input element. */ - get(thing: 'value'): string; - - /** Returns the item object that is visually selected. */ - get(thing: 'select'): TimePickerItemObject; - - /** Returns the item object that is visually highlighted. */ - get(thing: 'highlight'): TimePickerItemObject; - - /** Returns the item object that sets the current view. */ - get(thing: 'view'): TimePickerItemObject; - - /** Returns the item object that limits the picker's lower range. */ - get(thing: 'min'): TimePickerItemObject; - - /** Returns the item object that limits the picker's upper range. */ - get(thing: 'max'): TimePickerItemObject; - - /** Returns a boolean value of whether the picker is open or not. */ - get(thing: 'open'): boolean; - - /** Returns a boolean value of whether the picker has started or not. */ - get(thing: 'start'): boolean; - - /** Returns a unique 9-digit integer that is the ID of the picker. */ - get(thing: 'id'): number; - - /** Returns an array of items that determine which item objects to disable on the picker. */ - get(thing: 'disable'): any[]; - - /** Returns a formatted string for the item object specified by `thing` */ - get(thing: string, format: string): string; - - /** Set the properties, objects, and states to change the state of the picker. */ - set(thing: string, value?: any): TimePickerObject; - set(things: TimePickerSetThings): TimePickerObject; - - /** Bind callbacks to get fired off when the relative picker method is called. */ - on(methodName, callback: () => void ): TimePickerObject; - - /** Bind multiple callbacks at once to get fired off when the relative picker method is called. */ - on(callbackObject: CallbackObject): TimePickerObject; - - /** Trigger callbacks that have been queued up using the the on method. */ - trigger(event: string): TimePickerObject; -} +interface DatePickerObject extends PickerObject { } +interface TimePickerObject extends PickerObject { } interface JQuery { - pickadate(options?: pickadateOptions): HTMLInputElement; - pickatime(options?: pickatimeOptions): HTMLInputElement; + pickadate(methodName: "picker"): DatePickerObject; + pickadate(methodName: string): any; + pickadate(options?: pickadateOptions): JQuery; + + pickatime(methodName: "picker"): TimePickerObject; + pickatime(methodName: string): any; + pickatime(options?: pickatimeOptions): JQuery; } -interface HTMLInputElement { - pickadate(picker: string): DatePickerObject; - pickatime(picker: string): TimePickerObject; -} diff --git a/jquery.window/jquery.window-tests.ts b/jquery.window/jquery.window-tests.ts new file mode 100644 index 000000000..0b5fa7e83 --- /dev/null +++ b/jquery.window/jquery.window-tests.ts @@ -0,0 +1,139 @@ +/// +/// + +function example_1() { + $.window({ + title: "Cyclops Studio", + url: "http://apps.fstoke.me/" + }); +} + +function example_2() { + $.window({ + showModal: true, + modalOpacity: 0.5, + icon: "http://www.fstoke.me/favicon.ico", + title: "Professional JavaScript for Web Developers", + content: $("#window_block2").html(), // load window_block2 html content + footerContent: " This is a nice plugin :^)" + }); +}; + +function example_3() { + // prepare customerized static attributes, see static attributes + // Note: you should call this method before starting to create window instances, or windows might display wrong. + $.window.prepare({ + dock: 'bottom', // change the dock direction: 'left', 'right', 'top', 'bottom' + animationSpeed: 200, // set animation speed + minWinLong: 180 // set minimized window long dimension width in pixel + }); + + // limit window within body + $.window({ + icon: 'http://www.fstoke.me/favicon.ico', + title: "This window only can be dragged within body boundary", + content: "
I only can be dragged within body element." + + "

Really? Really? You can try it... :)
", + checkBoundary: true, + x: 80, + y: 80 + }); + + // limit window within a element + $("#my_boundary_panel").window({ + icon: 'http://mail.google.com/favicon.ico', + title: "This window only can be dragged within its parent element", + content: "
I only can be dragged within my boss...@@
", + checkBoundary: true, + width: 200, + height: 160, + maxWidth: 400, + maxHeight: 300, + x: 80, + y: 80 + }); + + // assign the dock area + $.window.prepare({ + dock: 'bottom', // change the dock direction: 'left', 'right', 'top', 'bottom' + dockArea: $('#myDockArea'), // set the dock area + animationSpeed: 200, // set animation speed + minWinLong: 180 // set minimized window long dimension width in pixel + }); +} + +function example_4() { + $.window({ + title: "Un-draggable & Un-resizable Window", + content: "
I can't be dragged...
" + + "I can't be resized too...

Of course, maximize and minimize are also disabled...

" + + "So... What can I do? I only can be closed. @_@
", + draggable: false, + resizable: false, + maximizable: false, + minimizable: false, + showModal: true + }); +} + +function example_5() { + var log = console.log; + $.window({ + title: "complext window", + content: $("#window_block5").html(), // load window_block5 html content + x: 150, // the x-axis value on screen, if -1 means put on screen center + y: 100, // the y-axis value on screen, if -1 means put on screen center + width: 600, // window width + height: 300, // window height + minWidth: 200, // the minimum width, if -1 means no checking + minHeight: 100, // the minimum height, if -1 means no checking + maxWidth: 700, // the minimum width, if -1 means no checking + maxHeight: 400, // the minimum height, if -1 means no checking + scrollable: false, // a boolean flag to show scroll bar or not + onOpen: (wnd: JQueryWindow.Window) => { // a callback function while container is added into body + alert('open'); + }, + onShow: (wnd: JQueryWindow.Window) => { // a callback function while whole window display routine is finished + alert('show'); + }, + onClose: (wnd: JQueryWindow.Window) => { // a callback function while user click close button + alert('close'); + }, + onSelect: (wnd: JQueryWindow.Window) => { // a callback function while user select the window + log('select'); + }, + onUnselect: (wnd: JQueryWindow.Window) => { // a callback function while window unselected + log('unelect'); + }, + onDrag: (wnd: JQueryWindow.Window) => { // a callback function while window is going to drag + log('drag'); + }, + afterDrag: (wnd: JQueryWindow.Window) => { // a callback function after window dragged + log('after dragged'); + }, + onResize: (wnd: JQueryWindow.Window) => { // a callback function while window is going to resize + log('resize'); + }, + afterResize: (wnd: JQueryWindow.Window) => { // a callback function after window resized + log('after resized'); + }, + onMinimize: (wnd: JQueryWindow.Window) => { // a callback function while window is going to minimize + log('minimize'); + }, + afterMinimize: (wnd: JQueryWindow.Window) => { // a callback function after window minimized + log('after minimized'); + }, + onMaximize: (wnd: JQueryWindow.Window) => { // a callback function while window is going to maximize + log('maximize'); + }, + afterMaximize: (wnd: JQueryWindow.Window) => { // a callback function after window maximized + log('after maximized'); + }, + onCascade: (wnd: JQueryWindow.Window) => { // a callback function while window is going to cascade + log('cascade'); + }, + afterCascade: (wnd: JQueryWindow.Window) => { // a callback function after window cascaded + log('after cascaded'); + } + }); +} \ No newline at end of file diff --git a/jquery.window/jquery.window.d.ts b/jquery.window/jquery.window.d.ts new file mode 100644 index 000000000..8fb4bbc81 --- /dev/null +++ b/jquery.window/jquery.window.d.ts @@ -0,0 +1,460 @@ +// Type definitions for Window plugin for jQuery 5.0.4 +// Project: http://fstoke.me/jquery/window/ +// Definitions by: Ryan Graham +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module JQueryWindow { + // Instance methods + interface Window { + /** + get window id + **/ + getWindowId(): string; + /** + get window container's parent panel, it's a jQuery object + **/ + getCaller(): JQuery; + /** + get window container panel, it's a jQuery object + **/ + getContainer(): JQuery; + /** + get window header panel, it's a jQuery object + **/ + getHeader(): JQuery; + /** + get window frame panel, it's a jQuery object + **/ + getFrame(): JQuery; + /** + get window footer panel, it's a jQuery object + **/ + getFooter(): JQuery; + /** + set current window as screen center + **/ + alignCenter(): void; + /** + set current window as horizontal center + **/ + alignHorizontalCenter(): void; + /** + set current window as vertical center + **/ + alignVerticalCenter(): void; + /** + select current window, it will increase the original z-index value with 2 + **/ + select(): void; + /** + unselect current window, it will set the z-index as original options.z + **/ + unselect(): void; + /** + move current window to target position or shift it by passed distance + **/ + move(x: number, y: number, bShift: boolean): void; + /** + resize current window to target width/height + **/ + resize(width: number, height: number): void; + /** + maximize current window + **/ + maximize(): void; + /** + minimize current window + **/ + minimize(): void; + /** + restore current window, it could be maximized or cascade status + **/ + restore(): void; + /** + close current window + **/ + close(quiet: boolean): void; + /** + hide current window + **/ + hide(): void; + /** + show current window + **/ + show(): void; + /** + change window title + **/ + setTitle(title: string): void; + /** + change iframe url + **/ + setUrl(url: string): void; + /** + change frame content + **/ + setContent(content: string|JQuery|HTMLElement): void; + /** + change footer content + **/ + setFooterContent(content: string|JQuery|HTMLElement): void; + /** + get window title text + **/ + getTitle(): string; + /** + get url string + **/ + getUrl(): string; + /** + get frame html content + **/ + getContent(): string; + /** + get footer html content + **/ + getFooterContent(): string; + /** + get window maximized status + **/ + isMaximized(): boolean; + /** + get window minmized status + **/ + isMinimized(): boolean; + /** + get window selected status + **/ + isSelected(): boolean; + /** + set window icon + **/ + setIcon(iconUrl: string): void; + /** + show window icon + **/ + showIcon(): void; + /** + hide window icon + **/ + hideIcon(): void; + } + + // Static methods + interface Static { + (options: WindowOptions): JQueryWindow.Window; + /** + initialize with customerized static setting attributes + **/ + prepare(options?: StaticOptions): void; + /** + close all created windows + **/ + closeAll(quiet?: boolean): void; + /** + hide all created windows + **/ + hideAll(): void; + /** + show all created windows + **/ + showAll(): void; + /** + return all created windows instance + **/ + getAll(): Array; + /** + get the window instance by passed window id + **/ + getWindow(windowId: string): JQueryWindow.Window; + /** + get the selected window instance + **/ + getSelectedWindow(): JQueryWindow.Window; + } + + // Static options + interface StaticOptions { + /** + the direction of minimized window dock at. the available values are [left, right, top, bottom] + **/ + dock?: string; + /** + the area which the windows will dock at + **/ + dockArea?: JQuery|HTMLElement; + /** + the speed of animations: maximize, minimize, restore, shift, in milliseconds + **/ + animationSpeed?: number; + /** + the narrow dimension of minimized window + **/ + minWinNarrow?: number; + /** + the long dimension of minimized window + **/ + minWinLong?: number; + /** + to handle browser scrollbar when window status changed(maximize, minimize, cascade) + **/ + handleScrollbar?: boolean; + /** + to decide show log in firebug, IE8, chrome console + **/ + showLog?: boolean; + } + + // Instance options + interface WindowOptions { + /** + an icon image url string. if this attribute is given, it will force to replace the original favicon of remote page on window. or you can set it as null to hide icon. + **/ + icon?: string; + /** + the title text of window + **/ + title: string; + /** + the target url of iframe ready to load. + **/ + url?: string; + /** + this attribute only works when url is null. when passing a jquery object or a element, it will clone the original one to append. + **/ + content?: string|JQuery|HTMLElement; + /** + same as content attribute, but it's put on footer panel. + **/ + footerContent?: string|JQuery|HTMLElement; + /** + container extra class + **/ + containerClass?: string; + /** + header extra class + **/ + headerClass?: string; + /** + frame extra class + **/ + frameClass?: string; + /** + footer extra class + **/ + footerClass?: string; + /** + selected header extra class + **/ + selectedHeaderClass?: string; + /** + the x-axis value on screen(or caller element), if -1 means put on screen(or caller element) center + **/ + x?: number; + /** + the y-axis value on screen(or caller element), if -1 means put on screen(or caller element) center + **/ + y?: number; + /** + the css z-index value + **/ + z?: number; + /** + window width + **/ + width?: number; + /** + window height + **/ + height?: number; + /** + the minimum width, if -1 means no checking + **/ + minWidth?: number; + /** + the minimum height, if -1 means no checking + **/ + minHeight?: number; + /** + the maximum width, if -1 means no checking + **/ + maxWidth?: number; + /** + the maximum height, if -1 means no checking + **/ + maxHeight?: number; + /** + to control show modal on background + **/ + showModal?: boolean; + /** + the opacity of modal dialog + **/ + modalOpacity?: number; + /** + to control show footer panel + **/ + showFooter?: boolean; + /** + to control display window as round corner + **/ + showRoundCorner?: boolean; + /** + to control window closable + **/ + closable?: boolean; + /** + to control window minimizable + **/ + minimizable?: boolean; + /** + to control window maximizable + **/ + maximizable?: boolean; + /** + to control window with remote url could be bookmarked + **/ + bookmarkable?: boolean; + /** + to control window draggable + **/ + draggable?: boolean; + /** + to control window resizable + **/ + resizable?: boolean; + /** + to show scroll bar or not + **/ + scrollable?: boolean; + /** + to check window dialog overflow html body or caller element + **/ + checkBoundary?: boolean; + /** + to limit window only can be dragged within browser window. this attribute only works when checkBoundary is true and caller is null. + **/ + withinBrowserWindow?: boolean; + /** + to describe the customized button display and callback function + **/ + custBtns?: Array; + /** + a callback function while container is added into body + **/ + onOpen?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while whole window display routine is finished + **/ + onShow?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while user click close button + **/ + onClose?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while user select the window + **/ + onSelect?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window unselected + **/ + onUnselect?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to drag + **/ + onDrag?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window dragged + **/ + afterDrag?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to resize + **/ + onResize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window resized + **/ + afterResize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to minimize + **/ + onMinimize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window minimized + **/ + afterMinimize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to maximize + **/ + onMaximize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window maximized + **/ + afterMaximize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to cascade + **/ + onCascade?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window cascaded + **/ + afterCascade?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while iframe ready to connect remoting url. this attribute only works while url attribute is given + **/ + onIframeStart?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while iframe load finished. this attribute only works while url attribute is given + **/ + onIframeEnd?: (wnd: JQueryWindow.Window) => void; + /** + if null means no check, or pass a string to show warning message while iframe is going to redirect current top page + **/ + iframeRedirectCheckMsg?: string; + /** + random the new created window position, it only works when options x,y value both are -1 + **/ + createRandomOffset?: { x: number; y: number }; + } + + // Button definition + interface Button { + /** + + **/ + id: string; + /** + + **/ + title?: string; + /** + + **/ + clazz?: string; + /** + + **/ + style?: string; + /** + + **/ + image: string; + /** + + **/ + callback: (btn: JQueryWindow.Button, wnd: JQueryWindow.Window) => void; + } + +} + +// Register with JQuery instance +interface JQuery { + window(options: JQueryWindow.WindowOptions): JQueryWindow.Window; +} + +// Register with JQuery static +interface JQueryStatic { + window: JQueryWindow.Static; +} \ No newline at end of file diff --git a/jsonpath/jsonpath-tests.ts b/jsonpath/jsonpath-tests.ts new file mode 100644 index 000000000..d7fd50868 --- /dev/null +++ b/jsonpath/jsonpath-tests.ts @@ -0,0 +1,55 @@ +/// + +import jp = require('jsonpath'); + +var data: any; + +/** + * jp.query(obj, pathExpression) + * Find elements in obj matching pathExpression. Returns an array of elements that satisfy the provided JSONPath expression, or an empty array if none were matched. + */ +var authors = jp.query(data, '$..author'); + +/** + * jp.paths(obj, pathExpression) + * Find elements in obj matching pathExpression. Returns an array of element paths that satisfy the provided JSONPath expression. Each path is itself an array of keys representing the location within obj of the matching element. + */ +var paths = jp.paths(data, '$..author'); + +/** + * jp.nodes(obj, pathExpression) + * Find elements and their corresponding paths in obj matching pathExpression. Returns an array of node objects where each node has a path containing an array of keys representing the location within obj, and a value pointing to the matched element. + */ +var nodes = jp.nodes(data, '$..author'); + +/** + * jp.value(obj, pathExpression, [newValue]) + * Returns the value of the first element matching pathExpression. If newValue is provided, sets the value of the first matching element and returns the new value. + */ +var value = jp.value(data, '$.store..price'); +jp.value(data, '$.store..price', 12.5); + +/** + * jp.parent(obj, pathExpression) + * Returns the parent of the first matching element. + */ +var parent = jp.parent(data, '$.store..price'); + +/** + * jp.apply(obj, pathExpression, fn) + * Runs the supplied function fn on each matching element, and replaces each matching element with the return value from the function. The function accepts the value of the matching element as its only parameter. Returns matching nodes with their updated values. + */ +var nodes = jp.apply(data, '$..author', (value: string) => { return value.toUpperCase() }); + +/** + * jp.parse(pathExpression) + * Parse the provided JSONPath expression into path components and their associated operations. + */ +var path = jp.parse('$..author'); + +/** + * jp.stringify(path) + * Returns a path expression in string form, given a path. The supplied path may either be a flat array of keys, as returned by jp.nodes for example, or may alternatively be a fully parsed path expression in the form of an array of path components as returned by jp.parse. + */ +var pathExpression = jp.stringify(['$', 'store', 'book', 0, 'author']); + diff --git a/jsonpath/jsonpath.d.ts b/jsonpath/jsonpath.d.ts new file mode 100644 index 000000000..db5322017 --- /dev/null +++ b/jsonpath/jsonpath.d.ts @@ -0,0 +1,21 @@ +// Type definitions for jsonpath 0.1.3 +// Project: https://www.npmjs.org/package/jsonpath +// Definitions by: Hiroki Horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "jsonpath" { + + type PathComponent = string|number; + + export function query(obj: any, pathExpression: string): any[]; + export function paths(obj: any, pathExpression: string): PathComponent[][]; + export function nodes(obj: any, pathExpression: string): { path: PathComponent[]; value: any; }[]; + export function value(obj: any, pathExpression: string): any; + export function value(obj: any, pathExpression: string, newValue: any): any; + export function parent(obj: any, pathExpression: string): any; + export function apply(obj: any, pathExpression: string, fn: (x: any) => any): { path: PathComponent[]; value: any; }[]; + export function parse(pathExpression: string): any[]; + export function stringify(path: PathComponent[]): string; + +} + diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 1708a9d10..a1e92ef71 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1573,6 +1573,26 @@ declare module L { */ getSouthEast(): LatLng; + /** + * Returns the west longitude in degrees of the bounds. + */ + getWest(): number; + + /** + * Returns the east longitude in degrees of the bounds. + */ + getEast(): number; + + /** + * Returns the north latitude in degrees of the bounds. + */ + getNorth(): number; + + /** + * Returns the south latitude in degrees of the bounds. + */ + getSouth(): number; + /** * Returns the center point of the bounds. */ diff --git a/less-middleware/less-middleware-tests.ts b/less-middleware/less-middleware-tests.ts new file mode 100644 index 000000000..0a84203b6 --- /dev/null +++ b/less-middleware/less-middleware-tests.ts @@ -0,0 +1,28 @@ +/// + +import express = require('express'); +import lessMiddleware = require('less-middleware'); +var app = express(); + +app.use(lessMiddleware('public', { + cacheFile: null, + debug: false, + dest: 'dest', + force: false, + once: false, + pathRoot: 'root', + postprocess: { + css: function(css, req) { return css; }, + }, + preprocess: { + less: function(src, req) { return src; }, + path: function(pathname, req) { return pathname; }, + importPaths: function(paths, req) { return paths; } + }, + render: { + compress: 'auto', + yuicompress: false, + paths: ['foo', 'bar'] + }, + storeCss: function(css, req, next) {}, +})); diff --git a/less-middleware/less-middleware.d.ts b/less-middleware/less-middleware.d.ts new file mode 100644 index 000000000..ee0e0069d --- /dev/null +++ b/less-middleware/less-middleware.d.ts @@ -0,0 +1,108 @@ +// Type definitions for less-middleware 2.0.1 +// Project: https://github.com/emberfeather/less.js-middleware +// Definitions by: Federico Bond +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* =================== USAGE =================== + + import lessMiddleware = require('less-middleware'); + app.use(lessMiddleware(source, options)); + + =============================================== */ + +/// + +declare module "less-middleware" { + import express = require('express'); + + /** + * Middleware created to allow processing of Less files for Connect JS framework + * and by extension the Express JS framework + */ + function lessMiddleware(source: string, options?: { + /** + * Show more verbose logging? + */ + debug?: boolean; + + /** + * Destination directory to output the compiled .css files. + */ + dest?: string; + + /** + * Always re-compile less files on each request. + */ + force?: boolean; + + /** + * Only recompile once after each server restart. + * Useful for reducing disk i/o on production. + */ + once?: boolean; + + /** + * Common root of the source and destination. + * It is prepended to both the source and destination before being used. + */ + pathRoot?: string; + + /** + * Object containing functions relevant to preprocessing data. + */ + postprocess?: { + + /** + * Function that modifies the compiled css output before being stored. + */ + css?(css: string, req: express.Request): string; + }; + + /** + * Object containing functions relevant to preprocessing data. + */ + preprocess?: { + + /** + * Function that modifies the raw less output before being parsed and compiled. + */ + less?(css: string, req: express.Request): string; + + /** + * Function that modifies the less pathname before being loaded from the filesystem. + */ + path?(pathname: string, req: express.Request): string; + + /** + * Function that modifies the import paths used by the less parser per request. + */ + importPaths?(paths: string[], req: express.Request): string[]; + }; + + /** + * Options for the less render. + */ + render?: { + + compress?: string; + yuicompress?: boolean; + paths?: string[]; + }; + + /** + * Function that is in charge of storing the css in the filesystem. + */ + storeCss?(pathname: string, css: string, req: express.Request, next: Function): void; + + /** + * Path to a JSON file that will be used to cache less data across server restarts. + * This can greatly speed up initial load time after a server restart - if the less + * files haven't changed and the css files still exist, specifying this option will + * mean that the less files don't need to be recompiled after a server restart. + */ + cacheFile?: string; + + }): express.RequestHandler; + + export = lessMiddleware; +} diff --git a/less/less-tests.ts b/less/less-tests.ts index a984306ee..589250d0b 100644 --- a/less/less-tests.ts +++ b/less/less-tests.ts @@ -2,33 +2,12 @@ import less = require("less"); -declare var __dirname: string; - -less.render('.class { width: (1 + 1) }', (e, css) => console.log(css)); - -var parser: less.Parser = new less.Parser; - -parser.parse('.class { width: (1 + 1) }', function (err, tree) { - if (err) return console.error(err); - tree.toCSS(); +less.render(".class { width: (1 + 1) }").then((output) => { + console.log(output.css); }); -var parser2 = new less.Parser({ - paths: ['.', './lib'], - filename: 'style.less' +less.render("fail").then((output) => { + throw new Error("promise should have been rejected"); +}, (error: Less.RenderError) => { + console.log("rejected as expected on line number " + error.line); }); - -parser2.parse('.class { width: (1 + 1) }', (e, tree) => tree.toCSS({ compress: true })); - -var lessParser = new less.Parser({ - paths: [__dirname], - filename: "out.less" -}); - -lessParser.parse('.class { width: (1 + 1) }', function (err, tree) { - tree.rules.forEach(function (rule) { - if (rule.path) { - console.log(rule.path); - } - }); -}); \ No newline at end of file diff --git a/less/less.d.ts b/less/less.d.ts index 4c096525d..f329dd48e 100644 --- a/less/less.d.ts +++ b/less/less.d.ts @@ -1,556 +1,85 @@ // Type definitions for LESS // Project: http://lesscss.org/ -// Definitions by: AndrewGaspar +// Definitions by: Tom Hasner // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module less { - class LessError { - constructor(e: Error, env); +declare module Less { + // Promise definitions from ../es6-promise/es6-promise.d.ts + interface Thenable { + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + } - type: any; - message: string; + class Promise implements Thenable { + constructor(callback: (resolve : (value?: R | Thenable) => void, reject: (error?: any) => void) => void); + + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise; + + catch(onRejected?: (error: any) => U | Thenable): Promise; + + finally(finallyCallback: () => any): Promise; + } + + interface RootFileInfo { filename: string; - index; - line: number; - callLine: number; - callExtract; - stack; - column; - extract: any[]; + relativeUrls: boolean; + rootpath: string; + currentDirectory: string; + entryPath: string; + rootFilename: string; + } + + class PluginManager { + constructor(less: LessStatic); + } + + interface Plugin { + install: (less: LessStatic, pluginManager: PluginManager) => void; + } + + interface SourceMapOption { + sourceMapURL: string; + sourceMapBasepath: string; + sourceMapRootpath: string; + outputSourceFiles: boolean; + sourceMapFileInline: boolean; } interface Options { - contents?; - rootpath?: string; - files?; - paths?: string[]; - mime?: string; + sourceMap?: SourceMapOption; filename?: string; - optimization?: number; - dumpLineNumbers?: boolean; - strictImports?; - entryPath?: string; - relativeUrls?; - errback? (path: string, paths: string[], callback: Function, env: Options); - frames?; - compress?: boolean; + plugins: Plugin[]; + rootFileInfo?: RootFileInfo; } - export module tree { - export module mixin { // TODO - export class Call { - - } - - export class Definition extends Ruleset { - - } - } - - export module functions { - export function rgb(r: number, g: number, b: number): Color; - export function rgba(r: number, g: number, b: number, a: number): Color; - export function hsl(h: number, s?: number, l?: number): Color; - export function hsla(h: number, s?: number, l?: number, a?: number): Color; - export function hsv(h: number, s: number, v: number): Color; - export function hsva(h: number, s: number, v: number, a: number): Color; - export function hue(color: Color): Dimension; - export function saturation(color: Color): Dimension; - export function lightness(color: Color): Dimension; - export function red(color: Color): Dimension; - export function green(color: Color): Dimension; - export function blue(color: Color): Dimension; - export function alpha(color: Color): Dimension; - export function luma(color: Color): Dimension; - export function saturate(color: Color, amount: IValuableNumber): Color; - export function desaturate(color: Color, amount: IValuableNumber): Color; - export function lighten(color: Color, amount: IValuableNumber): Color; - export function darken(color: Color, amount: IValuableNumber): Color; - export function fadein(color: Color, amount: IValuableNumber): Color; - export function fadeout(color: Color, amount: IValuableNumber): Color; - export function fade(color: Color, amount: IValuableNumber): Color; - export function spin(color: Color, amount: IValuableNumber): Color; - export function mix(color1: Color, color2: Color, weight: Dimension): Color; - export function greyscale(color: Color): Color; - export function contrast(color: Color, dark?: Color, light?: Color, threshold?: IValuableNumber): Color; - export function contrast(color: Color, dark?: Color, light?: Color, threshold?: number): Color; - export function e(str: string): Anonymous; - export function e(str: JavaScript): Anonymous; - export function escape(str: IValuableString): Anonymous; - export function unit(val: IValuableNumber, unit?: ICSSable): Dimension; - export function round(n: Dimension, f?: IValuableNumber): Dimension; - export function round(n: number, f?: IValuableNumber): number; - export function ceil(n: number): number; - export function ceil(n: Dimension): Dimension; - export function floor(n: number): number; - export function floor(n: Dimension): Dimension; - export function argb(color: Color): Anonymous; - export function percentage(n: IValuableNumber): Dimension; - export function color(n: Quoted): Color; - export function iscolor(n): Keyword; - export function isnumber(n): Keyword; - export function isstring(n): Keyword; - export function iskeyword(n): Keyword; - export function isurl(n): Keyword; - export function ispixel(n): Keyword; - export function ispercentage(n): Keyword; - export function isem(n): Keyword; - export function multiply(color1: Color, color2: Color): Color; - export function screen(color1: Color, color2: Color): Color; - export function overlay(color1: Color, color2: Color): Color; - export function softlight(color1: Color, color2: Color): Color; - export function hardlight(color1: Color, color2: Color): Color; - export function difference(color1: Color, color2: Color): Color; - export function exclusion(color1: Color, color2: Color): Color; - export function average(color1: Color, color2: Color): Color; - export function negation(color1: Color, color2: Color): Color; - export function tint(color: Color, amount: Dimension): Color; - export function shade(color: Color, amount: Dimension): Color; - } - - export var colors: any; // Could be module - got lazy - - interface HasDebugInfo { - debugInfo: DebugInfo; - } - - interface DebugInfo { - lineNumber; - fileName: string; - } - - interface HSL { - h: number; - s: number; - l: number; - a: number; - } - - interface DebugInfoFunction { - (env: Options, ctx: HasDebugInfo): string; - asComment(ctx: HasDebugInfo): string; - asMediaQuery(ctx: HasDebugInfo): string; - } - - interface RuleContainer { - [name: string]: Rule; - } - - interface ICSSable { - toCSS(ctx?, env?: Options): string; - } - - interface IEvalable { - eval(env: Options): IEvalable; - } - - interface IInjectable extends ICSSable, IEvalable {} - - interface IOperable { - operate(op: Operation, other: IOperable): IOperable; - } - - interface IComparable { - compare(x: IComparable): number; - } - - interface IColorable { - toColor(): Color; - } - - interface IValuableNumber { - value: number; - } - - interface IValuableString { - value: string; - } - - export class Color implements IOperable, IInjectable, IComparable { - constructor(rgb: string, a: number); - constructor(rgb: number[], a: number); - - rgb: number[]; - alpha: number; - eval(): Color; - toCSS(): string; - operate(op: Operation, other: Color): Color; - operate(op: Operation, other: IColorable): Color; - toHSL(): HSL; - toARGB(): string; - compare(x: Color): number; - } - - export class Directive implements IInjectable { - constructor(name, value); - - name; - value: ICSSable; - ruleset: Ruleset; - - toCSS(ctx?, env?: Options): string; - eval(env: Options): Directive; - - variable(name); - find(); - rulesets(); - } - - export class Operation implements IEvalable { - constructor(op, operands); - - op: string; - operands: IEvalable; - - eval(env: Options): IEvalable; - - operate(op: string, a: number, b: number): number; - } - - export class Dimension implements IColorable, IInjectable, IOperable, IComparable { - constructor(value: number, unit: string); - - value: number; - unit: string; - - eval(): Dimension; - toColor(): Color; - toCSS(): string; - operate(op: Operation, other: Dimension): Dimension; - compare(other: IComparable): number; - } - - export class Keyword implements IInjectable, IComparable { - constructor(value: string); - - value: string; - - eval(): Keyword; - toCSS(): string; - compare(other: IComparable): number; - - static True: Keyword; - static False: Keyword; - } - - export class Variable implements IEvalable { - constructor(name: string, index, file: string); - - name: string; - index; - file: string; - - eval(env: Options): IEvalable; - } - - export class AbstractRuleset implements IEvalable { - selectors: Selector[]; - rules: any[]; - strictImports; - - eval(env: Options): Ruleset; - evalImports(env: Options): void; - makeImportant(): Ruleset; - matchArgs(args: any): boolean; - resetCache(): void; - variables(): RuleContainer; - variable(): Rule; - rulesets(): Ruleset[]; - find(selector: Selector, self: Rule): Rule[]; - joinSelectors(paths: string[], context: any[][], selectors: Selector[]): void; - joinSelector(paths: string[], context: any[][], selector: Selector): void; - mergeElementsOnToSelectors(elements: Element[], selectors: Selector[]): void; - } - - export class Ruleset extends AbstractRuleset { - constructor(selectors: Selector[], rules: Rule[], strictImports); - - toCSS(context?: any[][], env?: Options): string; - } - - export class Element implements IInjectable { - constructor(combinator: Combinator, value, index); - - combinator: Combinator; - value; - index; - - eval(env: Options): Element; - toCSS(env?: Options): string; - } - - export class Combinator implements ICSSable { - constructor(value: string); - - value: string; - - toCSS(env?: Options): string; - } - - export class Selector implements IInjectable { - constructor(elements: Element[]); - - match(other: Selector): boolean; - eval(env: Options): Selector; - toCSS(env?: Options): string; - } - - export class Quoted implements IInjectable, IComparable { - constructor(str: string, content: string, escaped: boolean, i); - - escaped: boolean; - value: string; - quote: string; - index; - - toCSS(): string; - eval(env: Options): Quoted; - compare(x: IComparable): number; - } - - export class Expression implements IInjectable { - constructor(value: IEvalable[]); - - value: IEvalable[]; - - eval(env: Options): IEvalable; - toCSS(env?: Options): string; - } - - export class Rule implements IInjectable { - constructor(name: string, value?: Value, important?: string, index?, inline?: boolean); - - name: string; - value: Value; - important: string; - index; - inline: boolean; - - toCSS(env?: Options): string; - eval(context): Rule; - - makeImportant(): Rule; - } - - export class Shorthand implements IInjectable { - constructor(a: ICSSable, b: ICSSable); - - a: ICSSable; - b: ICSSable; - - toCSS(env?: Options): string; - eval(): Shorthand; - } - - export class Call implements IInjectable { - constructor(name: string, args: IEvalable[], index, filename: string); - - name: string; - args: IEvalable[]; - index; - filename: string; - - eval(env: Options): IEvalable; - toCSS(env?: Options): string; - } - - export class URL implements IInjectable { - constructor(val, rootpath: string); - - value; - rootpath: string; - - toCSS(): string; - eval(ctx): URL; - } - - export class Alpha implements IInjectable { - constructor(val); - - value; - - toCSS(): string; - eval(env: Options): Alpha; - } - - export class Import implements IInjectable { - constructor(path, imports, features: ICSSable, once: boolean, index, rootpath); - - once: boolean; - index; - features: ICSSable; - rootpath; - path: string; - css: boolean; - - toCSS(env?: Options): string; - eval(env: Options): IEvalable; - } - - export class Comment implements IInjectable { - constructor(value: string, silent); - - value: string; - silent: boolean; - - toCSS(env?: Options): string; - eval(): Comment; - } - - export class Anonymous implements IInjectable, IComparable { - constructor(value: string); - - value: string; - - toCSS(): string; - eval(): Anonymous; - compare(x): number; - } - - export class Value implements IInjectable { - constructor(value: IEvalable[]); - - value: IEvalable[]; - is: string; - - eval(env: Options): IEvalable; - toCSS(env?: Options): string; - } - - export class JavaScript implements IEvalable { - constructor(expression: string, index, escaped: boolean); - - escaped: boolean; - expression: string; - index; - - eval(env: Options): IEvalable; - } - - export class Assignment implements IInjectable { - constructor(key: string, val); - constructor(key: string, val: ICSSable); - constructor(key: string, val: IEvalable); - - key: string; - value; - - toCSS(): string; - eval(env: Options): Assignment; - } - - export class Condition { - constructor(op: string, l, r, i, negate: boolean); - - op: string; - lvalue; - rvalue; - index; - negate: boolean; - - eval(env: Options): boolean; - } - - export class Paren implements IInjectable { - constructor(node: IInjectable); - value: IInjectable; - - toCSS(env?: Options): string; - eval(env: Options): Paren; - } - - export class Media implements IInjectable { - constructor(value, features); - - selectors: Selector[]; - features: Value; - ruleset: Ruleset; - - toCSS(ctx?, env?: Options): string; - eval(env: Options): IEvalable; - - variable(name): Rule; - rulesets(): Ruleset[]; - find(selector: Selector, self: Rule): Rule[]; - - emptySelectors(): Selector[]; - evalTop(env: Options): IEvalable; - evalNested(env: Options): Ruleset; - permute(arr: any[]): any[]; - bubbleSelectors(selectors: Selector[]): void; - } - - export class Ratio implements IInjectable { - constructor(value: string); - - value: string; - - toCSS(env?: Options): string; - eval(): Ratio; - } - - export class UnicodeDescriptor implements IInjectable { - constructor(value: string); - - value: string; - - toCSS(env?: Options): string; - eval(): UnicodeDescriptor; - } - - export class Attribute implements IInjectable { - constructor(value: string); - - value: string; - - toCSS(env?: Options): string; - genCSS(env: Options, output): string; - eval(): Attribute; - } - - export var debugInfo: DebugInfoFunction; - export function find(obj: any[], fun: Function): any; - export function jsify(obj: any): string; - export function operate(op: string, a: number, b: number): number; - - export var True: Keyword; - export var False: Keyword; + interface RenderError { + column: number; + extract: string[]; + filename: string; + index: number; + line: number; + message: string; + type: string; } - class ParserNode extends tree.AbstractRuleset { - toCSS(): string; - toCSS(options: { compress: boolean; }, variables?): string; + interface RenderOutput { + css: string; + map: string; + imports: string[]; } +} - export class Parser { - constructor(env?: Options); +interface LessStatic { + render(input: string, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; + render(input: string, options: Less.Options, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; - imports: { - paths: string[]; - queue: string[]; - files; - contents; - mime: string; - error; - push(path: string, callback: (e, root, imported) => void); - }; // TODO + render(input: string): Less.Promise; + render(input: string, options: Less.Options): Less.Promise; - parse: (str: string, callback: (error: LessError, root: ParserNode) => void ) => void; - - parsers: { // Major TODO - }; - } - - export function render(input: string, callback: (e, css: string) => void): void; - export function render(input: string, options: Options, - callback: (e, css: string) => void): void; - - export function formatError(ctx, options: { color: boolean; }): string; - export function writeError(ctx, options: { color: boolean; }): void; - - export var version: number[]; + version: number[]; } declare module "less" { - export = less; + export = less; } + +declare var less: LessStatic; diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 46c11ebf6..10900315f 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -139,6 +139,15 @@ result = <_.Dictionary>_(<{ [index: string]: string; }>{ 'key1': 'test1' // /************* // * Arrays * // *************/ +result = _.chunk([1, '2', '3', false]); +result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(); +result = _.chunk([1, '2', '3', false], 2); +result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(2); +result = _.chunk([1, 2, 3, 4]); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(); +result = _.chunk([1, 2, 3, 4], 2); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(2); + result = _.compact([0, 1, false, 2, '', 3]); result = <_.LoDashArrayWrapper>_([0, 1, false, 2, '', 3]).compact(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 426162e2e..01238b769 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -17,7 +17,7 @@ declare module _ { * explicitly included in the build. * * The chainable wrapper functions are: - * after, assign, bind, bindAll, bindKey, chain, compact, compose, concat, countBy, + * after, assign, bind, bindAll, bindKey, chain, chunk, compact, compose, concat, countBy, * createCallback, curry, debounce, defaults, defer, delay, difference, filter, flatten, * forEach, forEachRight, forIn, forInRight, forOwn, forOwnRight, functions, groupBy, * indexBy, initial, intersection, invert, invoke, keys, map, max, memoize, merge, min, @@ -254,6 +254,30 @@ declare module _ { /********* * Arrays * **********/ + + //_.chunk + interface LoDashStatic { + /** + * Creates an array of elements split into groups the length of size. If collection can’t be + * split evenly, the final chunk will be the remaining elements. + * @param array The array to process. + * @param size The length of each chunk. + * @return Returns the new array containing chunks. + **/ + chunk(array: Array, size?: number): T[][]; + + /** + * @see _.chunk + **/ + chunk(array: List, size?: number): T[][]; + } + + interface LoDashArrayWrapper { + /** + * @see _.chunk + **/ + chunk(size?: number): LoDashArrayWrapper; + } //_.compact interface LoDashStatic { @@ -5745,6 +5769,18 @@ declare module _ { **/ isEmpty(value: any): boolean; } + + //_.isError + interface LoDashStatic { + /** + * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, + * or URIError object. + * @param value The value to check. + * @return True if value is an error object, else false. + */ + isError(value: any): boolean; + } + //_.isEqual interface LoDashStatic { diff --git a/lory.js/lory.js-tests.ts b/lory.js/lory.js-tests.ts new file mode 100644 index 000000000..4247dceca --- /dev/null +++ b/lory.js/lory.js-tests.ts @@ -0,0 +1,62 @@ +/// + +(function() { + var elm = document.querySelector('.js-foo'); + var elm2 = document.querySelector('.js-bar'); + var elm3 = document.querySelector('.js-baz'); + var elm4 = document.querySelector('.js-foobar'); + + ////////////////////////////////////////////////// + // Init + ////////////////////////////////////////////////// + + lory(elm); + + // with options + lory(elm2, { + slidesToScroll: 1, + slideSpeed: 300, + rewindSpeed: 600, + snapBackSpeed: 200, + ease: 'ease', + rewind: true, + infinite: false + }); + + // with callbacks + lory(elm3, { + beforeInit: () => { }, + afterInit: () => { }, + beforePrev: () => { return 1; }, + beforeNext: () => { return false; }, + beforeTouch: () => { return ''; }, + beforeResize: () => { } + }); + + // with options & callbacks + lory(elm4, { + slidesToScroll: 1, + slideSpeed: 300, + rewindSpeed: 600, + snapBackSpeed: 200, + ease: 'ease', + rewind: true, + infinite: 4, + beforeInit: () => { return function() { console.log('foo') }; }, + afterInit: () => { return [0, 1]; }, + beforePrev: () => { }, + beforeNext: () => { }, + beforeTouch: () => { }, + beforeResize: () => { return {}; } + }); + + ////////////////////////////////////////////////// + // Public API + ////////////////////////////////////////////////// + + lory.setup(); + lory.prev(); + lory.next(); + lory.reset(); + lory.slideTo(1); +}()); diff --git a/lory.js/lory.js.d.ts b/lory.js/lory.js.d.ts new file mode 100644 index 000000000..4dc7860d8 --- /dev/null +++ b/lory.js/lory.js.d.ts @@ -0,0 +1,110 @@ +// Type definitions for lory 0.4.3 +// Project: https://github.com/meandmax/lory/ +// Definitions by: kubosho +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var lory: LoryStatic; + +interface LoryStatic { + (element: Element, options?: LoryOptions): LoryStatic; + + /** + * slides to the previous slide. + */ + prev(): void; + + /** + * slides to the next slide. + */ + next(): void; + + /** + * slides to the index given as an argument. + */ + slideTo(index: number): void; + + /** + * binds eventlisteners, merging default and user options, setup the slides based on DOM (called once during initialisation). Call setup if DOM or user options have changed or eventlisteners needs to be rebinded. + */ + setup(): void; + + /** + * sets the slider back to the starting position and resets the current index (called on resize event). + */ + reset(): void; +} + +interface LoryOptions { + ////////////////////////////////////////////////// + // Options + ////////////////////////////////////////////////// + + /** + * slides scrolled at once (default: 1). + */ + slidesToScroll?: number; + + /** + * time in milliseconds for the animation of a valid slide attempt (default: 300). + */ + slideSpeed?: number; + + /** + * time in milliseconds for the animation of the rewind after the last slide (default: 600). + */ + rewindSpeed?: number; + + /** + * time for the snapBack of the slider if the slide attempt was not valid (default: 200). + */ + snapBackSpeed?: number; + + /** + * cubic bezier easing functions: http://easings.net/de (default: 'cubic-bezier(0.455, 0.03, 0.515, 0.955)'). + */ + ease?: string; + + /** + * if slider reached the last slide, with next click the slider goes back to the startindex (default: false). + */ + rewind?: boolean; + + /** + * like carousel, works with multiple slides (default: false). (do not combine with rewind) + */ + infinite?: boolean | number; + + ////////////////////////////////////////////////// + // Callbacks + ////////////////////////////////////////////////// + + /** + * executed before initialisation (first in setup function) + */ + beforeInit?: () => T; + + /** + * executed after initialisation (end of setup function) + */ + afterInit?: () => T; + + /** + * executed on click of prev controls (prev function) + */ + beforePrev?: () => T; + + /** + * executed on click of next controls (next function) + */ + beforeNext?: () => T; + + /** + * executed on touch attempt (touchstart) + */ + beforeTouch?: () => T; + + /** + * executed on every resize event + */ + beforeResize?: () => T; +} diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index ee528b666..2b9b25635 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -38,7 +38,7 @@ declare module Backbone { include(value: any): boolean; initial(): View; initial(n: number): View[]; - invoke(methodName: string, arguments?: any[]): any; + invoke(methodName: string, args?: any[]): any; isEmpty(object: any): boolean; last(): View; last(n: number): View[]; @@ -533,7 +533,7 @@ declare module Marionette { * Calls the method named by methodName on each value in the collection. Any extra * arguments passed to invoke will be forwarded on to the method invocation. */ - invoke(methodName: string, arguments?: any[]): any; + invoke(methodName: string, args?: any[]): any; /** * Returns true if the RegionManager contains no regions. diff --git a/meteor/README.md b/meteor/README.md index ae8178f2c..8f93e1816 100644 --- a/meteor/README.md +++ b/meteor/README.md @@ -1,6 +1,6 @@ # Meteor Type Definitions -These are the definitions for version 1.0.3.1 of Meteor. +These are the definitions for version 1.1.0.1 of Meteor. Although these definitions can be downloaded separately for use, the recommended way to use these definitions in a Meteor application is by installing the [typescript-libs](https://atmospherejs.com/meteortypescript/typescript-libs) Meteor smart package from atmosphere. The smart package contains TypeScript @@ -16,25 +16,21 @@ to generate the official [Meteor docs] (http://docs.meteor.com/). ## Usage -1. If you are using the smart package, add a symbolic link to the definitions from within some directory within your project (e.g. ".typescript" or "lib"). The -definitions can be found somewhere deep within `/.meteor/...`. The following will probably work: +1. Add a symbolic link to the definitions from within some directory within your project (e.g. ".typescript" or "lib"). The definitions can be found somewhere +deep within `/.meteor/...`. The following will probably work: $ ln -s ../.meteor/local/build/programs/server/assets/packages/meteortypescript_typescript-libs/definitions package_defs - If the definitions can't be found within the .meteor directory, you will have to manually pull down the definitions from github and add them to your project: - If you are just using the *meteor.d.ts* file from this source, you can just add the file to any directory in your project (e.g. ".typescript" or "lib"). - 2. Install the [Typescript compiler for Meteor](https://github.com/meteor-typescript/meteor-typescript-compiler) or an [IDE which can transpile TypeScript to JavaScript](#transpiling-typescript). 3. From the typescript files, add references. Reference the definition files with a single line: /// (substitute path in your project) - Or you can reference definition files individually: - + /// (substitue path in your project) /// /// @@ -46,26 +42,28 @@ definitions can be found somewhere deep within `/.meteor/...`. ### References -Try to stay away from referencing *file.ts*, rather generate a *file.d.ts* using `tsc --reference file.ts`, and reference it in your file. Compilation will -be much faster and code cleaner - it's always better to split definition from implemention. +Meteor code can run on the client and the server, for this reason you should try to stay away from referencing *file.ts* directly: you may get unexpected results. +Rather generate a *file.d.ts* using `tsc --reference file.ts`, and reference it in your file. + +Compilation will be much faster and code cleaner - it's always better to split definition from implementation anyways. ### Templates -When specifying template *helpers*, *events*, and functions for *created*, *rendered*, and *destroyed*, you will need to use a "bracket notation" instead of the "dot notation": +With the exception of the **body** and **head** templates, Meteor's Template dot notation cannot be used (ie. *Template.mytemplate*). Thanks to Typescript static typing checks, you will need to used the *bracket notation* to access the Template. - Template['myTemplateName']['helpers']({ + + Template['myTemplateName'].helpers({ foo: function () { return Session.get("foo"); } }); - Template['myTemplateName']['rendered'] = function ( ) { ... } + Template['myTemplateName'].rendered = function ( ) { ... } + -This is because TypeScript enforces typing and it will throw an error saying "myTemplateName" does not exist when using the dot notation. +### Form fields -### Accessing a Form field - -Trying to read a form field value? use `(evt.target).value`. +Form fields typically need to be casted to . For instance to read a form field value, use `(evt.target).value`. ### Global variables @@ -77,7 +75,7 @@ Preface any global variable declarations with a TypeScript "declare var" stateme ### Collections -The majority of extra work required to use TypeScript with Meteor is creating and maintaining the collection interfaces. However, doing so also provides the +The majority of extra work required to use TypeScript with Meteor is creating and maintaining the collection interfaces. However, doing so also provides the additional benefit of succinctly documenting collection schema definitions (that are actually enforced). To define collections, you will need to create an interface representing the collection and then declare a Collection type variable with that interface type (as a generic): @@ -113,7 +111,7 @@ for all of you custom definitions. e.g. contents of ".typescript/custom_defs/cu /// /// /// - + ## Transpiling TypeScript @@ -132,4 +130,4 @@ Then, within WebStorm, go to Preferences -> File Watchers -> "+" symbol and add Last option, is to compile code from the command line. With node and the typescript compiler installed: - $ tsc *.ts \ No newline at end of file + $ tsc *.ts diff --git a/meteor/meteor-tests.ts b/meteor/meteor-tests.ts index e4c5b9066..ec2ad3b81 100644 --- a/meteor/meteor-tests.ts +++ b/meteor/meteor-tests.ts @@ -8,21 +8,15 @@ /*********************************** Begin setup for tests ******************************/ - -// A developer must declare a var Template like this in a separate file to use this TypeScript type definition file -//interface ITemplate { -// adminDashboard: Meteor.Template; -// chat: Meteor.Template; -//} -//declare var Template: ITemplate; - var Rooms = new Mongo.Collection('rooms'); var Messages = new Mongo.Collection('messages'); -var Monkeys = new Mongo.Collection('monkeys'); -var x = new Mongo.Collection('x'); -var y = new Mongo.Collection('y'); - -var check = function(str1, str2) {}; +interface MonkeyDAO { + _id: string; + name: string; +} +var Monkeys = new Mongo.Collection('monkeys'); +//var x = new Mongo.Collection('x'); +//var y = new Mongo.Collection('y'); /********************************** End setup for tests *********************************/ @@ -98,8 +92,8 @@ Tracker.autorun(function () { }); console.log("Current room has " + - Counts.find(Session.get("roomId")).count + - " messages."); +Counts.find(Session.get("roomId")).count + +" messages."); /** * From Publish and Subscribe, Meteor.subscribe section @@ -124,7 +118,7 @@ Meteor.methods({ var you_want_to_throw_an_error = true; if (you_want_to_throw_an_error) - throw new Meteor.Error("404", "Can't find my pants"); + throw new Meteor.Error("404", "Can't find my pants"); return "some return value"; }, @@ -146,15 +140,15 @@ var result = Meteor.call('foo', 1, 2); // DA: I added the "var" keyword in there interface ChatroomsDAO { - _id?: string; + _id?: string; } interface MessagesDAO { - _id?: string; + _id?: string; } var Chatrooms = new Mongo.Collection("chatrooms"); Messages = new Mongo.Collection("messages"); -var myMessages = Messages.find({userId: Session.get('myUserId')}).fetch(); +var myMessages = Messages.find({userId: Session.get('myUserId')}).fetch(); Messages.insert({text: "Hello, world!"}); @@ -171,10 +165,10 @@ Posts.insert({title: "Hello world", body: "First post"}); * since there is already a Collection constructor with a different signature * var Scratchpad = new Mongo.Collection; -for (var i = 0; i < 10; i++) - Scratchpad.insert({number: i * 2}); -assert(Scratchpad.find({number: {$lt: 9}}).count() === 5); -**/ + for (var i = 0; i < 10; i++) + Scratchpad.insert({number: i * 2}); + assert(Scratchpad.find({number: {$lt: 9}}).count() === 5); + **/ var Animal = function (doc) { // _.extend(this, doc); @@ -185,11 +179,16 @@ Animal.prototype = { makeNoise: function () { console.log(this.sound); } +}; + + +interface AnimalDAO { + _id: string; + makeNoise: () => void; } - // Define a Collection that uses Animal as its document -var Animals = new Mongo.Collection("Animals", { +var Animals = new Mongo.Collection("Animals", { transform: function (doc) { return new Animal(doc); } }); @@ -225,8 +224,8 @@ Template['adminDashboard'].events({ Meteor.methods({ declareWinners: function () { Players.update({score: {$gt: 10}}, - {$addToSet: {badges: "Winner"}}, - {multi: true}); + {$addToSet: {badges: "Winner"}}, + {multi: true}); } }); @@ -348,7 +347,7 @@ Session.equals("key", value); */ Meteor.publish("userData", function () { return Meteor.users.find({_id: this.userId}, - {fields: {'other': 1, 'things': 1}}); + {fields: {'other': 1, 'things': 1}}); }); Meteor.users.deny({update: function () { return true; }}); @@ -412,8 +411,8 @@ Accounts.emailTemplates.enrollAccount.subject = function (user) { }; Accounts.emailTemplates.enrollAccount.text = function (user, url) { return "You have been selected to participate in building a better future!" - + " To activate your account, simply click the link below:\n\n" - + url; + + " To activate your account, simply click the link below:\n\n" + + url; }; /** @@ -424,6 +423,36 @@ Template['adminDashboard'].helpers({ return Session.get("foo"); } }); +Template['newTemplate'].helpers({ + helperName: function () { + } +}); + +Template['newTemplate'].created = function () { + +}; + +Template['newTemplate'].rendered = function () { + +}; + +Template['newTemplate'].destroyed = function () { + +}; + +Template['newTemplate'].events({ + 'click .something': function (event) { + } +}); + +Template.registerHelper('testHelper', function() { + return 'tester'; +}); + +var instance = Template.instance(); +var data = Template.currentData(); +var data = Template.parentData(1); +var body = Template.body; /** * From Match section @@ -481,10 +510,9 @@ Tracker.autorun(function (c) { * From Deps, Deps.Computation */ if (Tracker.active) { - Tracker.onInvalidate(function () { - x.destroy(); - y.finalize(); - }); + Tracker.onInvalidate(function () { + console.log('invalidated'); + }); } /** @@ -494,15 +522,15 @@ var weather = "sunny"; var weatherDep = new Tracker.Dependency; var getWeather = function () { - weatherDep.depend(); - return weather; + weatherDep.depend(); + return weather; }; var setWeather = function (w) { - weather = w; - // (could add logic here to only call changed() - // if the new value is different from the old) - weatherDep.changed(); + weather = w; + // (could add logic here to only call changed() + // if the new value is different from the old) + weatherDep.changed(); }; /** @@ -512,7 +540,7 @@ Meteor.methods({checkTwitter: function (userId) { check(userId, String); this.unblock(); var result = HTTP.call("GET", "http://api.twitter.com/xyz", - {params: {user: userId}}); + {params: {user: userId}}); if (result.statusCode === 200) return true return false; @@ -520,12 +548,12 @@ Meteor.methods({checkTwitter: function (userId) { HTTP.call("POST", "http://api.twitter.com/xyz", - {data: {some: "json", stuff: 1}}, - function (error, result) { - if (result.statusCode === 200) { - Session.set("twizzled", true); - } - }); + {data: {some: "json", stuff: 1}}, + function (error, result) { + if (result.statusCode === 200) { + Session.set("twizzled", true); + } + }); /** * From Email, Email.send section @@ -542,9 +570,9 @@ Meteor.methods({ // In your client code: asynchronously send an email Meteor.call('sendEmail', - 'alice@example.com', - 'Hello from Meteor!', - 'This is a test of Email.send.'); + 'alice@example.com', + 'Hello from Meteor!', + 'This is a test of Email.send.'); var testTemplate = new Blaze.Template(); var testView = new Blaze.View(); @@ -562,8 +590,8 @@ Blaze.toHTMLWithData(testTemplate, function() {}); Blaze.toHTMLWithData(testView, {test: 1}); Blaze.toHTMLWithData(testView, function() {}); -var reactiveVar1 = new ReactiveVar('test value'); -var reactiveVar2 = new ReactiveVar('test value', function(oldVal) { return true; }); +var reactiveVar1 = new ReactiveVar('test value'); +var reactiveVar2 = new ReactiveVar('test value', function(oldVal) { return true; }); var varValue: string = reactiveVar1.get(); reactiveVar1.set('new value'); \ No newline at end of file diff --git a/meteor/meteor.d.ts b/meteor/meteor.d.ts index e64547096..4118fbe06 100644 --- a/meteor/meteor.d.ts +++ b/meteor/meteor.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Meteor 1.0.3.1 +// Type definitions for Meteor 1.1.0.1 // Project: http://www.meteor.com/ // Definitions by: Dave Allen // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,344 +7,419 @@ * These are the modules and interfaces that can't be automatically generated from the Meteor data.js file */ -interface EJSON extends JSON {} -interface TemplateStatic { - new(): Template; - [templateName: string]: Meteor.TemplatePage; +interface EJSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSON.CustomType; } +interface JSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; +} +interface EJSON extends EJSONable {} declare module Match { - var Any; - var String; - var Integer; - var Boolean; - var undefined; - //function null(); // not allowed in TypeScript - var Object; - function Optional(pattern):boolean; - function ObjectIncluding(dico):boolean; - function OneOf(...patterns); - function Where(condition); + var Any; + var String; + var Integer; + var Boolean; + var undefined; + //function null(); // not allowed in TypeScript + var Object; + function Optional(pattern):boolean; + function ObjectIncluding(dico):boolean; + function OneOf(...patterns); + function Where(condition); } declare module Meteor { - //interface EJSONObject extends Object {} + /** Start definitions for Template **/ + interface Event { + type:string; + target:HTMLElement; + currentTarget:HTMLElement; + which: number; + stopPropagation():void; + stopImmediatePropagation():void; + preventDefault():void; + isPropagationStopped():boolean; + isImmediatePropagationStopped():boolean; + isDefaultPrevented():boolean; + } - /** Start definitions for Template **/ - // DA: "Template" needs to support these functions: - // Template..rendered - // Template..created - // Template..destroyed - // Template..helpers - // Template..events - // and - // Template.currentData - // Template.parentData, etc. + interface EventHandlerFunction extends Function { + (event?:Meteor.Event):void; + } - interface Event { - type:string; - target:HTMLElement; - currentTarget:HTMLElement; - which: number; - stopPropagation():void; - stopImmediatePropagation():void; - preventDefault():void; - isPropagationStopped():boolean; - isImmediatePropagationStopped():boolean; - isDefaultPrevented():boolean; - } + interface EventMap { + [id:string]:Meteor.EventHandlerFunction; + } + /** End definitions for Template **/ - interface EventHandlerFunction extends Function { - (event?:Meteor.Event):any; - } + interface LoginWithExternalServiceOptions { + requestPermissions?: string[]; + requestOfflineToken?: Boolean; + forceApprovalPrompt?: Boolean; + userEmail?: string; + loginStyle?: string; + } - interface EventMap { - [id:string]:Meteor.EventHandlerFunction; - } + function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - interface TemplatePage { - rendered: Function; - created: Function; - destroyed: Function; - events(eventMap:Meteor.EventMap): void; - helpers(helpers:{[id:string]: any}): void; - } - /** End definitions for Template **/ + interface UserEmail { + address:string; + verified:boolean; + } - interface LoginWithExternalServiceOptions { - requestPermissions?: string[]; - requestOfflineToken?: Boolean; - forceApprovalPrompt?: Boolean; - userEmail?: string; - loginStyle?: string; - } + interface User { + _id?:string; + username?:string; + emails?:Meteor.UserEmail[]; + createdAt?: number; + profile?: any; + services?: any; + } - function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + interface SubscriptionHandle { + stop(): void; + ready(): boolean; + } - interface UserEmail { - address:string; - verified:boolean; - } + interface Tinytest { + add(name:string, func:Function); + addAsync(name:string, func:Function); + } - interface User { - _id?:string; - username?:string; - emails?:Meteor.UserEmail[]; - createdAt?: number; - profile?: any; - services?: any; - } + enum StatusEnum { + connected, + connecting, + failed, + waiting, + offline + } - interface SubscriptionHandle { - stop(): void; - ready(): boolean; - } + interface LiveQueryHandle { + stop(): void; + } - interface Tinytest { - add(name:string, func:Function); - addAsync(name:string, func:Function); - } + interface EmailFields { + subject?: Function; + text?: Function; + } - enum StatusEnum { - connected, - connecting, - failed, - waiting, - offline - } + interface EmailTemplates { + from: string; + siteName: string; + resetPassword: Meteor.EmailFields; + enrollAccount: Meteor.EmailFields; + verifyEmail: Meteor.EmailFields; + } - interface LiveQueryHandle { - stop(): void; - } + interface Error { + error: number; + reason?: string; + details?: string; + } - interface EmailFields { - subject?: Function; - text?: Function; - } - - interface EmailTemplates { - from: string; - siteName: string; - resetPassword: Meteor.EmailFields; - enrollAccount: Meteor.EmailFields; - verifyEmail: Meteor.EmailFields; - } - - interface Error { - error: number; - reason?: string; - details?: string; - } - - interface Connection { - id: string; - close: Function; - onClose: Function; - clientAddress: string; - httpHeaders: Object; - } + interface Connection { + id: string; + close: Function; + onClose: Function; + clientAddress: string; + httpHeaders: Object; + } } declare module Mongo { - interface Selector extends Object {} - interface Modifier {} - interface SortSpecifier {} - interface FieldSpecifier { - [id: string]: Number; - } - enum IdGenerationEnum { - STRING, - MONGO - } - interface AllowDenyOptions { - insert?: (userId:string, doc) => boolean; - update?: (userId, doc, fieldNames, modifier) => boolean; - remove?: (userId, doc) => boolean; - fetch?: string[]; - transform?: Function; - } + interface Selector extends Object {} + interface Modifier {} + interface SortSpecifier {} + interface FieldSpecifier { + [id: string]: Number; + } + enum IdGenerationEnum { + STRING, + MONGO + } + interface AllowDenyOptions { + insert?: (userId:string, doc) => boolean; + update?: (userId, doc, fieldNames, modifier) => boolean; + remove?: (userId, doc) => boolean; + fetch?: string[]; + transform?: Function; + } } declare module HTTP { - interface HTTPRequest { - content?:string; - data?:any; - query?:string; - params?:{[id:string]:string}; - auth?:string; - headers?:{[id:string]:string}; - timeout?:number; - followRedirects?:boolean; - } - interface HTTPResponse { - statusCode:number; - content:string; - // response is not always json - data:any; - headers:{[id:string]:string}; - } + interface HTTPRequest { + content?:string; + data?:any; + query?:string; + params?:{[id:string]:string}; + auth?:string; + headers?:{[id:string]:string}; + timeout?:number; + followRedirects?:boolean; + } + + interface HTTPResponse { + statusCode?:number; + headers?:{[id:string]: string}; + content?:string; + data?:any; + } + + function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?:Function):HTTP.HTTPResponse; + function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + } declare module Email { - interface EmailMessage { - from: string; - to: any; // string or string[] - cc?: any; // string or string[] - bcc?: any; // string or string[] - replyTo?: any; // string or string[] - subject: string; - text?: string; - html?: string; - headers?: {[id: string]: string}; - } + interface EmailMessage { + from: string; + to: any; // string or string[] + cc?: any; // string or string[] + bcc?: any; // string or string[] + replyTo?: any; // string or string[] + subject: string; + text?: string; + html?: string; + headers?: {[id: string]: string}; + } } declare module DDP { - interface DDPStatic { - subscribe(name, ...rest); - call(method:string, ...parameters):void; - apply(method:string, ...parameters):void; - methods(IMeteorMethodsDictionary); - status():DDPStatus; - reconnect(); - disconnect(); - onReconnect(); - } + interface DDPStatic { + subscribe(name, ...rest); + call(method:string, ...parameters):void; + apply(method:string, ...parameters):void; + methods(IMeteorMethodsDictionary); + status():DDPStatus; + reconnect(); + disconnect(); + onReconnect(); + } - interface DDPStatus { - connected: boolean; - status: Meteor.StatusEnum; - retryCount: number; - //To turn this into an interval until the next reconnection, use retryTime - (new Date()).getTime() - retryTime?: number; - reason?: string; - } + interface DDPStatus { + connected: boolean; + status: Meteor.StatusEnum; + retryCount: number; + //To turn this into an interval until the next reconnection, use retryTime - (new Date()).getTime() + retryTime?: number; + reason?: string; + } } declare module Random { - function id(numberOfChars?: number): string; - function secret(numberOfChars?: number): string; - function fraction():number; - function hexString(numberOfDigits:number):string; // @param numberOfDigits, @returns a random hex string of the given length - function choice(array:any[]):string; // @param array, @return a random element in array - function choice(str:string):string; // @param str, @return a random char in str + function id(numberOfChars?: number): string; + function secret(numberOfChars?: number): string; + function fraction():number; + function hexString(numberOfDigits:number):string; // @param numberOfDigits, @returns a random hex string of the given length + function choice(array:any[]):string; // @param array, @return a random element in array + function choice(str:string):string; // @param str, @return a random char in str } declare module Blaze { - interface View { - name: string; - parentView: Blaze.View; - isCreated: boolean; - isRendered: boolean; - isDestroyed: boolean; - renderCount: number; - autorun(runFunc: Function): void; - onViewCreated(func: Function): void; - onViewReady(func: Function): void; - onViewDestroyed(func: Function): void; - firstNode(): Node; - lastNode(): Node; - template: Blaze.Template; - templateInstance(): any; - } - interface Template { - viewName: string; - renderFunction: Function; - constructView(): Blaze.View; - } + interface View { + name: string; + parentView: Blaze.View; + isCreated: boolean; + isRendered: boolean; + isDestroyed: boolean; + renderCount: number; + autorun(runFunc: Function): void; + onViewCreated(func: Function): void; + onViewReady(func: Function): void; + onViewDestroyed(func: Function): void; + firstNode(): Node; + lastNode(): Node; + template: Blaze.Template; + templateInstance(): any; + } + interface Template { + viewName: string; + renderFunction: Function; + constructView(): Blaze.View; + } } +declare module BrowserPolicy { + + interface framing { + disallow():void; + restrictToOrigin(origin:string):void; + allowAll():void; + } + interface content { + allowEval():void; + allowInlineStyles():void; + allowInlineScripts():void; + allowSameOriginForAll():void; + allowDataUrlForAll():void; + allowOriginForAll(origin:string):void; + allowImageOrigin(origin:string):void; + allowFrameOrigin(origin:string):void; + allowContentTypeSniffing():void; + allowAllContentOrigin():void; + allowAllContentDataUrl():void; + allowAllContentSameOrigin():void; + + disallowAll():void; + disallowInlineStyles():void; + disallowEval():void; + disallowInlineScripts():void; + disallowFont():void; + disallowObject():void; + disallowAllContent():void; + //TODO: add the basic content types + // allowOrigin(origin) + // allowDataUrl() + // allowSameOrigin() + // disallow() + } +} + +declare module Tracker { + export var ComputationFunction: (computation: Tracker.Computation) => void; + +} + +declare var IterationCallback: (doc: T, index: number, cursor: Mongo.Cursor) => void; + /** * These modules and interfaces are automatically generated from the Meteor api.js file */ declare module Accounts { - var ui: { - config(options: { - requestPermissions?: Object; - requestOfflineToken?: Object; - forceApprovalPrompt?: Object; - passwordSignupFields?: string; - }): void; - }; - var emailTemplates: Meteor.EmailTemplates; + function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; function config(options: { - sendVerificationEmail?: boolean; - forbidClientAccountCreation?: Boolean; - restrictCreationByEmailDomain?: string | Function; - loginExpirationInDays?: number; - oauthSecretKey?: string; - }): void; - function validateLoginAttempt(func: Function): {stop: Function}; - function onLogin(func: Function): {stop: Function}; - function onLoginFailure(func: Function): {stop: Function}; + sendVerificationEmail?: boolean; + forbidClientAccountCreation?: boolean; + restrictCreationByEmailDomain?: string | Function; + loginExpirationInDays?: number; + oauthSecretKey?: string; + }): void; + function createUser(options: { + username?: string; + email?: string; + password?: string; + profile?: Object; + }, callback?: Function): string; + var emailTemplates: Meteor.EmailTemplates; + function forgotPassword(options: { + email?: string; + }, callback?: Function): void; function onCreateUser(func: Function): void; - function validateNewUser(func: Function): void; - function onResetPasswordLink(callback: Function): void; function onEmailVerificationLink(callback: Function): void; function onEnrollmentLink(callback: Function): void; - function createUser(options: { - username?: string; - email?: string; - password?: string; - profile?: Object; - }, callback?: Function): string; - function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; - function forgotPassword(options: { - email?: string; - }, callback?: Function): void; + function onLogin(func: Function): {stop: Function}; + function onLoginFailure(func: Function): {stop: Function}; + function onResetPasswordLink(callback: Function): void; function resetPassword(token: string, newPassword: string, callback?: Function): void; - function verifyEmail(token: string, callback?: Function): void; - function setPassword(userId: string, newPassword: string): void; - function sendResetPasswordEmail(userId: string, email?: string): void; function sendEnrollmentEmail(userId: string, email?: string): void; + function sendResetPasswordEmail(userId: string, email?: string): void; function sendVerificationEmail(userId: string, email?: string): void; + function setPassword(userId: string, newPassword: string, options?: { + logout?: Object; + }): void; + var ui: { + config(options: { + requestPermissions?: Object; + requestOfflineToken?: Object; + forceApprovalPrompt?: Object; + passwordSignupFields?: string; + }): void; + }; + function validateLoginAttempt(func: Function): {stop: Function}; + function validateNewUser(func: Function): void; + function verifyEmail(token: string, callback?: Function): void; +} + +declare module App { + function accessRule(domainRule: string, options?: { + launchExternal?: boolean; + }); /** TODO: add return value **/ +function configurePlugin(pluginName: string, config: Object): void; + function icons(icons: Object): void; + function info(options: { + id?: string; + version?: string; + name?: string; + description?: string; + author?: string; + email?: string; + website?: string; + }): void; + function launchScreens(launchScreens: Object): void; + function setPreference(name: string, value: string): void; +} + +declare module Assets { + function getBinary(assetPath: string, asyncCallback?: Function): EJSON; + function getText(assetPath: string, asyncCallback?: Function): string; } declare module Blaze { - var currentView: Blaze.View; - function With(data: Object | Function, contentFunc: Function): Blaze.View; - function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - function isTemplate(value: any): boolean; - function render(templateOrView: Template | Blaze.View, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; - function renderWithData(templateOrView: Template | Blaze.View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; - function remove(renderedView: Blaze.View): void; - function toHTML(templateOrView: Template | Blaze.View): string; - function toHTMLWithData(templateOrView: Template | Blaze.View, data: Object | Function): string; - function getData(elementOrView?: HTMLElement | Blaze.View): Object; - function getView(element?: HTMLElement): Blaze.View; - function Template(viewName?: string, renderFunction?: Function): void; - interface Template{ + function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; + var Template: TemplateStatic; + interface TemplateStatic { + new(viewName?: string, renderFunction?: Function): Template; + // It should be [templateName: string]: TemplateInstance but this is not possible -- user will need to cast to TemplateInstance + [templateName: string]: any | Template; // added "any" to make it work + head: Template; + find(selector:string):Blaze.Template; + findAll(selector:string):Blaze.Template[]; + $:any; + } + interface Template { } - function TemplateInstance(view: Blaze.View): void; - interface TemplateInstance{ + var TemplateInstance: TemplateInstanceStatic; + interface TemplateInstanceStatic { + new(view: Blaze.View): TemplateInstance; + } + interface TemplateInstance { + $(selector: string): any; + autorun(runFunc: Function): Object; data: Object; - view: Object; + find(selector?: string): Blaze.TemplateInstance; + findAll(selector: string): Blaze.TemplateInstance[]; firstNode: Object; lastNode: Object; - $(selector: string): Node[]; - findAll(selector: string): HTMLElement[]; - find(selector?: string): HTMLElement; - autorun(runFunc: Function): Object; + subscribe(name: string, ...args): Meteor.SubscriptionHandle; + subscriptionsReady(): boolean; + view: Object; } - function View(name?: string, renderFunction?: Function): void; - interface View{ + function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; + var View: ViewStatic; + interface ViewStatic { + new(name?: string, renderFunction?: Function): View; + } + interface View { } + function With(data: Object | Function, contentFunc: Function): Blaze.View; + var currentView: Blaze.View; + function getData(elementOrView?: HTMLElement | Blaze.View): Object; + function getView(element?: HTMLElement): Blaze.View; + function isTemplate(value: any): boolean; + function remove(renderedView: Blaze.View): void; + function render(templateOrView: Template | Blaze.View, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; + function renderWithData(templateOrView: Template | Blaze.View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; + function toHTML(templateOrView: Template | Blaze.View): string; + function toHTMLWithData(templateOrView: Template | Blaze.View, data: Object | Function): string; } -declare module Match { - function test(value: any, pattern: any): boolean; +declare module Cordova { + function depends(dependencies:{[id:string]:string}): void; } declare module DDP { @@ -352,330 +427,355 @@ declare module DDP { } declare module EJSON { - var newBinary: any; - function addType(name: string, factory: Function): void; - function toJSONValue(val: EJSON): JSON; - function fromJSONValue(val: JSON): any; - function stringify(val: EJSON, options?: { - indent?: boolean | number | string; - canonical?: Boolean; - }): string; - function parse(str: string): EJSON; - function isBinary(x: Object): boolean; - function equals(a: EJSON, b: EJSON, options?: { - keyOrderSensitive?: boolean; - }): boolean; - function clone(val:T): T; - function CustomType(): void; - interface CustomType{ - typeName(): string; - toJSONValue(): JSON; + var CustomType: CustomTypeStatic; + interface CustomTypeStatic { + new(): CustomType; + } + interface CustomType { clone(): EJSON.CustomType; equals(other: Object): boolean; + toJSONValue(): JSON; + typeName(): string; } + function addType(name: string, factory: (val: EJSONable) => JSONable): void; + function clone(val:T): T; + function equals(a: EJSON, b: EJSON, options?: { + keyOrderSensitive?: boolean; + }): boolean; + function fromJSONValue(val: JSON): any; + function isBinary(x: Object): boolean; + var newBinary: any; + function parse(str: string): EJSON; + function stringify(val: EJSON, options?: { + indent?: boolean | number | string; + canonical?: boolean; + }): string; + function toJSONValue(val: EJSON): JSON; +} + +declare module Match { + function test(value: any, pattern: any): boolean; } declare module Meteor { - var users: Mongo.Collection; - var isClient: boolean; - var isServer: boolean; - var settings: {[id:string]: any}; - var isCordova: boolean; - var release: string; - function userId(): string; - function loggingIn(): boolean; - function user(): Meteor.User; - function logout(callback?: Function): void; - function logoutOtherClients(callback?: Function): void; - function loginWith(options?: { - requestPermissions?: string[]; - requestOfflineToken?: boolean; - forceApprovalPrompt?: Boolean; - userEmail?: string; - loginStyle?: string; - }, callback?: Function): void; - function loginWithPassword(user: Object | string, password: string, callback?: Function): void; - function subscribe(name: string, ...args): SubscriptionHandle; - function call(name: string, ...args): void; - function apply(name: string, args: EJSON[], options?: { - wait?: boolean; - onResultReceived?: Function; - }, asyncCallback?: Function): void; - function status(): Meteor.StatusEnum; - function reconnect(): void; - function disconnect(): void; - function onConnection(callback: Function): void; - function publish(name: string, func: Function): void; - function methods(methods: Object): void; - function wrapAsync(func: Function, context?: Object): any; - function startup(func: Function): void; - function setTimeout(func: Function, delay: number): number; - function setInterval(func: Function, delay: number): number; - function clearInterval(id: number): void; - function clearTimeout(id: number): void; - function absoluteUrl(path?: string, options?: { - secure?: boolean; - replaceLocalhost?: Boolean; - rootUrl?: string; - }): string; - function Error(error: string, reason?: string, details?: string): void; - interface Error{ + var Error: ErrorStatic; + interface ErrorStatic { + new(error: string, reason?: string, details?: string): Error; + } + interface Error { } + function absoluteUrl(path?: string, options?: { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + }): string; + function apply(name: string, args: EJSONable[], options?: { + wait?: boolean; + onResultReceived?: Function; + }, asyncCallback?: Function): any; + function call(name: string, ...args): any; + function clearInterval(id: number): void; + function clearTimeout(id: number): void; + function disconnect(): void; + var isClient: boolean; + var isCordova: boolean; + var isServer: boolean; + function loggingIn(): boolean; + function loginWith(options?: { + requestPermissions?: string[]; + requestOfflineToken?: boolean; + forceApprovalPrompt?: boolean; + userEmail?: string; + loginStyle?: string; + }, callback?: Function): void; + function loginWithPassword(user: Object | string, password: string, callback?: Function): void; + function logout(callback?: Function): void; + function logoutOtherClients(callback?: Function): void; + function methods(methods: Object): void; + function onConnection(callback: Function): void; + function publish(name: string, func: Function): void; + function reconnect(): void; + var release: string; + function setInterval(func: Function, delay: number): number; + function setTimeout(func: Function, delay: number): number; + var settings: {[id:string]: any}; + function startup(func: Function): void; + function status(): Meteor.StatusEnum; + function subscribe(name: string, ...args): Meteor.SubscriptionHandle; + function user(): Meteor.User; + function userId(): string; + var users: Mongo.Collection; + function wrapAsync(func: Function, context?: Object): any; } declare module Mongo { - function Collection(name: string, options?: { - connection?: Object; - idGeneration?: string; - transform?: Function; - }): void; - interface Collection{ - insert(doc: Object, callback?: Function): string; - update(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: { - multi?: boolean; - upsert?: Boolean; - }, callback?: Function): number; - find(selector?: Mongo.Selector, options?: { - sort?: Mongo.SortSpecifier; - skip?: number; - limit?: number; - fields?: Mongo.FieldSpecifier; - reactive?: boolean; - transform?: Function; - }): Mongo.Cursor; - findOne(selector?: Mongo.Selector, options?: { - sort?: Mongo.SortSpecifier; - skip?: number; - fields?: Mongo.FieldSpecifier; - reactive?: boolean; - transform?: Function; - }): T; - remove(selector: Mongo.Selector, callback?: Function): void; - upsert(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: { - multi?: boolean; - }, callback?: Function): {numberAffected?: number; insertedId?: string;}; + var Collection: CollectionStatic; + interface CollectionStatic { + new(name: string, options?: { + connection?: Object; + idGeneration?: string; + transform?: Function; + }): Collection; + } + interface Collection { allow(options: { - insert?: (userId:string, doc) => boolean; - update?: (userId, doc, fieldNames, modifier) => boolean; - remove?: (userId, doc) => boolean; - fetch?: string[]; - transform?: Function; - }): boolean; + insert?: (userId:string, doc) => boolean; + update?: (userId, doc, fieldNames, modifier) => boolean; + remove?: (userId, doc) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; deny(options: { - insert?: (userId:string, doc) => boolean; - update?: (userId, doc, fieldNames, modifier) => boolean; - remove?: (userId, doc) => boolean; - fetch?: string[]; - transform?: Function; - }): boolean; + insert?: (userId:string, doc) => boolean; + update?: (userId, doc, fieldNames, modifier) => boolean; + remove?: (userId, doc) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + find(selector?: Mongo.Selector, options?: { + sort?: Mongo.SortSpecifier; + skip?: number; + limit?: number; + fields?: Mongo.FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): Mongo.Cursor; + findOne(selector?: Mongo.Selector, options?: { + sort?: Mongo.SortSpecifier; + skip?: number; + fields?: Mongo.FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): T; + insert(doc: Object, callback?: Function): string; + remove(selector: Mongo.Selector, callback?: Function): void; + update(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, callback?: Function): number; + upsert(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: { + multi?: boolean; + }, callback?: Function): {numberAffected?: number; insertedId?: string;}; + _ensureIndex(indexName: string, options?: {[key: string]: any}): void; } - function ObjectID(hexString: string): void; - interface ObjectID{ + var Cursor: CursorStatic; + interface CursorStatic { + new(): Cursor; } - - function Cursor(): void; - interface Cursor{ - forEach(callback: Function, thisArg?: any): void; - map(callback: Function, thisArg?: any): void; - fetch(): Array; + interface Cursor { count(): number; + fetch(): Array; + forEach(callback: (doc: T, index: number, cursor: Mongo.Cursor) => void, thisArg?: any): void; + map(callback: (doc: T, index: number, cursor: Mongo.Cursor) => void, thisArg?: any): Array; observe(callbacks: Object): Meteor.LiveQueryHandle; observeChanges(callbacks: Object): Meteor.LiveQueryHandle; } -} - -declare module Tracker { - var active: boolean; - var currentComputation: Tracker.Computation; - function Computation(): void; - interface Computation{ - stopped: boolean; - invalidated: boolean; - firstRun: boolean; - onInvalidate(callback: Function): void; - invalidate(): void; - stop(): void; + var ObjectID: ObjectIDStatic; + interface ObjectIDStatic { + new(hexString: string): ObjectID; + } + interface ObjectID { } - function flush(): void; - function autorun(runFunc: Function): Tracker.Computation; - function nonreactive(func: Function): void; - function onInvalidate(callback: Function): void; - function afterFlush(callback: Function): void; - function Dependency(): void; - interface Dependency{ - depend(fromComputation?: Tracker.Computation): boolean - changed(): void; - hasDependents(): boolean - } - -} - -declare module Assets { - function getText(assetPath: string, asyncCallback?: Function): string; - function getBinary(assetPath: string, asyncCallback?: Function): EJSON; -} - -declare module App { - function info(options: { - id?: string; - version?: string; - name?: string; - description?: string; - author?: string; - email?: string; - website?: string; - }): void; - function setPreference(name: string, value: string): void; - function configurePlugin(pluginName: string, config: Object): void; - function icons(icons: Object): void; - function launchScreens(launchScreens: Object): void; -} - -declare module Package { - function describe(options: { - summary?: string; - version?: string; - name?: string; - git?: string; - documentation?: string; - }): void; - function onUse(func: Function): void; - function onTest(func: Function): void; - function registerBuildPlugin(options?: { - name?: string; - use?: string | string[]; - sources?: string[]; - npmDependencies?: Object; - }): void; } declare module Npm { function depends(dependencies:{[id:string]:string}): void; - function require(name: string): void; + function require(name: string): any; } -declare module Cordova { - function depends(dependencies:{[id:string]:string}): void; +declare module Package { + function describe(options: { + summary?: string; + version?: string; + name?: string; + git?: string; + documentation?: string; + }): void; + function onTest(func: Function): void; + function onUse(func: Function): void; + function registerBuildPlugin(options?: { + name?: string; + use?: string | string[]; + sources?: string[]; + npmDependencies?: Object; + }): void; +} + +declare module Tracker { + function Computation(): void; + interface Computation { + firstRun: boolean; + invalidate(): void; + invalidated: boolean; + onInvalidate(callback: Function): void; + stop(): void; + stopped: boolean; + } + + var Dependency: DependencyStatic; + interface DependencyStatic { + new(): Dependency; + } + interface Dependency { + changed(): void; + depend(fromComputation?: Tracker.Computation): boolean; + hasDependents(): boolean; + } + + var active: boolean; + function afterFlush(callback: Function): void; + function autorun(runFunc: (computation: Tracker.Computation) => void, options?: { + onError?: Function; + }): Tracker.Computation; + var currentComputation: Tracker.Computation; + function flush(): void; + function nonreactive(func: Function): void; + function onInvalidate(callback: Function): void; } declare module Session { - function set(key: string, value: EJSON | any /** Undefined **/): void; - function setDefault(key: string, value: EJSON | any /** Undefined **/): void; - function get(key: string): any; function equals(key: string, value: string | number | boolean | any /** Null **/ | any /** Undefined **/): boolean; + function get(key: string): any; + function set(key: string, value: EJSONable | any /** Undefined **/): void; + function setDefault(key: string, value: EJSONable | any /** Undefined **/): void; } declare module HTTP { function call(method: string, url: string, options?: { - content?: string; - data?: Object; - query?: string; - params?: Object; - auth?: string; - headers?: Object; - timeout?: number; - followRedirects?: boolean; - }, asyncCallback?: Function): HTTP.HTTPResponse; + content?: string; + data?: Object; + query?: string; + params?: Object; + auth?: string; + headers?: Object; + timeout?: number; + followRedirects?: boolean; + npmRequestOptions?: Object; + }, asyncCallback?: Function): HTTP.HTTPResponse; + function del(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; function get(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; function post(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; function put(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function del(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; } declare module Email { function send(options: { - from?: string; - to?: string | string[]; - cc?: string | string[]; - bcc?: string | string[]; - replyTo?: string | string[]; - subject?: string; - text?: string; - html?: string; - headers?: Object; - }): void; + from?: string; + to?: string | string[]; + cc?: string | string[]; + bcc?: string | string[]; + replyTo?: string | string[]; + subject?: string; + text?: string; + html?: string; + headers?: Object; + attachments?: Object[]; + }): void; } -declare function Subscription(): void; -interface Subscription{ - connection: Meteor.Connection; - userId: string; - error(error: Error): void; - stop(): void; - onStop(func: Function): void; - added(collection: string, id: string, fields: Object): void; - changed(collection: string, id: string, fields: Object): void; - removed(collection: string, id: string): void; - ready(): void; +declare var CompileStep: CompileStepStatic; +interface CompileStepStatic { + new(): CompileStep; +} +interface CompileStep { + addAsset(options: { + }, path: string, data: any /** Buffer **/ | string); /** TODO: add return value **/ + addHtml(options: { + section?: string; + data?: string; + }); /** TODO: add return value **/ + addJavaScript(options: { + path?: string; + data?: string; + sourcePath?: string; + }); /** TODO: add return value **/ + addStylesheet(options: { + }, path: string, data: string, sourceMap: string); /** TODO: add return value **/ + arch; /** TODO: add return value **/ + declaredExports; /** TODO: add return value **/ + error(options: { + }, message: string, sourcePath?: string, line?: number, func?: string); /** TODO: add return value **/ + fileOptions; /** TODO: add return value **/ + fullInputPath; /** TODO: add return value **/ + inputPath; /** TODO: add return value **/ + inputSize; /** TODO: add return value **/ + packageName; /** TODO: add return value **/ + pathForSourceMap; /** TODO: add return value **/ + read(n?: number): any; + rootOutputPath; /** TODO: add return value **/ } -declare function ReactiveVar(initialValue: T, equalsFunc?: Function): void; -interface ReactiveVar{ +declare var PackageAPI: PackageAPIStatic; +interface PackageAPIStatic { + new(): PackageAPI; +} +interface PackageAPI { + addFiles(filename: string | string[], architecture?: string): void; + export(exportedObject: string, architecture?: string): void; + imply(packageSpecs: string | string[]): void; + use(packageNames: string | string[], architecture?: string, options?: { + weak?: boolean; + unordered?: boolean; + }): void; + versionsFrom(meteorRelease: string | string[]): void; +} + +declare var ReactiveVar: ReactiveVarStatic; +interface ReactiveVarStatic { + new(initialValue: T, equalsFunc?: Function): ReactiveVar; +} +interface ReactiveVar { get(): T; set(newValue: T): void; } +declare var Subscription: SubscriptionStatic; +interface SubscriptionStatic { + new(): Subscription; +} +interface Subscription { + added(collection: string, id: string, fields: Object): void; + changed(collection: string, id: string, fields: Object): void; + connection: Meteor.Connection; + error(error: Error): void; + onStop(func: Function): void; + ready(): void; + removed(collection: string, id: string): void; + stop(): void; + userId: string; +} + declare var Template: TemplateStatic; -// TemplateStatic interface should be defined separately at top with static methods -interface Template{ - onCreated: Function; - onRendered: Function; - onDestroyed: Function; - created: Function; - rendered: Function; - destroyed: Function; - body: TemplateStatic; - helpers(helpers:{[id:string]: any}): void; - events(eventMap: {[actions: string]: Function}): void; - instance(): Blaze.TemplateInstance; +interface TemplateStatic { + new(): Template; + // It should be [templateName: string]: TemplateInstance but this is not possible -- user will need to cast to TemplateInstance + [templateName: string]: any | Template; // added "any" to make it work + head: Template; + find(selector:string):Blaze.Template; + findAll(selector:string):Blaze.Template[]; + $:any; + body: Template; currentData(): {}; + instance(): Blaze.TemplateInstance; parentData(numLevels?: number): {}; registerHelper(name: string, helperFunction: Function): void; } - -declare function CompileStep(): void; -interface CompileStep{ - inputSize; /** TODO: add return value **/ - inputPath; /** TODO: add return value **/ - fullInputPath; /** TODO: add return value **/ - pathForSourceMap; /** TODO: add return value **/ - packageName; /** TODO: add return value **/ - rootOutputPath; /** TODO: add return value **/ - arch; /** TODO: add return value **/ - fileOptions; /** TODO: add return value **/ - declaredExports; /** TODO: add return value **/ - read(n?: number); /** TODO: add return value **/ - addHtml(options: { - section?: string; - data?: string; - }); /** TODO: add return value **/ - addStylesheet(options: { - }, path: string, data: string, sourceMap: string); /** TODO: add return value **/ - addJavaScript(options: { - path?: string; - data?: string; - sourcePath?: string; - }); /** TODO: add return value **/ - addAsset(options: { - }, path: string, data: any /** Buffer **/ | string); /** TODO: add return value **/ - error(options: { - }, message: string, sourcePath?: string, line?: number, func?: string); /** TODO: add return value **/ -} - -declare function PackageAPI(): void; -interface PackageAPI{ - use(packageNames: string | string[], architecture?: string, options?: { - weak?: boolean; - unordered?: Boolean; - }): void; - imply(packageSpecs: string | string[]): void; - addFiles(filename: string | string[], architecture?: string): void; - versionsFrom(meteorRelease: string | string[]): void; - export(exportedObject: string, architecture?: string): void; +interface Template { + created: Function; + destroyed: Function; + events(eventMap: {[actions: string]: Function}): void; + helpers(helpers:{[id:string]: any}): void; + onCreated: Function; + onDestroyed: Function; + onRendered: Function; + rendered: Function; } +declare function MethodInvocation(options: { +}); /** TODO: add return value **/ +declare function check(value: any, pattern: any): void; diff --git a/moment-timezone/moment-timezone-tests.ts b/moment-timezone/moment-timezone-tests.ts index f6a754c6e..6e818c742 100644 --- a/moment-timezone/moment-timezone-tests.ts +++ b/moment-timezone/moment-timezone-tests.ts @@ -8,11 +8,16 @@ june.tz('America/Los_Angeles').format('ha z'); var a = moment.tz("2013-11-18 11:55", "America/Toronto"); var b = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", "America/Toronto"); var c = moment.tz(1403454068850, "America/Toronto"); +var d = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", true, "America/Toronto"); + +a.tz(); var arr = [2013, 5, 1], str = "2013-12-01", obj = { year : 2013, month : 5, day : 1 }; +moment.tz("America/Los_Angeles"); + moment.tz(arr, "America/Los_Angeles"); moment.tz(str, "America/Los_Angeles"); moment.tz(obj, "America/Los_Angeles"); diff --git a/moment-timezone/moment-timezone.d.ts b/moment-timezone/moment-timezone.d.ts index 1e908ace1..02d72ac2e 100644 --- a/moment-timezone/moment-timezone.d.ts +++ b/moment-timezone/moment-timezone.d.ts @@ -7,6 +7,7 @@ declare module moment { interface Moment { + tz(): string; tz(timezone: string): Moment; } @@ -27,9 +28,11 @@ interface MomentZone { } interface MomentTimezone { + (timezone: string): moment.Moment; (date: number, timezone: string): moment.Moment; (date: number[], timezone: string): moment.Moment; (date: string, format: string, timezone: string): moment.Moment; + (date: string, format: string, useStrict: boolean, timezone: string): moment.Moment; (date: Date, timezone: string): moment.Moment; (date: moment.Moment, timezone: string): moment.Moment; (date: Object, timezone: string): moment.Moment; diff --git a/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api-tests.ts b/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api-tests.ts deleted file mode 100644 index 76dba72a5..000000000 --- a/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api-tests.ts +++ /dev/null @@ -1,127 +0,0 @@ -/// - -import Syntax = spiderMonkeyParserAPI.Syntax; - -var literal:Syntax.Literal = { - loc: { - source: null, - start: { - line: 1, - column: 10 - }, - end: { - line: 1, - column: 12 - } - }, - type: "Literal", - value: 42 -}; - -// generated by http://esprima.org/demo/parse.html?code=%22use%20strict%22%3B%0A%0Afunction%20Test%20()%20%7B%0A%7D%0A%0ATest.prototype.hello%20%3D%20function(word)%20%7B%0A%09word%20%3D%20word%20%7C%7C%20%22TypeScript%22%3B%0A%09return%20word%3B%0A%7D%3B%0A -var program:Syntax.Program = { - "type": "Program", - "body": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "Literal", - "value": "use strict", - "raw": "\"use strict\"" - } - }, - { - "type": "FunctionDeclaration", - "id": { - "type": "Identifier", - "name": "Test" - }, - "params": [], - "defaults": [], - "body": { - "type": "BlockStatement", - "body": [] - }, - "rest": null, - "generator": false, - "expression": false - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "MemberExpression", - "computed": false, - "object": { - "type": "MemberExpression", - "computed": false, - "object": { - "type": "Identifier", - "name": "Test" - }, - "property": { - "type": "Identifier", - "name": "prototype" - } - }, - "property": { - "type": "Identifier", - "name": "hello" - } - }, - "right": { - "type": "FunctionExpression", - "id": null, - "params": [ - { - "type": "Identifier", - "name": "word" - } - ], - "defaults": [], - "body": { - "type": "BlockStatement", - "body": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "Identifier", - "name": "word" - }, - "right": { - "type": "LogicalExpression", - "operator": "||", - "left": { - "type": "Identifier", - "name": "word" - }, - "right": { - "type": "Literal", - "value": "TypeScript", - "raw": "\"TypeScript\"" - } - } - } - }, - { - "type": "ReturnStatement", - "argument": { - "type": "Identifier", - "name": "word" - } - } - ] - }, - "rest": null, - "generator": false, - "expression": false - } - } - } - ] -}; diff --git a/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api.d.ts b/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api.d.ts deleted file mode 100644 index e91029137..000000000 --- a/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api.d.ts +++ /dev/null @@ -1,614 +0,0 @@ -// Type definitions for Mozilla SpiderMonkey Parser API 1.8.5 -// Project: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API -// Definitions by: vvakame -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module spiderMonkeyParserAPI { - - // NOTE if property can hold null, that property to be optional. - - module Syntax { - /** - * By default, Reflect.parse() produces Node objects, which are plain JavaScript objects (i.e., their prototype derives from the standard Object prototype). - * All node types implement the following interface: - */ - interface Node { - /** - * The type field is a string representing the AST variant type. - * Each subtype of Node is documented below with the specific string of its type field. - * You can use this field to determine which interface a node implements. - */ - type: string; - /** - * The loc field represents the source location information of the node. - * If the parser produced no information about the node's source location, the field is null; otherwise it is an object consisting of a start position (the position of the first character of the parsed source region) and an end position (the position of the first character after the parsed source region): - */ - loc?: SourceLocation; - } - - interface SourceLocation { - source?: string; - start: Position; - end: Position; - } - - /** - * Each Position object consists of a line number (1-indexed) and a column number (0-indexed): - */ - interface Position { - line: number; // uint32 >= 1; - column: number; // uint32 >= 0; - } - - /** - * A complete program source tree. - */ - interface Program extends Node { - type: string; // "Program" - body: Statement[]; - } - - /** - * A function declaration or expression. - * The body of the function may be a block statement, or in the case of an expression closure, an expression. - * If the generator flag is true, the function is a generator function, i.e., contains a yield expression in its body (other than in a nested function). - * If the expression flag is true, the function is an expression closure and the body field is an expression. - */ - interface Function extends Node { - id?: Identifier; - params: Pattern[]; - defaults: Expression[]; - rest?: Identifier; - body?: BlockStatement | Expression; - generator: boolean; - expression: boolean; - } - - /** - * Any statement. - */ - interface Statement extends Node { - } - - /** - * An empty statement, i.e., a solitary semicolon. - */ - interface EmptyStatement extends Statement { - type: string; // "EmptyStatement"; - } - - /** - * A block statement, i.e., a sequence of statements surrounded by braces. - */ - interface BlockStatement extends Statement { - type: string; // "BlockStatement"; - body: Statement[]; - } - - /** - * An if statement. - */ - interface IfStatement extends Statement { - type: string; // "IfStatement"; - test: Expression; - consequent: Statement; - alternate?: Statement; - } - - /** - * A labeled statement, i.e., a statement prefixed by a break/continue label. - */ - interface LabeledStatement extends Statement { - type: string; // "LabeledStatement"; - label: Identifier; - body: Statement; - } - - /** - * A break statement. - */ - interface BreakStatement extends Statement { - type: string; // "BreakStatement"; - label?: Identifier; - } - - /** - * A continue statement. - */ - interface ContinueStatement extends Statement { - type: string; // "ContinueStatement"; - label?: Identifier; - } - - /** - * A with statement. - */ - interface WithStatement extends Statement { - type: string; // "WithStatement"; - object: Expression; - body: Statement; - } - - /** - * A switch statement. - * The lexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a new lexical scope). - */ - interface SwitchStatement extends Statement { - type: string; // "SwitchStatement"; - discriminant: Expression; - cases: SwitchCase[]; - lexical: boolean; - } - - /** - * A return statement. - */ - interface ReturnStatement extends Statement { - type: string; // "ReturnStatement"; - argument?: Expression; - } - - /** - * A throw statement. - */ - interface ThrowStatement extends Statement { - type: string; // "ThrowStatement"; - argument: Expression; - } - - /** - * A try statement. - */ - interface TryStatement extends Statement { - type: string; //"TryStatement"; - block: BlockStatement; - handler?: CatchClause; - guardedHandlers: CatchClause[]; - finalizer?: BlockStatement; - } - - /** - * A while statement. - */ - interface WhileStatement extends Statement { - type: string; // "WhileStatement"; - test: Expression; - body: Statement; - } - - /** - * A do/while statement. - */ - interface DoWhileStatement extends Statement { - type: string; // "DoWhileStatement"; - body: Statement; - test: Expression; - } - - /** - * A for statement. - */ - interface ForStatement extends Statement { - type: string; // "ForStatement"; - init?: VariableDeclaration | Expression; - test?: Expression; - update?: Expression; - body: Statement; - } - - /** - * A for/in statement, or, if each is true, a for each/in statement. - */ - interface ForInStatement extends Statement { - type: string; // "ForInStatement"; - left: VariableDeclaration | Expression; - right: Expression; - body: Statement; - each: boolean; - } - - /** - * A for/of statement. - */ - interface ForOfStatement extends Statement { - type: string; // "ForOfStatement"; - left: VariableDeclaration | Expression; - right: Expression; - body: Statement; - } - - /** - * A let statement. - */ - interface LetStatement extends Statement { - type: string; // "LetStatement"; - head: VariableDeclarator[]; - body: Statement; - } - - /** - * A debugger statement. - */ - interface DebuggerStatement extends Statement { - type: string; // "DebuggerStatement"; - } - - /** - * Any declaration node. Note that declarations are considered statements; this is because declarations can appear in any statement context in the language recognized by the SpiderMonkey parser. - */ - interface Declaration extends Statement { - } - - /** - * A function declaration. - */ - interface FunctionDeclaration extends Function, Declaration { - type: string; // "FunctionDeclaration"; - id: Identifier; // Note: The id field cannot be null. - params: Pattern[]; - defaults: Expression[]; - rest?: Identifier; - body: BlockStatement | Expression; - generator: boolean; - expression: boolean; - } - - /** - * A variable declaration, via one of var, let, or const. - */ - interface VariableDeclaration extends Declaration { - type: string; // "VariableDeclaration"; - declarations: VariableDeclarator[]; - kind: string; // "var" | "let" | "const"; - } - - /** - * A variable declarator. - */ - interface VariableDeclarator extends Node { - type: string; // "VariableDeclarator"; - id: Pattern; // Note: The id field cannot be null. - init?: Expression; - } - - /** - * Any expression node. - * Since the left-hand side of an assignment may be any expression in general, an expression can also be a pattern. - */ - interface Expression extends Node, Pattern { - } - - /** - * A this expression. - */ - interface ThisExpression extends Expression { - type: string; // "ThisExpression"; - } - - /** - * An array expression. - */ - interface ArrayExpression extends Expression { - type: string; // "ArrayExpression"; - elements: Expression[]; // [ Expression | null ]; - } - - /** - * An object expression. - */ - interface ObjectExpression extends Expression { - type: string; // "ObjectExpression"; - properties: Property[]; - } - - /** - * A literal property in an object expression can have either a string or number as its value. - * Ordinary property initializers have a kind value "init"; getters and setters have the kind values "get" and "set", respectively. - */ - interface Property extends Node { - type: string; // "Property"; - key: Literal | Identifier; - value: Expression; - kind: string; // "init" | "get" | "set"; - } - - /** - * A function expression. - */ - interface FunctionExpression extends Function, Expression { - type: string; // "FunctionExpression"; - id?: Identifier; - params: Pattern[]; - defaults: Expression[]; - rest?: Identifier; - body: BlockStatement | Expression; - generator: boolean; - expression: boolean; - } - - /** - * A fat arrow function expression, i.e., `let foo = (bar) => { ... body ... }`. - */ - interface ArrowExpression extends Function, Expression { - type: string; // "ArrowExpression"; - params: Pattern[]; - defaults: Expression[]; - rest?: Identifier; - body: BlockStatement | Expression; - generator: boolean; - expression: boolean; - } - - /** - * A sequence expression, i.e., a comma-separated sequence of expressions. - */ - interface SequenceExpression extends Expression { - type: string; // "SequenceExpression"; - expressions: Expression[]; - } - - /** - * A unary operator expression. - */ - interface UnaryExpression extends Expression { - type: string; // "UnaryExpression"; - operator: UnaryOperator; - prefix: boolean; - argument: Expression; - } - - /** - * A binary operator expression. - */ - interface BinaryExpression extends Expression { - type: string; // "BinaryExpression"; - operator: BinaryOperator; - left: Expression; - right: Expression; - } - - /** - * An assignment operator expression. - */ - interface AssignmentExpression extends Expression { - type: string; // "AssignmentExpression"; - operator: AssignmentOperator; - left: Expression; - right: Expression; - } - - /** - * An update (increment or decrement) operator expression. - */ - interface UpdateExpression extends Expression { - type: string; // "UpdateExpression"; - operator: UpdateOperator; - argument: Expression; - prefix: boolean; - } - - /** - * A logical operator expression. - */ - interface LogicalExpression extends Expression { - type: string; // "LogicalExpression"; - operator: LogicalOperator; - left: Expression; - right: Expression; - } - - /** - * A conditional expression, i.e., a ternary ?/: expression. - */ - interface ConditionalExpression extends Expression { - type: string; // "ConditionalExpression"; - test: Expression; - alternate: Expression; - consequent: Expression; - } - - /** - * A new expression. - */ - interface NewExpression extends Expression { - type: string; // "NewExpression"; - callee: Expression; - arguments: Expression[]; - } - - /** - * A function or method call expression. - */ - interface CallExpression extends Expression { - type: string; // "CallExpression"; - callee: Expression; - arguments: Expression[]; - } - - /** - * A member expression. - * If computed === true, the node corresponds to a computed e1[e2] expression and property is an Expression. - * If computed === false, the node corresponds to a static e1.x expression and property is an Identifier. - */ - interface MemberExpression extends Expression { - type: string; // "MemberExpression"; - object: Expression; - property: Identifier | Expression; - computed: boolean; - } - - /** - * A yield expression. - */ - interface YieldExpression extends Expression { - type: string; // "YieldExpression"; - argument?: Expression; - } - - /** - * An array comprehension. - * The blocks array corresponds to the sequence of for and for each blocks. - * The optional filter expression corresponds to the final if clause, if present. - */ - interface ComprehensionExpression extends Expression { - type: string; // "ComprehensionExpression"; - body: Expression; - blocks: ComprehensionBlock[]; - filter?: Expression; - } - - /** - * A generator expression. - * As with array comprehensions, the blocks array corresponds to the sequence of for and for each blocks, and the optional filter expression corresponds to the final if clause, if present. - */ - interface GeneratorExpression extends Expression { - type: string; // "GeneratorExpression"; - body: Expression; - blocks: ComprehensionBlock[]; - filter?: Expression; - } - - /** - * A graph expression, aka "sharp literal," such as #1={ self: #1# }. - */ - interface GraphExpression extends Expression { - type: string; // "GraphExpression"; - index: number; // uint32; - expression: Literal; - } - - /** - * A graph index expression, aka "sharp variable," such as #1#. - */ - interface GraphIndexExpression extends Expression { - type: string; // "GraphIndexExpression"; - index: number; // uint32; - } - - /** - * A let expression. - */ - interface LetExpression extends Expression { - type: string; // "LetExpression"; - head: VariableDeclarator[]; - body: Expression; - } - - /** - * JavaScript 1.7 introduced destructuring assignment and binding forms. - * All binding forms (such as function parameters, variable declarations, and catch block headers) accept array and object destructuring patterns in addition to plain identifiers. - * The left-hand sides of assignment expressions can be arbitrary expressions, but in the case where the expression is an object or array literal, it is interpreted by SpiderMonkey as a destructuring pattern. - * - * Since the left-hand side of an assignment can in general be any expression, in an assignment context, a pattern can be any expression. - * In binding positions (such as function parameters, variable declarations, and catch headers), patterns can only be identifiers in the base case, not arbitrary expressions. - */ - interface Pattern extends Node { - } - - /** - * An object-destructuring pattern. A literal property in an object pattern can have either a string or number as its value. - */ - interface ObjectPattern extends Pattern { - type: string; // "ObjectPattern"; - properties: {key: Literal | Identifier; value: Pattern;}[]; // [ { key: Literal | Identifier, value: Pattern } ]; - } - - /** - * An array-destructuring pattern. - */ - interface ArrayPattern extends Pattern { - type: string; // "ArrayPattern"; - elements: Pattern[]; // [ Pattern | null ]; - } - - /** - * A case (if test is an Expression) or default (if test === null) clause in the body of a switch statement. - */ - interface SwitchCase extends Node { - type: string; // "SwitchCase"; - test?: Expression; - consequent: Statement[]; - } - - /** - * A catch clause following a try block. - * The optional guard property corresponds to the optional expression guard on the bound variable. - */ - interface CatchClause extends Node { - type: string; // "CatchClause"; - param: Pattern; - guard?: Expression; - body: BlockStatement; - } - - /** - * A for or for each block in an array comprehension or generator expression. - */ - interface ComprehensionBlock extends Node { - type: string; // "ComprehensionBlock"; - left: Pattern; - right: Expression; - each: boolean; - } - - /** - * An identifier. - * Note that an identifier may be an expression or a destructuring pattern. - */ - interface Identifier extends Node, Expression, Pattern { - type: string; // "Identifier"; - name: string; - } - - /** - * A literal token. Note that a literal can be an expression. - */ - interface Literal extends Node, Expression { - type: string; // "Literal"; - value?: string | boolean | number | RegExp; - } - - /** - * A unary operator token. - */ - interface UnaryOperator extends String { - // "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" - } - - /** - * A binary operator token. - */ - interface BinaryOperator extends String { - // "==" | "!=" | "===" | "!==" - // | "<" | "<=" | ">" | ">=" - // | "<<" | ">>" | ">>>" - // | "+" | "-" | "*" | "/" | "%" - // | "|" | "^" | "&" | "in" - // | "instanceof" | ".." - // Note: The .. operator is E4X-specific. - } - - /** - * A logical operator token. - */ - interface LogicalOperator extends String { - // "||" | "&&" - } - - /** - * An assignment operator token. - */ - interface AssignmentOperator extends String { - // "=" | "+=" | "-=" | "*=" | "/=" | "%=" - // | "<<=" | ">>=" | ">>>=" - // | "|=" | "^=" | "&=" - } - - /** - * An update (increment or decrement) operator token. - */ - interface UpdateOperator extends String { - // "++" | "--" - } - } -} diff --git a/ng-grid/ng-grid-tests.ts b/ng-grid/ng-grid-tests.ts index 82105ea5b..d8d153f28 100644 --- a/ng-grid/ng-grid-tests.ts +++ b/ng-grid/ng-grid-tests.ts @@ -63,7 +63,7 @@ selectionProvider.selectedItems = []; selectionProvider.selectedIndex = 1; selectionProvider.lastClickedRow = {}; selectionProvider.ignoreSelectedItemChanges = false; -selectionProvider.pKeyParser = {}; +selectionProvider.pKeyParser = {}; selectionProvider.ChangeSelection({}, {}); nr = selectionProvider.getSelection({}); nr = selectionProvider.getSelectionIndex({}); @@ -256,15 +256,15 @@ nr = gridScope.totalRowWidth(); a = gridScope.headerScrollerDim(); var gridInstance: ngGrid.IGridInstance = {}; -gridInstance.$canvas = {}; -gridInstance.$viewport = {}; -gridInstance.$groupPanel = {}; -gridInstance.$footerPanel = {}; -gridInstance.$headerScroller = {}; -gridInstance.$headerContainer = {}; -gridInstance.$headers = {}; -gridInstance.$topPanel = {}; -gridInstance.$root = {}; +gridInstance.$canvas = {}; +gridInstance.$viewport = {}; +gridInstance.$groupPanel = {}; +gridInstance.$footerPanel = {}; +gridInstance.$headerScroller = {}; +gridInstance.$headerContainer = {}; +gridInstance.$headers = {}; +gridInstance.$topPanel = {}; +gridInstance.$root = {}; gridInstance.config = {}; gridInstance.data = {}; gridInstance.elementDims = {}; @@ -290,7 +290,7 @@ gridInstance.clearSortingData(); gridInstance.configureColumnWidths(); gridInstance.fixColumnIndexes(); gridInstance.fixGroupIndexes(); -var p:ng.IPromise = gridInstance.getTemplate(''); +var p:angular.IPromise = gridInstance.getTemplate(''); p = gridInstance.init(); p = gridInstance.initTemplates(); gridInstance.minRowsToRender(); @@ -302,12 +302,12 @@ gridInstance.sortColumnsInit(); gridInstance.sortData({}, {}); var test_styleProvider:ngGrid.IStyleProvider = new ngStyleProvider({}, {}); -var test_searchProvider:ngGrid.ISearchProvider = new ngSearchProvider({}, {}, {}); -var test_selectionProvider:ngGrid.ISelectionProvider = new ngSelectionProvider({}, {}, {}); -var test_eventProvider:ngGrid.IEventProvider = new ngEventProvider({}, {}, {}, {}); +var test_searchProvider:ngGrid.ISearchProvider = new ngSearchProvider({}, {}, {}); +var test_selectionProvider:ngGrid.ISelectionProvider = new ngSelectionProvider({}, {}, {}); +var test_eventProvider:ngGrid.IEventProvider = new ngEventProvider({}, {}, {}, {}); var test_aggregate:ngGrid.IAggregate = new ngAggregate({}, {}, 10, true); var test_renderedRange:ngGrid.IRenderedRange = new ngRenderedRange(1, 2); var test_dimension:ngGrid.IDimension = new ngDimension({}); var test_row:ngGrid.IRow = new ngRow({}, {}, {}, 0, {}); -var test_column:ngGrid.IColumn = new ngColumn({}, {}, {}, {}, {}, {}); +var test_column:ngGrid.IColumn = new ngColumn({}, {}, {}, {}, {}, {}); var test_footer:ngGrid.IFooter = new ngFooter({}, {}); diff --git a/ng-grid/ng-grid.d.ts b/ng-grid/ng-grid.d.ts index 3bb3b2daa..0fb267faa 100644 --- a/ng-grid/ng-grid.d.ts +++ b/ng-grid/ng-grid.d.ts @@ -30,9 +30,9 @@ declare module ngGrid { export interface IDomAccessProvider { previousColumn:IColumn; grid:IGridInstance; - changeUserSelect(elm:ng.IAugmentedJQuery, value:string):void; + changeUserSelect(elm:angular.IAugmentedJQuery, value:string):void; focusCellElement($scope:IGridScope, index:number):void; - selectionHandlers($scope:IGridScope, elm:ng.IAugmentedJQuery):void; + selectionHandlers($scope:IGridScope, elm:angular.IAugmentedJQuery):void; } export interface IStyleProviderStatic { @@ -43,7 +43,7 @@ declare module ngGrid { } export interface ISearchProviderStatic { - new($scope:IGridScope, grid:IGridInstance, $filter:ng.IFilterService):ISearchProvider; + new($scope:IGridScope, grid:IGridInstance, $filter:angular.IFilterService):ISearchProvider; } export interface ISearchProvider { @@ -53,7 +53,7 @@ declare module ngGrid { } export interface ISelectionProviderStatic { - new(grid:IGridInstance, $scope:IGridScope, $parse:ng.IParseService):ISelectionProvider; + new(grid:IGridInstance, $scope:IGridScope, $parse:angular.IParseService):ISelectionProvider; } export interface ISelectionProvider { @@ -62,7 +62,7 @@ declare module ngGrid { selectedIndex:number; lastClickedRow:any; ignoreSelectedItemChanges:boolean; - pKeyParser:ng.ICompiledExpression; + pKeyParser:angular.ICompiledExpression; ChangeSelection(rowItem:any, event:any):void; getSelection(entity:any):number; getSelectionIndex(entity:any):number; @@ -71,7 +71,7 @@ declare module ngGrid { } export interface IEventProviderStatic { - new(grid:IGridInstance, $scope:IGridScope, domUtilityService:service.IDomUtilityService, $timeout:ng.ITimeoutService):IEventProvider; + new(grid:IGridInstance, $scope:IGridScope, domUtilityService:service.IDomUtilityService, $timeout:angular.ITimeoutService):IEventProvider; } export interface IEventProvider { @@ -203,7 +203,7 @@ declare module ngGrid { } export interface IColumnStatic { - new(config:IGridOptions, $scope:IGridScope, grid:IGridInstance, domUtilityService:service.IDomUtilityService, $templateCache:ng.ITemplateCacheService, $utils:any):IColumn; + new(config:IGridOptions, $scope:IGridScope, grid:IGridInstance, domUtilityService:service.IDomUtilityService, $templateCache:angular.ITemplateCacheService, $utils:any):IColumn; } export interface IColumn { @@ -251,7 +251,7 @@ declare module ngGrid { setVars(fromCol:IColumn):void; } - export interface IGridScope extends ng.IScope { + export interface IGridScope extends angular.IScope { elementsNeedMeasuring:boolean; columns:any[]; renderedRows:any[]; @@ -292,15 +292,15 @@ declare module ngGrid { } export interface IGridInstance { - $canvas:ng.IAugmentedJQuery; - $viewport:ng.IAugmentedJQuery; - $groupPanel:ng.IAugmentedJQuery; - $footerPanel:ng.IAugmentedJQuery; - $headerScroller:ng.IAugmentedJQuery; - $headerContainer:ng.IAugmentedJQuery; - $headers:ng.IAugmentedJQuery; - $topPanel:ng.IAugmentedJQuery; - $root:ng.IAugmentedJQuery; + $canvas:angular.IAugmentedJQuery; + $viewport:angular.IAugmentedJQuery; + $groupPanel:angular.IAugmentedJQuery; + $footerPanel:angular.IAugmentedJQuery; + $headerScroller:angular.IAugmentedJQuery; + $headerContainer:angular.IAugmentedJQuery; + $headers:angular.IAugmentedJQuery; + $topPanel:angular.IAugmentedJQuery; + $root:angular.IAugmentedJQuery; config:IGridOptions; data:any; elementDims:IElementDimension; @@ -327,9 +327,9 @@ declare module ngGrid { configureColumnWidths():void; fixColumnIndexes():void; fixGroupIndexes():void; - getTemplate(key:string):ng.IPromise; - init():ng.IPromise; - initTemplates():ng.IPromise; + getTemplate(key:string):angular.IPromise; + init():angular.IPromise; + initTemplates():angular.IPromise; minRowsToRender():void; refreshDomSizes():void; resizeOnData(col:IColumn):void; @@ -602,7 +602,7 @@ declare module ngGrid { eventStorage:any; numberOfGrids:number; immediate:number; - AssignGridContainers($scope:IGridScope, rootel:ng.IAugmentedJQuery, grid:IGridInstance):void; + AssignGridContainers($scope:IGridScope, rootel:angular.IAugmentedJQuery, grid:IGridInstance):void; getRealWidth(obj:IDimension):number; UpdateGridLayout($scope:IGridScope, grid:IGridInstance):void; setStyleText(grid:IGridInstance, css:string):void; diff --git a/node-azure/azure.d.ts b/node-azure/azure.d.ts index 91c5c0bf0..7e52a8be3 100644 --- a/node-azure/azure.d.ts +++ b/node-azure/azure.d.ts @@ -832,8 +832,8 @@ declare module "azure" { whereKeys(partitionKey: string, rowKey: string): TableQuery; whereNextKeys(partitionKey: string, rowKey: string): TableQuery; where(condition: string, ...values: string[]): TableQuery; - and(condition: string, ...arguments: string[]): TableQuery; - or(condition: string, ...arguments: string[]): TableQuery; + and(condition: string, ...args: string[]): TableQuery; + or(condition: string, ...args: string[]): TableQuery; top(integer: number): TableQuery; toQueryObject(): any; toPath(): string; diff --git a/nodemailer-direct-transport/nodemailer-direct-transport-tests.ts b/nodemailer-direct-transport/nodemailer-direct-transport-tests.ts new file mode 100644 index 000000000..ef8c78479 --- /dev/null +++ b/nodemailer-direct-transport/nodemailer-direct-transport-tests.ts @@ -0,0 +1,22 @@ +/// + +import directTransport = require('nodemailer-direct-transport'); + +var opts: directTransport.DirectOptions = { + name: "harry" +}; + +var transport: nodemailer.Transport = directTransport(opts); + +// setup e-mail data with unicode symbols +var mailOptions: nodemailer.SendMailOptions = { + from: 'Fred Foo ✔ ', // sender address + to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers + subject: 'Hello ✔', // Subject line + text: 'Hello world ✔', // plaintext body + html: 'Hello world ✔' // html body +}; +transport.send(mailOptions, (error: Error, info: nodemailer.SentMessageInfo): void => { + // nothing +}); + diff --git a/nodemailer-direct-transport/nodemailer-direct-transport.d.ts b/nodemailer-direct-transport/nodemailer-direct-transport.d.ts new file mode 100644 index 000000000..aa04d8ea6 --- /dev/null +++ b/nodemailer-direct-transport/nodemailer-direct-transport.d.ts @@ -0,0 +1,35 @@ +// Type definitions for nodemailer-direct-transport 1.0.2 +// Project: https://github.com/andris9/nodemailer-direct-transport +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare module "nodemailer-direct-transport" { + + module directTransport { + + export interface AuthOptions { + user?: string; + pass?: string; + xoauth2?: any; + } + + export interface DirectOptions { + /** + * optional hostname of the client, used for identifying to the server + */ + name?: string; + /** + * if true, the connection emits all traffic between client and server as 'log' events + */ + debug?: boolean; + } + } + + function directTransport(options: directTransport.DirectOptions): nodemailer.Transport; + + export = directTransport; + +} diff --git a/nodemailer-smtp-pool/nodemailer-smtp-pool-tests.ts b/nodemailer-smtp-pool/nodemailer-smtp-pool-tests.ts new file mode 100644 index 000000000..1970ebab5 --- /dev/null +++ b/nodemailer-smtp-pool/nodemailer-smtp-pool-tests.ts @@ -0,0 +1,23 @@ +/// + +import smtpPool = require('nodemailer-smtp-pool'); + +var opts: smtpPool.SmtpPoolOptions = { + maxConnections: 5, + maxMessages: 10 +}; + +var transport: nodemailer.Transport = smtpPool(opts); + +// setup e-mail data with unicode symbols +var mailOptions: nodemailer.SendMailOptions = { + from: 'Fred Foo ✔ ', // sender address + to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers + subject: 'Hello ✔', // Subject line + text: 'Hello world ✔', // plaintext body + html: 'Hello world ✔' // html body +}; +transport.send(mailOptions, (error: Error, info: nodemailer.SentMessageInfo): void => { + // nothing +}); + diff --git a/nodemailer-smtp-pool/nodemailer-smtp-pool.d.ts b/nodemailer-smtp-pool/nodemailer-smtp-pool.d.ts new file mode 100644 index 000000000..2c9a77932 --- /dev/null +++ b/nodemailer-smtp-pool/nodemailer-smtp-pool.d.ts @@ -0,0 +1,88 @@ +// Type definitions for nodemailer-smtp-pool 1.0.1 +// Project: https://github.com/andris9/nodemailer-smtp-pool +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "nodemailer-smtp-pool" { + import tls = require("tls"); + + module smtpPool { + + export interface AuthOptions { + user?: string; + pass?: string; + xoauth2?: any; + } + + export interface SmtpPoolOptions { + /** + * is the port to connect to (defaults to 25 or 465) + */ + port?: number; + /** + * is the hostname or IP address to connect to (defaults to 'localhost') + */ + host?: string; + /** + * defines if the connection should use SSL (if true) or not (if false) + */ + secure?: boolean; + /** + * defines authentication data (see authentication section below) + */ + auth?: AuthOptions; + /** + * turns off STARTTLS support if true + */ + ignoreTLS?: boolean; + /** + * optional hostname of the client, used for identifying to the server + */ + name?: string; + /** + * is the local interface to bind to for network connections + */ + localAddress?: string; + /** + * how many milliseconds to wait for the connection to establish + */ + connectionTimeout?: number; + /** + * how many milliseconds to wait for the greeting after connection is established + */ + greetingTimeout?: number; + /** + * how many milliseconds of inactivity to allow + */ + socketTimeout?: number; + /** + * if true, the connection emits all traffic between client and server as 'log' events + */ + debug?: boolean; + /** + * defines preferred authentication method, eg. 'PLAIN' + */ + authMethod?: string; + /** + * defines additional options to be passed to the socket constructor, eg. {rejectUnauthorized: true} + */ + tls?: tls.ConnectionOptions; + /** + * (defaults to 5) is the count of maximum simultaneous connections to make against the SMTP server + */ + maxConnections?: number; + /** + * (defaults to 100) limits the message count to be sent using a single connection. After maxMessages messages the connection is dropped and a new one is created for the following messages + */ + maxMessages?: number; + } + } + + + function smtpPool(options: smtpPool.SmtpPoolOptions): nodemailer.Transport; + export = smtpPool; + +} diff --git a/nodemailer-smtp-transport/nodemailer-smtp-transport-tests.ts b/nodemailer-smtp-transport/nodemailer-smtp-transport-tests.ts new file mode 100644 index 000000000..3b0c2e29a --- /dev/null +++ b/nodemailer-smtp-transport/nodemailer-smtp-transport-tests.ts @@ -0,0 +1,23 @@ +/// + +import smtpTransport = require('nodemailer-smtp-transport'); + +var opts: smtpTransport.SmtpOptions = { + host: "localhost", + port: 25 +}; + +var transport: nodemailer.Transport = smtpTransport(opts); + +// setup e-mail data with unicode symbols +var mailOptions: nodemailer.SendMailOptions = { + from: 'Fred Foo ✔ ', // sender address + to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers + subject: 'Hello ✔', // Subject line + text: 'Hello world ✔', // plaintext body + html: 'Hello world ✔' // html body +}; +transport.send(mailOptions, (error: Error, info: nodemailer.SentMessageInfo): void => { + // nothing +}); + diff --git a/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts b/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts new file mode 100644 index 000000000..a12d66991 --- /dev/null +++ b/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts @@ -0,0 +1,79 @@ +// Type definitions for nodemailer-smtp-transport 1.0.2 +// Project: https://github.com/andris9/nodemailer-smtp-transport +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "nodemailer-smtp-transport" { + + import tls = require("tls"); + + module smtpTransport { + export interface AuthOptions { + user?: string; + pass?: string; + xoauth2?: any; + } + + export interface SmtpOptions { + /** + * is the port to connect to (defaults to 25 or 465) + */ + port?: number; + /** + * is the hostname or IP address to connect to (defaults to 'localhost') + */ + host?: string; + /** + * defines if the connection should use SSL (if true) or not (if false) + */ + secure?: boolean; + /** + * defines authentication data (see authentication section below) + */ + auth?: AuthOptions; + /** + * turns off STARTTLS support if true + */ + ignoreTLS?: boolean; + /** + * optional hostname of the client, used for identifying to the server + */ + name?: string; + /** + * is the local interface to bind to for network connections + */ + localAddress?: string; + /** + * how many milliseconds to wait for the connection to establish + */ + connectionTimeout?: number; + /** + * how many milliseconds to wait for the greeting after connection is established + */ + greetingTimeout?: number; + /** + * how many milliseconds of inactivity to allow + */ + socketTimeout?: number; + /** + * if true, the connection emits all traffic between client and server as 'log' events + */ + debug?: boolean; + /** + * defines preferred authentication method, eg. 'PLAIN' + */ + authMethod?: string; + /** + * defines additional options to be passed to the socket constructor, eg. {rejectUnauthorized: true} + */ + tls?: tls.ConnectionOptions; + } + } + + function smtpTransport(options: smtpTransport.SmtpOptions): nodemailer.Transport; + + export = smtpTransport; +} diff --git a/nodemailer/nodemailer-tests.ts b/nodemailer/nodemailer-tests.ts index 94a955e67..1d99046c0 100644 --- a/nodemailer/nodemailer-tests.ts +++ b/nodemailer/nodemailer-tests.ts @@ -1,105 +1,28 @@ -/// /// -var nodemailer: Nodemailer; -var fs: any; -var pathlib: any; +import nodemailer = require('nodemailer'); -// Create an Amazon SES transport object -var transport:Transport = nodemailer.createTransport("SES", { - AWSAccessKeyID: "AWSACCESSKEY", - AWSSecretKey: "/AWS/SECRET", - ServiceUrl: "https://email.us-east-1.amazonaws.com" // optional +// create reusable transporter object using SMTP transport +var transporter: nodemailer.Transporter = nodemailer.createTransport({ + service: 'Gmail', + auth: { + user: 'gmail.user@gmail.com', + pass: 'userpass' + } }); -console.log('SES Configured'); - -// optional DKIM signing - -transport.useDKIM({ - domainName: "do-not-trust.node.ee", // signing domain - keySelector: "dkim", // selector name (in this case there's a dkim._domainkey.do-not-trust.node.ee TXT record set up) - privateKey: fs.readFileSync(pathlib.join(__dirname,"test_private.pem")) -}); - - -// Message object -var message:MailComposer = { - - // sender info - from: 'Sender Name ', - - // Comma separated list of recipients - to: '"Receiver Name" ', - - // Subject of the message - subject: 'Nodemailer is unicode friendly ✔', // - - // plaintext body - text: 'Hello to myself!', - - // HTML body - html: '

Hello to myself

' + - '

Here\'s a nyan cat for you as an embedded attachment:

', - - // An array of attachments - attachments: [ - - // String attachment - { - fileName: 'notes.txt', - contents: 'Some notes about this e-mail', - contentType: 'text/plain' // optional, would be detected from the filename - }, - - // Binary Buffer attachment - { - fileName: 'image.png', - contents: new Buffer('iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/' + - '//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U' + - 'g9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC', 'base64'), - - cid: 'note@node' // should be as unique as possible - }, - - // File Stream attachment - { - fileName: 'nyancat.gif', - filePath: __dirname + "/nyan.gif", - cid: 'nyan@node' // should be as unique as possible - } - ] +// setup e-mail data with unicode symbols +var mailOptions: nodemailer.SendMailOptions = { + from: 'Fred Foo ✔ ', // sender address + to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers + subject: 'Hello ✔', // Subject line + text: 'Hello world ✔', // plaintext body + html: 'Hello world ✔' // html body }; -console.log('Sending Mail'); - -transport.sendMail(message, function (error) { - if (error) { - console.log('Error occured'); - console.log(error.message); - return; - } - console.log('Message sent successfully!'); +// send mail with defined transport object +transporter.sendMail(mailOptions, (error: Error, info: nodemailer.SentMessageInfo): void => { + // nothing }); -// From the SMTP section of https://npmjs.org/package/nodemailer README - -var smptTransport1: Transport = nodemailer.createTransport("SMTP", { - service: "Gmail", // sets automatically host, port and connection security settings - auth: { - user: "gmail.user@gmail.com", - pass: "userpass" - } -}); - -var smtpTransport2: Transport = nodemailer.createTransport("SMTP", { - host: "smtp.gmail.com", // hostname - secureConnection: true, // use SSL - port: 465, // port for secure SMTP - auth: { - user: "gmail.user@gmail.com", - pass: "userpass" - } -}); - diff --git a/nodemailer/nodemailer-types.d.ts b/nodemailer/nodemailer-types.d.ts new file mode 100644 index 000000000..bffa6b301 --- /dev/null +++ b/nodemailer/nodemailer-types.d.ts @@ -0,0 +1,149 @@ +// Type definitions for Nodemailer 1.3.2 +// Project: https://github.com/andris9/Nodemailer +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module nodemailer { + + export interface AttachmentObject { + /** + * filename to be reported as the name of the attached file, use of unicode is allowed + */ + filename?: string; + /** + * optional content id for using inline images in HTML message source + */ + cid?: string; + /** + * Pathname or URL to use streaming + */ + path?: string; + /** + * String, Buffer or a Stream contents for the attachment + */ + content: string|Buffer|NodeJS.ReadableStream; + /** + * If set and content is string, then encodes the content to a Buffer using the specified encoding. Example values: base64, hex, 'binary' etc. Useful if you want to use binary attachments in a JSON formatted e-mail object. + */ + encoding?: string; + /** + * optional content type for the attachment, if not set will be derived from the filename property + */ + contentType?: string; + /** + * optional content disposition type for the attachment, defaults to 'attachment' + */ + contentDisposition?: string; + } + + export interface SendMailOptions { + /** + * The e-mail address of the sender. All e-mail addresses can be plain 'sender@server.com' or formatted 'Sender Name ', see here for details + */ + from?: string; + /** + * An e-mail address that will appear on the Sender: field + */ + sender?: string; + /** + * Comma separated list or an array of recipients e-mail addresses that will appear on the To: field + */ + to?: string|string[]; + /** + * Comma separated list or an array of recipients e-mail addresses that will appear on the Cc: field + */ + cc?: string|string[]; + /** + * Comma separated list or an array of recipients e-mail addresses that will appear on the Bcc: field + */ + bcc?: string|string[]; + /** + * An e-mail address that will appear on the Reply-To: field + */ + replyTo?: string; + /** + * The message-id this message is replying + */ + inReplyTo?: string; + /** + * Message-id list (an array or space separated string) + */ + references?: string|string[]; + /** + * The subject of the e-mail + */ + sbject?: string; + /** + * The plaintext version of the message as an Unicode string, Buffer, Stream or an object {path: '...'} + */ + text?: string|Buffer|NodeJS.ReadableStream|AttachmentObject; + /** + * The HTML version of the message as an Unicode string, Buffer, Stream or an object {path: '...'} + */ + html?: string|Buffer|NodeJS.ReadableStream|AttachmentObject; + /** + * An object or array of additional header fields (e.g. {"X-Key-Name": "key value"} or [{key: "X-Key-Name", value: "val1"}, {key: "X-Key-Name", value: "val2"}]) + */ + headers?: any; + /** + * An array of attachment objects (see below for details) + */ + attachments?: AttachmentObject[]; + /** + * An array of alternative text contents (in addition to text and html parts) (see below for details) + */ + alternatives?: AttachmentObject[]; + /** + * optional Message-Id value, random value will be generated if not set + */ + messageId?: string; + /** + * optional Date value, current UTC string will be used if not set + */ + date?: Date; + /** + * optional transfer encoding for the textual parts (defaults to 'quoted-printable') + */ + encoding?: string; + } + + export interface SentMessageInfo { + /** + * most transports should return the final Message-Id value used with this property + */ + messageId: string; + /** + * includes the envelope object for the message + */ + envelope: any; + /** + * is an array returned by SMTP transports (includes recipient addresses that were accepted by the server) + */ + accepted: string[]; + /** + * is an array returned by SMTP transports (includes recipient addresses that were rejected by the server) + */ + rejected: string[]; + /** + * is an array returned by Direct SMTP transport. Includes recipient addresses that were temporarily rejected together with the server response + */ + pending?: string[]; + /** + * is a string returned by SMTP transports and includes the last SMTP response from the server + */ + response: string; + } + + /** + * This is what you implement to create a new transporter yourself + */ + export interface Transport { + name: string; + version: string; + send(mail: SendMailOptions, callback?: (error: Error, info: SentMessageInfo) => void): void; + close(): void; + } + +} diff --git a/nodemailer/nodemailer.d.ts b/nodemailer/nodemailer.d.ts index a63479e83..e0d1300b0 100644 --- a/nodemailer/nodemailer.d.ts +++ b/nodemailer/nodemailer.d.ts @@ -1,111 +1,63 @@ -// Type definitions for Nodemailer -// Project: https://github.com/andris9/Nodemailer -// Definitions by: Vincent Bortone -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// Nodemailer is an easy to use module to send e-mails with Node.JS (using SMTP or sendmail or Amazon SES) and is unicode friendly . - -declare class Transport { - static transports: { - SMTP: Transport; - SES: Transport; - SENDMAIL: Transport; - STUB: Transport; - }; - - constructor(type: string, options?: any); - options: Object; - transportType: string; - sendMailWithTransport(emailMessage: MailComposer, callback?: (err: Error) => any): any; - useDKIM(dkim: DKIMOptions): void; - close(callback?: (err: Error) => any): any; - sendMail(message: MailComposer, callback?: (err: Error) => any): any; - send_mail(message:MailComposer, callback?: (err: Error) => any): any; -} - -interface NodeMailerAttachment { - fileName: string; - filePath?: string; - contents?: any; - contentType?: string; - cid?: string; -} - -interface MailComposer { - from: string; // sender info - to: string; // Comma separated list of recipients - subject: string; // Subject of the message - headers?: {}; - text?: string; // plaintext body - html?: string; // HTML body - attachments?: NodeMailerAttachment[]; // An array of attachments - forceEmbeddedImages?: boolean; -} - -interface DKIMOptions{ - domainName: string; // signing domain - keySelector: string; // selector name (in this case there's a dkim._domainkey.do-not-trust.node.ee TXT record set up) - privateKey: any; -} - -declare class XOAuthGenerator { - constructor(options: XOAuthGeneratorOptions); - generate(callback: () => any): string; -} - -interface XOAuthGeneratorOptions { - user: string; - consumerKey: string; // optional - consumerSecret: string; // optional - token: string; - tokenSecret: string; -} - -interface XOAuth2Options { - user: string; - clientId: string; - clientSecret: string; - refreshToken: string; -} - -interface NodemailerTransportOptions { - service?: string; - auth?: NodemailerAuthInterface; - debug?: boolean; - AWSAccessKeyID?: string; - AWSSecretKey: string; - ServiceUrl: string; -} - -interface NodemailerAuthInterface { - user?: string; - pass?: string; - XOAuthToken?: XOAuthGenerator; - XOAuth2?: XOAuth2Options; -} - -interface NodemailerSMTPTransportOptions { - service?: string; - host?: string; - port?: number; - secureConnection?: boolean; - name?: string; - auth: NodemailerAuthInterface; - ignoreTLS?: boolean; - debug?: boolean; - maxConnections?: number; -} - - -interface Nodemailer { - createTransport(type: string): Transport; - createTransport(type: string, options: NodemailerTransportOptions): Transport; - createTransport(type: string, options: NodemailerSMTPTransportOptions): Transport; - createTransport(type: string, path: string): Transport; - createXOAuthGenerator(options: XOAuthGeneratorOptions): XOAuthGenerator; -} - -declare module "nodemailer" { - var nodemailer: Nodemailer; - export = nodemailer; -} +// Type definitions for Nodemailer 1.3.2 +// Project: https://github.com/andris9/Nodemailer +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// +/// + +declare module "nodemailer" { + + import directTransport = require("nodemailer-direct-transport"); + import smtpTransport = require("nodemailer-smtp-transport"); + + export type Transport = nodemailer.Transport; + export type SendMailOptions = nodemailer.SendMailOptions; + export type SentMessageInfo = nodemailer.SentMessageInfo; + + /** + * Transporter plugin + */ + export interface Plugin { + (mail: SendMailOptions, callback?: (error: Error, info: SentMessageInfo) => void): void; + } + + /** + * This is what you use to send mail + */ + export interface Transporter { + /** + * Send a mail + */ + sendMail(mail: SendMailOptions, callback?: (error: Error, info: SentMessageInfo) => void): void; + + /** + * Attach a plugin. 'compile' and 'stream' plugins can be attached with use(plugin) method + * + * @param step is a string, either 'compile' or 'stream' thatd defines when the plugin should be hooked + * @param pluginFunc is a function that takes two arguments: the mail object and a callback function + */ + use(step: string, plugin: Plugin): void; + + + /** + * Close all connections + */ + close?(): void; + } + + /** + * Create a direct transporter + */ + export function createTransport(options?: directTransport.DirectOptions): Transporter; + /** + * Create an SMTP transporter + */ + export function createTransport(options?: smtpTransport.SmtpOptions): Transporter; + /** + * Create a transporter from a given implementation + */ + export function createTransport(transport: Transport): Transporter; +} diff --git a/notifyjs/notifyjs-tests.ts b/notifyjs/notifyjs-tests.ts index 8771224c8..1b1d7f906 100644 --- a/notifyjs/notifyjs-tests.ts +++ b/notifyjs/notifyjs-tests.ts @@ -14,6 +14,7 @@ function test_Notify_constructor() { body : "fuga", icon : "./logo.png", tag : "user", + timeout : 1000, notifyShow : (e:Event)=> console.log("notifyShow", e), notifyClose : ()=> console.log("notifyClose"), notifyClick : ()=> console.log("notifyClick"), diff --git a/notifyjs/notifyjs.d.ts b/notifyjs/notifyjs.d.ts index f36b8fbcd..0cff4e0c5 100644 --- a/notifyjs/notifyjs.d.ts +++ b/notifyjs/notifyjs.d.ts @@ -72,6 +72,11 @@ declare module notifyjs { * unique identifier to stop duplicate notifications */ tag? : string; + + /** + * number of seconds to close the notification automatically + */ + timeout? : number; /** * callback when notification is shown diff --git a/object-path/object-path-tests.ts b/object-path/object-path-tests.ts index 5984c78a8..d29cec141 100644 --- a/object-path/object-path-tests.ts +++ b/object-path/object-path-tests.ts @@ -1,68 +1,94 @@ -/// - -var - object = { - one: 1, - two: { - three: 3, - four: ['4'] - } - }, - array: any[] = [], - Null:any = null; - -objectPath.del(array) === ['12']; -objectPath.del(object) === object; -objectPath.del(object) === object; - -objectPath.del() === void 0; -objectPath.del(object, ['1','2','3']); -objectPath.del(object, [1,2,3]); -objectPath.del(object, 1); -objectPath.del(object, 'one').one === 1; - -objectPath.coalesce(object, ['1','2']) === void 0; -objectPath.coalesce(object, ['1',['2','1']]) === void 0; -objectPath.coalesce(object, ['1',['2','1']], 1) === 1; -objectPath.coalesce(object, [1,1], 1) === 1; -objectPath.coalesce(object, >[1,[1,1]], 1) === 1; - -objectPath.ensureExists(object, '1.2', 2); -objectPath.ensureExists(object, 1, 2); -objectPath.ensureExists(object, [1,2], 2); -objectPath.ensureExists(object, ['1','2'], 2); -objectPath.ensureExists(object, ['1','2'], 2) === 3; -objectPath.ensureExists(object, ['1','2'], 2) === [[]]; - -objectPath.push(object, 1, 1,2,3,4); -objectPath.push(object, 1, 1,'2', 3, false); -objectPath.push(object, 'one.four', 1,'2', 3, false); -objectPath.push(object, ['one','two'], [1,'2', 3, false]); - -objectPath.get(array) === array; -objectPath.get(Null) === Null; -objectPath.get() === void 0; -objectPath.get(object, 'one') === 1; -objectPath.get(object, ['two','three']) === 3; -objectPath.get(object, ['three'], 3) === 3; -objectPath.get(object, 'three', 3) === 3; -objectPath.get(object, 0, 3) === 3; -objectPath.get(object, 0, '3') === '3'; -objectPath.get(object, 0, ['1','2']) === ['1','2']; -objectPath.get(object, 0) === 10; - -objectPath.set(object, '1.2', true); -objectPath.set(object, ['1','2'], true); -objectPath.set(object, [1, 2], true); -objectPath.set(object, '1.2', true, true); -objectPath.set(object, '1.2', true, false); -objectPath.set(object, '1.2', true, false) === ['string']; -objectPath.set(object, '1.2', true, false) === object; - -objectPath.insert(object, '1.2', 1); -objectPath.insert(object, ['1','2'], 1); -objectPath.insert(object, 1, 1); -objectPath.insert(object, [1,2], 1); -objectPath.insert(object, '1.2', 1, 2); -objectPath.insert(object, ['1.2'], 1, 6); - +/// + +import ObjectPath = require('object-path'); + +var + object = { + one: 1, + two: { + three: 3, + four: ['4'] + } + }, + array: any[] = [], + Null:any = null; + +var obj = ObjectPath(object); + +obj.del(array); +obj.coalesce([1,2]); +obj.ensureExists('1.2', 1); +obj.push(1, 'value'); +obj.get(array); +obj.set(array, 'value'); +obj.insert(1, 10); + +objectPath.del(array) === ['12']; +objectPath.del(object) === object; +objectPath.del(object) === object; +obj.del() === object; + +objectPath.has(object, ['1','2','3']) === true; +objectPath.has(object, ['1.2.3']) === false; +objectPath.has(object, [1,2,3]) === true; +objectPath.has(object, 1) === false; +objectPath.has() === false; + +objectPath.del() === void 0; +objectPath.del(object, ['1','2','3']); +objectPath.del(object, [1,2,3]); +objectPath.del(object, 1); +objectPath.del(object, 'one').one === 1; +obj.del('one').one === 1; + +objectPath.coalesce(object, ['1','2']) === void 0; +objectPath.coalesce(object, ['1',['2','1']]) === void 0; +objectPath.coalesce(object, ['1',['2','1']], 1) === 1; +objectPath.coalesce(object, [1,1], 1) === 1; +objectPath.coalesce(object, >[1,[1,1]], 1) === 1; +obj.coalesce(>[1,[1,1]], 1) === 1; + +objectPath.ensureExists(object, '1.2', 2); +objectPath.ensureExists(object, 1, 2); +objectPath.ensureExists(object, [1,2], 2); +objectPath.ensureExists(object, ['1','2'], 2); +objectPath.ensureExists(object, ['1','2'], 2) === 3; +objectPath.ensureExists(object, ['1','2'], 2) === [[]]; +obj.ensureExists(['1','2'], 2) === [[]]; + +objectPath.push(object, 1, 1,2,3,4); +objectPath.push(object, 1, 1,'2', 3, false); +objectPath.push(object, 'one.four', 1,'2', 3, false); +objectPath.push(object, ['one','two'], [1,'2', 3, false]); +obj.push(['one','two'], [1,'2', 3, false]); + +objectPath.get(array) === array; +objectPath.get(Null) === Null; +objectPath.get() === void 0; +objectPath.get(object, 'one') === 1; +objectPath.get(object, ['two','three']) === 3; +objectPath.get(object, ['three'], 3) === 3; +objectPath.get(object, 'three', 3) === 3; +objectPath.get(object, 0, 3) === 3; +objectPath.get(object, 0, '3') === '3'; +objectPath.get(object, 0, ['1','2']) === ['1','2']; +objectPath.get(object, 0) === 10; +obj.get(0) === 10; + +objectPath.set(object, '1.2', true); +objectPath.set(object, ['1','2'], true); +objectPath.set(object, [1, 2], true); +objectPath.set(object, '1.2', true, true); +objectPath.set(object, '1.2', true, false); +objectPath.set(object, '1.2', true, false) === ['string']; +objectPath.set(object, '1.2', true, false) === object; +obj.set('1.2', true, false) === object; + +objectPath.insert(object, '1.2', 1); +objectPath.insert(object, ['1','2'], 1); +objectPath.insert(object, 1, 1); +objectPath.insert(object, [1,2], 1); +objectPath.insert(object, '1.2', 1, 2); +objectPath.insert(object, ['1.2'], 1, 6); +obj.insert(['1.2'], 1, 6); + diff --git a/object-path/object-path.d.ts b/object-path/object-path.d.ts index fe38f8702..711a305dc 100644 --- a/object-path/object-path.d.ts +++ b/object-path/object-path.d.ts @@ -1,238 +1,470 @@ -// Type definitions for objectPath v0.6.0 -// Project: https://github.com/mariocasciaro/object-path -// Definitions by: Paulo Cesar -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare var objectPath: objectPath.IObjectPathStatic; - -declare module objectPath { - - interface IStringArray { - [index: number]: string; - } - - interface INumberArray { - [index: number]: number; - } - - interface IObjectPathStatic { - /*======== Del =========*/ - - /** - * Deletes a member from object or array - * @param {object} object - * @param {string[]|string} path - * @return object - */ - del(object: T, path: IStringArray): T; - /** - * @see objectPath.del - */ - del(object: T, path: INumberArray): T; - /** - * @see objectPath.del - */ - del(object: T, path: number): T; - /** - * @see objectPath.del - */ - del(object: T, path: string): T; - /** - * @see objectPath.del - */ - del(object: T): T; - /** - * @see objectPath.del - */ - del():void; - - /*======== Get =========*/ - /** - * Get a path from an object - * @param {object} object - * @param {string|string[]|number|number[]} path - * @param {*} [defaultValue=undefined] - */ - get(object: T, path: string, defaultValue?: TResult): TResult; - /** - * @see objectPath.get - */ - get(object: T, path: IStringArray, defaultValue?: TResult): TResult; - /** - * @see objectPath.get - */ - get(object: T, path: number, defaultValue?: TResult): TResult; - /** - * @see objectPath.get - */ - get(object: T, path: INumberArray, defaultValue?: TResult): TResult; - /** - * @see objectPath.get - */ - get(object: T): T; - /** - * @see objectPath.get - */ - get():void; - - /*======== Set =========*/ - /** - * Set a path to a value - * @param {object} object - * @param {string|string[]|number|number[]} path - * @param {*} value - * @param {boolean} [doNotReplace=false] - * @return Any existing value on the path if any - */ - set(object: T, path: string, value: any, doNotReplace?:boolean): TExisting; - /** - * @see objectPath.set - */ - set(object: T, path: number, value: any, doNotReplace?:boolean): TExisting; - /** - * @see objectPath.set - */ - set(object: T, path: IStringArray, value: any, doNotReplace?:boolean): TExisting; - /** - * @see objectPath.set - */ - set(object: T, path: INumberArray, value: any, doNotReplace?:boolean): TExisting; - /** - * @see objectPath.set - */ - set(object: T): T; - /** - * @see objectPath.set - */ - set():void; - - /*======== Push =========*/ - /** - * Create (if path isn't an array) and push the value to it. Can push unlimited number of values - * @param {object} object - */ - push(object: T, path: INumberArray, ...args:any[]):void; - /** - * @see objectPath.push - */ - push(object: T, path: IStringArray, ...args:any[]):void; - /** - * @see objectPath.push - */ - push(object: T, path: number, ...args:any[]):void; - /** - * @see objectPath.push - */ - push(object: T, path: string, ...args:any[]):void; - /** - * @see objectPath.push - */ - push():void; - - /*======== Coalesce =========*/ - /** - * Get the first non undefined property - * @param {object} object - * @param {string[]|string[][]|number[]|number[][]} paths - * @param {*} defaultValue - * @return {*} - */ - coalesce(object: T, paths: IStringArray, defaultValue?: any):TResult; - /** - * @see objectPath.coalesce - */ - coalesce(object: T, paths: INumberArray, defaultValue?: any):TResult; - /** - * @see objectPath.coalesce - */ - coalesce(object: T, paths: IStringArray[], defaultValue?: any):TResult; - /** - * @see objectPath.coalesce - */ - coalesce(object: T, paths: INumberArray[], defaultValue?: any):TResult; - - /*======== Empty =========*/ - /** - * Empty a path. Arrays are set to length 0, objects have all elements deleted, strings - * are set to empty, numbers to 0, everything else is set to null - * @param {object} object - * @param {string|string[]|number[]} path - */ - empty(object: T, path: string):TResult; - /** - * @see objectPath.empty - */ - empty(object: T, path: INumberArray):TResult; - /** - * @see objectPath.empty - */ - empty(object: T, path: IStringArray):TResult; - /** - * @see objectPath.empty - */ - empty(object: T, path: number):TResult; - /** - * @see objectPath.empty - */ - empty(object: T):T; - /** - * @see objectPath.empty - */ - empty():void; - - /*======== EnsureExists =========*/ - /** - * Set a value if it doesn't exist, do nothing if it does - * @param {object} object - * @param {string|string[]|number|number[]} path - */ - ensureExists(object: T, path: string, value: any):TResult; - /** - * @see objectPath.ensureExists - */ - ensureExists(object: T, path: number, value: any):TResult; - /** - * @see objectPath.ensureExists - */ - ensureExists(object: T, path: INumberArray, value: any):TResult; - /** - * @see objectPath.ensureExists - */ - ensureExists(object: T, path: IStringArray, value: any):TResult; - /** - * @see objectPath.ensureExists - */ - ensureExists(object: T): T; - /** - * @see objectPath.ensureExists - */ - ensureExists():void; - - /*======== Insert =========*/ - /** - * Insert an item in an array path - * @param {object} object - * @param {string|string[]|number|number[]} path - * @param {*} value - * @param {number} [at=0] - */ - insert(object: T, path: string, value: any, at?: number):void; - /** - * @see objectPath.insert - */ - insert(object: T, path: INumberArray, value: any, at?: number):void; - /** - * @see objectPath.insert - */ - insert(object: T, path: IStringArray, value: any, at?: number):void; - /** - * @see objectPath.insert - */ - insert(object: T, path: number, value: any, at?: number):void; - } - -} - -declare module 'objectPath' { - export = objectPath; +// Type definitions for objectPath v0.9.x +// Project: https://github.com/mariocasciaro/object-path +// Definitions by: Paulo Cesar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var objectPath: objectPath.IObjectPathStatic; + +declare module objectPath { + + interface IStringArray { + [index: number]: string; + } + + interface INumberArray { + [index: number]: number; + } + + interface IObjectPathStatic { + /** + * Binds an object + */ + (object: T): IObjectPathBound; + + /*======== Del =========*/ + + /** + * Deletes a member from object or array + * @param {object} object + * @param {string[]|string} path + * @return object + */ + del(object: T, path: IStringArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: INumberArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: number): T; + /** + * @see objectPath.del + */ + del(object: T, path: string): T; + /** + * @see objectPath.del + */ + del(object: T): T; + /** + * @see objectPath.del + */ + del():void; + + /*======== Has =========*/ + /** + * Tests path existence + * @param {object} object + * @param {string[]|string} path + * @return object + */ + has(object: T, path: IStringArray): boolean; + /** + * @see objectPath.has + */ + has(object: T, path: INumberArray): boolean; + /** + * @see objectPath.has + */ + has(object: T, path: string): boolean; + /** + * @see objectPath.has + */ + has(object: T, path: number): boolean; + /** + * @see objectPath.has + */ + has(object: T): boolean; + /** + * @see objectPath.has + */ + has(): boolean; + + /*======== Get =========*/ + /** + * Get a path from an object + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} [defaultValue=undefined] + */ + get(object: T, path: string, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: IStringArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: number, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: INumberArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T): T; + /** + * @see objectPath.get + */ + get():void; + + /*======== Set =========*/ + /** + * Set a path to a value + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {boolean} [doNotReplace=false] + * @return Any existing value on the path if any + */ + set(object: T, path: string, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: number, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: IStringArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: INumberArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T): T; + /** + * @see objectPath.set + */ + set():void; + + /*======== Push =========*/ + /** + * Create (if path isn't an array) and push the value to it. Can push unlimited number of values + * @param {object} object + */ + push(object: T, path: INumberArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: IStringArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: number, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: string, ...args:any[]):void; + /** + * @see objectPath.push + */ + push():void; + + /*======== Coalesce =========*/ + /** + * Get the first non undefined property + * @param {object} object + * @param {string[]|string[][]|number[]|number[][]} paths + * @param {*} defaultValue + * @return {*} + */ + coalesce(object: T, paths: IStringArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: IStringArray[], defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray[], defaultValue?: any):TResult; + + /*======== Empty =========*/ + /** + * Empty a path. Arrays are set to length 0, objects have all elements deleted, strings + * are set to empty, numbers to 0, everything else is set to null + * @param {object} object + * @param {string|string[]|number[]} path + */ + empty(object: T, path: string):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: INumberArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: IStringArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: number):TResult; + /** + * @see objectPath.empty + */ + empty(object: T):T; + /** + * @see objectPath.empty + */ + empty():void; + + /*======== EnsureExists =========*/ + /** + * Set a value if it doesn't exist, do nothing if it does + * @param {object} object + * @param {string|string[]|number|number[]} path + */ + ensureExists(object: T, path: string, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: number, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: INumberArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: IStringArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T): T; + /** + * @see objectPath.ensureExists + */ + ensureExists():void; + + /*======== Insert =========*/ + /** + * Insert an item in an array path + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {number} [at=0] + */ + insert(object: T, path: string, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: INumberArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: IStringArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: number, value: any, at?: number):void; + } + + interface IObjectPathBound { + /*======== Del =========*/ + + /** + * @see objectPath.ensureExists + */ + del(path: IStringArray): T; + /** + * @see objectPath.del + */ + del(path: INumberArray): T; + /** + * @see objectPath.del + */ + del(path: number): T; + /** + * @see objectPath.del + */ + del(path: string): T; + /** + * @see objectPath.del + */ + del(): T; + + /*======== Has =========*/ + /** + * @see objectPath.ensureExists + */ + has(path: IStringArray): boolean; + /** + * @see objectPath.has + */ + has(path: INumberArray): boolean; + /** + * @see objectPath.has + */ + has(path: string): boolean; + /** + * @see objectPath.has + */ + has(path: number): boolean; + /** + * @see objectPath.has + */ + has(): boolean; + + /*======== Get =========*/ + /** + * @see objectPath.ensureExists + */ + get(path: string, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(path: IStringArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(path: number, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(path: INumberArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(): T; + + /*======== Set =========*/ + /** + * @see objectPath.ensureExists + */ + set(path: string, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(path: number, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(path: IStringArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(path: INumberArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(): T; + + /*======== Push =========*/ + /** + * @see objectPath.ensureExists + */ + push(path: INumberArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(path: IStringArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(path: number, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(path: string, ...args:any[]):void; + /** + * @see objectPath.push + */ + push():void; + + /*======== Coalesce =========*/ + /** + * @see objectPath.ensureExists + */ + coalesce(paths: IStringArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(paths: INumberArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(paths: IStringArray[], defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(paths: INumberArray[], defaultValue?: any):TResult; + + /*======== Empty =========*/ + /** + * @see objectPath.ensureExists + */ + empty(path: string):TResult; + /** + * @see objectPath.empty + */ + empty(path: INumberArray):TResult; + /** + * @see objectPath.empty + */ + empty(path: IStringArray):TResult; + /** + * @see objectPath.empty + */ + empty(path: number):TResult; + /** + * @see objectPath.empty + */ + empty():T; + + /*======== EnsureExists =========*/ + /** + * @see objectPath.ensureExists + */ + ensureExists(path: string, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(path: number, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(path: INumberArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(path: IStringArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(): T; + + /*======== Insert =========*/ + /** + * @see objectPath.insert + */ + insert(path: string, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(path: INumberArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(path: IStringArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(path: number, value: any, at?: number):void; + } +} + +// browser version +declare module 'objectPath' { + export = objectPath; +} + +// node version +declare module 'object-path' { + export = objectPath; } \ No newline at end of file diff --git a/on-finished/on-finished-tests.ts b/on-finished/on-finished-tests.ts new file mode 100644 index 000000000..c3956ac6b --- /dev/null +++ b/on-finished/on-finished-tests.ts @@ -0,0 +1,16 @@ +/// +/// + +import events = require('events'); +import onFinished = require('on-finished'); + +function test_finished() { + + var e = new events.EventEmitter(); + + var ret: NodeJS.EventEmitter = onFinished(e, () => { + //callback + }); + + var finished: boolean = onFinished.isFinished(e); +} diff --git a/on-finished/on-finished.d.ts b/on-finished/on-finished.d.ts new file mode 100644 index 000000000..0ca4f2286 --- /dev/null +++ b/on-finished/on-finished.d.ts @@ -0,0 +1,18 @@ +// Type definitions for on-finished v2.2.0 +// Project: https://github.com/jshttp/on-finished +// Definitions by: Honza Dvorsky +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +declare module 'on-finished' { + + function onFinished(msg:NodeJS.EventEmitter, listener:Function): NodeJS.EventEmitter; + + module onFinished { + export function isFinished(msg:NodeJS.EventEmitter):boolean; + } + + export = onFinished; +} diff --git a/on-headers/on-headers-tests.ts b/on-headers/on-headers-tests.ts new file mode 100644 index 000000000..11f33c4ef --- /dev/null +++ b/on-headers/on-headers-tests.ts @@ -0,0 +1,20 @@ +/// + +import http = require('http') +import onHeaders = require('on-headers') + +http.createServer(onRequest) + .listen(3000); + +function onRequest(req: http.ServerRequest, res: http.ServerResponse) { + onHeaders(res, addPoweredBy); + res.setHeader('Content-Type', 'text/plain') + res.end('hello!'); +} + +function addPoweredBy(): void { + // set if not set by end of request + if (!this.getHeader('X-Powered-By')) { + this.setHeader('X-Powered-By', 'Node.js'); + } +} diff --git a/on-headers/on-headers.d.ts b/on-headers/on-headers.d.ts new file mode 100644 index 000000000..bf873fd82 --- /dev/null +++ b/on-headers/on-headers.d.ts @@ -0,0 +1,33 @@ +// Type definitions for serve-favicon 2.1.6 +// Project: https://github.com/jshttp/on-headers +// Definitions by: John Jeffery +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "on-headers" { + import http = require("http"); + + /** + * This will add the listener to fire when headers are emitted for res. + * The listener is passed the response object as its context (this). + * Headers are considered emitted only once, right before they + * are sent to the client. + * + * When this is called multiple times on the same res, the listeners + * are fired in the reverse order they were added. + * + * @param res HTTP server response object + * @param listener Function to call prior to headers being emitted, + * the response object is passed as this context. + */ + function onHeaders(res: http.ServerResponse, listener: Function):void; + + // Note that this definition might be able to be improved in a future + // version of typescript. At the moment it is not possible to declare + // the type of the 'this' context for a function, but it might be included + // in a future typescript version. + // https://github.com/Microsoft/TypeScript/issues/229 + + export = onHeaders; +} \ No newline at end of file diff --git a/onsenui/onsenui-tests.ts b/onsenui/onsenui-tests.ts new file mode 100644 index 000000000..58b72da6e --- /dev/null +++ b/onsenui/onsenui-tests.ts @@ -0,0 +1,216 @@ +/// + +function onsStatic(): void { + ons.ready(function(): void { + alert('Ready!'); + }); + ons.bootstrap(); + ons.enableAutoStatusBarFill(); + ons.disableAutoStatusBarFill(); + ons.findParentComponentUntil('ons-page'); + ons.findComponent('.class1'); + ons.setDefaultDeviceBackButtonListener(null); + ons.disableDeviceBackButtonHandler(); + ons.enableDeviceBackButtonHandler(); + ons.isReady(); + var content: HTMLElement = document.getElementById('#my-content'); + content.innerHTML = 'Test Button'; + ons.compile(content); + ons.isWebView(); + ons.createAlertDialog('myPage.html'); + ons.createDialog('myPage.html'); + ons.createPopover('myPage.html'); + + var options: alertOptions = { + message: 'text message' + }; + ons.notification.alert(options); + ons.notification.confirm(options); + ons.notification.prompt(options); + + var potrait: boolean = ons.orientation.isPortrait(); + var isLandscape: boolean = ons.orientation.isLandscape(); + ons.orientation.on('eventName', null); + ons.orientation.once('eventName', null); + ons.orientation.off('eventName', null); + + var web: boolean = ons.platform.isWebView(); + var ios: boolean = ons.platform.isIOS(); + var iPhone: boolean = ons.platform.isIPhone(); + var iPad: boolean = ons.platform.isIPad(); + var blackBerry: boolean = ons.platform.isBlackBerry(); + var opera: boolean = ons.platform.isOpera(); + var firefox: boolean = ons.platform.isFirefox(); + var safari: boolean = ons.platform.isSafari(); + var chrome: boolean = ons.platform.isChrome(); + var ie: boolean = ons.platform.isIE(); + var ios7above: boolean = ons.platform.isIOS7above(); + +} + +function onsPage(page: PageView): void { + var DBBHandler: any = page.getDeviceBackButtonHandler(); +} + +function onsCarousel(carousel: CarouselView): void { + carousel.next(); + carousel.prev(); + carousel.first(); + carousel.last(); + carousel.setSwipeable(true); + var swipeable: boolean = carousel.isSwipeable(); + carousel.setActiveCarouselItemIndex(0); + carousel.getActiveCarouselItemIndex(); + var autoScrollEnabled: boolean = carousel.isAutoScrollEnabled(); + carousel.setAutoScrollEnabled(true); + carousel.getAutoScrollRatio(); + carousel.setOverscrollable(true); + var overscrollable: boolean = carousel.isOverscrollable(); + carousel.refresh(); + var disabled: boolean = carousel.isDisabled(); + carousel.setDisabled(false); + carousel.on('eventName', null); + carousel.once('eventName', null); + carousel.off('eventName', null); +} + +function onsPullHook(pullHook: PullHookView): void { + pullHook.setDisabled(false); + var disabled: boolean = pullHook.isDisabled(); + pullHook.setHeight(15); + pullHook.setThresholdHeight(4); + pullHook.on('eventName', null); + pullHook.once('eventName', null); + pullHook.off('eventName', null); +} + +function onsSplitView(splitViewVar: SplitView): void { + splitViewVar.setMainPage('myPage.html'); + splitViewVar.setSecondaryPage('myPage2.html'); + splitViewVar.update(); + splitViewVar.on('eventName', null); + splitViewVar.once('eventName', null); + splitViewVar.off('eventName', null); +} + +function onsAlertDialog(alertDialog: AlertDialogView): void { + var options: dialogOptions = { + animation: 'default' + }; + alertDialog.show(options); + alertDialog.hide(options); + var shown: boolean = alertDialog.isShown(); + alertDialog.destroy(); + alertDialog.setCancelable(true); + var cancelable: boolean = alertDialog.isCancelable(); + alertDialog.setDisabled(false); + var disabled: boolean = alertDialog.isDisabled(); + alertDialog.on('eventName', null); + alertDialog.once('eventName', null); + alertDialog.off('eventName', null); +} + +function onsDialog(dialog: DialogView): void { + var options: dialogOptions = { + animation: 'default' + }; + dialog.show(options); + dialog.hide(options); + var shown: boolean = dialog.isShown(); + dialog.destroy(); + var DBBHandler: any = dialog.getDeviceBackButtonHandler(); + dialog.setCancelable(true); + var cancelable: boolean = dialog.isCancelable(); + dialog.setDisabled(false); + var disabled: boolean = dialog.isDisabled(); + dialog.on('eventName', null); + dialog.once('eventName', null); + dialog.off('eventName', null); +} + +function onsButton(button: ButtonView): void { + button.startSpin(); + button.stopSpin(); + var spinning: boolean = button.isSpinning(); + button.setSpinAnimation('slide-left'); + button.setDisabled(false); + var disabled: boolean = button.isDisabled(); +} + +function onsSwitch(switchVar: SwitchView): void { + var checked: boolean = switchVar.isChecked(); + switchVar.setChecked(true); + var checkbox: HTMLElement = switchVar.getCheckboxElement(); + switchVar.on('eventName', null); + switchVar.once('eventName', null); + switchVar.off('eventName', null); +} + +function onsModal(modal: ModalView): void { + modal.toggle(); + modal.show(); + modal.hide(); + var DBBHandler: boolean = modal.getDeviceBackButtonHandler(); +} + +function onsNavigator(navigator: NavigatorView): void { + var options: navigatorOptions = { + animation: 'slide' + }; + navigator.pushPage('myPage.html'); + navigator.insertPage(2, 'myPage2.html'); + navigator.popPage(); + navigator.resetToPage('myPage.html'); + var currentPage: any = navigator.getCurrentPage(); + var pages: objectArray = navigator.getPages(); + var DBBHandler: any = navigator.getDeviceBackButtonHandler(); + navigator.on('eventName', null); + navigator.once('eventName', null); + navigator.off('eventName', null); +} + +function onsSlidingMenu(slidingMenu: SlidingMenuView): void { + var options: slidingMenuOptions = { + closeMenu: true + }; + slidingMenu.setMainPage('myPage.html', options); + slidingMenu.setMenuPage('myMenu.html', options); + slidingMenu.openMenu(options); + slidingMenu.closeMenu(options); + slidingMenu.toggleMenu(options); + var opened: boolean = slidingMenu.isMenuOpened(); + var DBBHandler: any = slidingMenu.getDeviceBackButtonHandler(); + slidingMenu.setSwipeable(true); + slidingMenu.on('eventName', null); + slidingMenu.once('eventName', null); + slidingMenu.off('eventName', null); +} + +function onsTabbar(tabBar: TabbarView): void { + var options: tabbarOptions = { + keepPage: true + }; + tabBar.setActiveTab(2, options); + var activeTab: number = tabBar.getActiveTab(); + tabBar.loadPage('myPage.html'); + tabBar.on('eventName', null); + tabBar.once('eventName', null); + tabBar.off('eventName', null); +} + +function onsPopover(popover: PopoverView): void { + var options: popoverOptions = { + animation: 'fade' + } + popover.show('#element5', options); + popover.hide(options); + var shown: boolean = popover.isShown(); + popover.destroy(); + popover.setCancelable(true); + var cancelable: boolean = popover.isCancelable(); + popover.setDisabled(true); + var disabled: boolean = popover.isDisabled(); + popover.on('eventName', null); + popover.once('eventName', null); + popover.off('eventName', null); +} diff --git a/onsenui/onsenui.d.ts b/onsenui/onsenui.d.ts new file mode 100644 index 000000000..287c8e2f5 --- /dev/null +++ b/onsenui/onsenui.d.ts @@ -0,0 +1,1017 @@ +// Type definitions for Onsen UI +// Project: http://onsen.io +// Definitions by: Fran Dios +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +// Some useful types +interface stringArray { + [index: number]: string; +} + +interface objectArray { + [index: number]: any; +} + + +/** + * @description Should be used as root component of each page. The content inside page component is scrollable + */ +interface PageView { + /** + * @return {Object} Device back button handler + * @description Get the associated back button handler. This method may return null if no handler is assigned + */ + getDeviceBackButtonHandler(): any; +} + +/** + * @description Carousel component + */ +interface CarouselView { + /** + * @description Show next ons-carousel item + */ + next(): void; + /** + * @description Show previous ons-carousel item + */ + prev(): void; + /** + * @description Show first ons-carousel item + */ + first(): void; + /** + * @description Show last ons-carousel item + */ + last(): void; + /** + * @param {Booelan} swipeable If value is true the carousel will be swipeable + * @description Set whether the carousel is swipeable or not + */ + setSwipeable(swipeable: boolean): void; + /** + * @return {Boolean} true if the carousel is swipeable + * @description Returns whether the carousel is swipeable or not + */ + isSwipeable(): boolean; + /** + * @param {Number} index The index that the carousel should be set to + * @description Specify the index of the ons-carousel-item to show + */ + setActiveCarouselItemIndex(index: number): void; + /** + * @return {Number} The current carousel item index + * @description Returns the index of the currently visible ons-carousel-item + */ + getActiveCarouselItemIndex(): number; + /** + * @param {Boolean} enabled If true auto scroll will be enabled + * @description Enable or disable "auto-scroll" attribute + */ + setAutoScrollEnabled(enabled: boolean): void; + /** + * @return {Boolean} true if auto scroll is enabled + * @description Returns whether the "auto-scroll" attribute is set or not + */ + isAutoScrollEnabled(): boolean; + /** + * @param {Number} ratio The desired ratio + * @description Set the auto scroll ratio. Must be a value between 0.0 and 1.0 + */ + setAutoScrollRatio(ratio: number): void; + /** + * @return {Number} The current auto scroll ratio + * @description Returns the current auto scroll ratio + */ + getAutoScrollRatio(): number; + /** + * @param {Boolean} overscrollable If true the carousel will be overscrollable + * @description Set whether the carousel is overscrollable or not + */ + setOverscrollable(overscrollable: boolean): void; + /** + * @return {Boolean} Whether the carousel is overscrollable or not + * @description Returns whether the carousel is overscrollable or not + */ + isOverscrollable(): boolean; + /** + * @description Update the layout of the carousel. Used when adding ons-carousel-items dynamically or to automatically adjust the size + */ + refresh(): void; + /** + * @return {Boolean} Whether the carousel is disabled or not + * @description Returns whether the dialog is disabled or enabled + */ + isDisabled(): boolean; + /** + * @param {Boolean} disabled If true the carousel will be disabled + * @description Disable or enable the dialog + */ + setDisabled(disabled: boolean): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @description Component that adds "pull-to-refresh" to an element + */ +interface PullHookView { + /** + * @param {Boolean} disabled If true the pull hook will be disabled + * @description Disable or enable the component + */ + setDisabled(disabled: boolean): void; + /** + * @return {Boolean} true if the pull hook is disabled + * @description Returns whether the component is disabled or enabled + */ + isDisabled(): boolean; + /** + * @param {Number} height Desired height + * @description Specify the height + */ + setHeight(height: number): void; + /** + * @param {Number} thresholdHeight Desired threshold height + * @description Specify the threshold height + */ + setThresholdHeight(thresholdHeight: number): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @description Divides the screen into a left and right section + */ +interface SplitView { + /** + * @param {String} pageUrl Page URL. Can be either an HTML document or an + * @description Show the page specified in pageUrl in the right section + */ + setMainPage(pageUrl: string): void; + /** + * @param {String} pageUrl Page URL. Can be either an HTML document or an + * @description Show the page specified in pageUrl in the left section + */ + setSecondaryPage(pageUrl: string): void; + /** + * @description Trigger an 'update' event and try to determine if the split behaviour should be changed + */ + update(): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface dialogOptions { + animation?: string; + callback?: any; +} + + +/** + * @modifier android Display an Android style alert dialog + * @description Alert dialog that is displayed on top of the current screen + */ +interface AlertDialogView { + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "fade", "slide" and "none" + * @param {Function} [options.callback] Function to execute after the dialog has been revealed + * @description Show the alert dialog + */ + show(options?: dialogOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "fade", "slide" and "none" + * @param {Function} [options.callback] Function to execute after the dialog has been hidden + * @description Hide the alert dialog + */ + hide(options?: dialogOptions): void; + /** + * @description Returns whether the dialog is visible or not + * @return {Boolean} true if the dialog is currently visible + */ + isShown(): boolean; + /** + * @description Destroy the alert dialog and remove it from the DOM tree + */ + destroy(): void; + /** + * @description Define whether the dialog can be canceled by the user or not + * @param {Boolean} cancelable If true the dialog will be cancelable + */ + setCancelable(cancelable: boolean): void; + /** + * @description Returns whether the dialog is cancelable or not + * @return {Boolean} true if the dialog is cancelable + */ + isCancelable(): boolean; + /** + * @description Disable or enable the alert dialog + * @param {Boolean} disabled If true the dialog will be disabled + */ + setDisabled(disabled: boolean): void; + /** + * @description Returns whether the dialog is disabled or enabled + * @return {Boolean} true if the dialog is disabled + */ + isDisabled(): boolean; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @description Dialog that is displayed on top of current screen + */ +interface DialogView { + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {Function} [options.callback] This function is called after the dialog has been revealed + * @description Show the dialog + */ + show(options?: dialogOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {Function} [options.callback] This functions is called after the dialog has been hidden + * @description Hide the dialog + */ + hide(options?: dialogOptions): void; + /** + * @description Returns whether the dialog is visible or not + * @return {Boolean} true if the dialog is visible + */ + isShown(): boolean; + /** + * @description Destroy the dialog and remove it from the DOM tree + */ + destroy(): void; + /** + * @return {Object} Device back button handler + * @description Retrieve the back button handler for overriding the default behavior + */ + getDeviceBackButtonHandler(): any; + /** + * @param {Boolean} cancelable If true the dialog will be cancelable + * @description Define whether the dialog can be canceled by the user or not + */ + setCancelable(cancelable: boolean): void; + /** + * @description Returns whether the dialog is cancelable or not + * @return {Boolean} true if the dialog is cancelable + */ + isCancelable(): boolean; + /** + * @description Disable or enable the dialog + * @param {Boolean} disabled If true the dialog will be disabled + */ + setDisabled(disabled: boolean): void; + /** + * @description Returns whether the dialog is disabled or enabled + * @return {Boolean} true if the dialog is disabled + */ + isDisabled(): boolean; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @modifier outline Button with outline and transparent background + * @modifier light Button that doesn't stand out + * @modifier quiet Button with no outline and or background + * @modifier cta Button that really stands out + * @modifier large Large button that covers the width of the screen + * @modifier large--quiet Large quiet button + * @modifier large--cta Large call to action button + * @description Button component. If you want to place a button in a toolbar, use ons-toolbar-button or ons-back-button instead + */ +interface ButtonView { + /** + * @description Show spinner on the button + */ + startSpin(): void; + /** + * @description Remove spinner from button + */ + stopSpin(): void; + /** + * @return {Boolean} true if the button is spinning + * @description Return whether the spinner is visible or not + */ + isSpinning(): boolean; + /** + * @description Set spin animation. Possible values are "slide-left" (default), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in" + * @param {String} animation Animation name + */ + setSpinAnimation(animation: string): void; + /** + * @description Disable or enable the button + */ + setDisabled(disabled: boolean): void; + /** + * @return {Boolean} true if the button is disabled + * @description Returns whether the button is disabled or enabled + */ + isDisabled(): boolean; +} + +/** + * @description Switch component + */ +interface SwitchView { + /** + * @return {Boolean} true if the switch is on + * @description Returns true if the switch is ON + */ + isChecked(): boolean; + /** + * @param {Boolean} checked If true the switch will be set to on + * @description Set the value of the switch. isChecked can be either true or false + */ + setChecked(checked: boolean): void; + /** + * @return {HTMLElement} The underlying checkbox element + * @description Get inner input[type=checkbox] element + */ + getCheckboxElement(): HTMLElement; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @description + * Modal component that masks current screen + * Underlying components are not subject to any events while the modal component is shown + */ +interface ModalView { + /** + * @description Toggle modal visibility + */ + toggle(): void; + /** + * @description Show modal + */ + show(): void; + /** + * @description Hide modal + */ + hide(): void; + /** + * @return {Object} Device back button handler + * @description Retrieve the back button handler + */ + getDeviceBackButtonHandler(): any; +} + +interface navigatorOptions { + animation?: string; + onTransitionEnd?: any; +} + +/** + * @description A component that provides page stack management and navigation. This component does not have a visible content + */ +interface NavigatorView { + /** + * @param {String} pageUrl Page URL. Can be either a HTML document or a <ons-template> + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none" + * @param {Function} [options.onTransitionEnd] Function that is called when the transition has ended + * @description Pushes the specified pageUrl into the page stack + */ + pushPage(pageUrl: string, options?: navigatorOptions): void; + /** + * @param {Number} index The index where it should be inserted + * @param {String} pageUrl Page URL. Can be either a HTML document or a <ons-template> + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none" + * @description Insert the specified pageUrl into the page stack with specified index + */ + insertPage(index: number, pageUrl: string, options?: navigatorOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {Function} [options.onTransitionEnd] Function that is called when the transition has ended + * @description Pops the current page from the page stack. The previous page will be displayed + */ + popPage(options?: navigatorOptions): void; + /** + * @param {String} pageUrl Page URL. Can be either a HTML document or an <ons-template> + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none" + * @param {Function} [options.onTransitionEnd] Function that is called when the transition has ended + * @description Clears page stack and adds the specified pageUrl to the page stack + */ + resetToPage(pageUrl: string, options?: navigatorOptions): void; + /** + * @return {Object} Current page object + * @description Get current page's navigator item. Use this method to access options passed by pushPage() or resetToPage() method + */ + getCurrentPage(): any; + /** + * @return {List} List of page objects + * @description Retrieve the entire page stack of the navigator + */ + getPages(): objectArray; + /** + * @return {Object} Device back button handler + * @description Retrieve the back button handler for overriding the default behavior + */ + getDeviceBackButtonHandler(): any; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface slidingMenuOptions { + closeMenu?: boolean; + callback?: any; +} + +/** + * @description Component for sliding UI where one page is overlayed over another page. The above page can be slided aside to reveal the page behind + */ +interface SlidingMenuView { + /** + * @param {String} pageUrl Page URL. Can be either an HTML document or an <ons-template> + * @param {Object} [options] Parameter object + * @param {Boolean} [options.closeMenu] If true the menu will be closed + * @param {Function} [options.callback] Function that is executed after the page has been set + * @description Show the page specified in pageUrl in the main contents pane + */ + setMainPage(pageUrl: string, options?: slidingMenuOptions): void; + /** + * @param {String} pageUrl Page URL. Can be either an HTML document or an <ons-template> + * @param {Object} [options] Parameter object + * @param {Boolean} [options.closeMenu] If true the menu will be closed after the menu page has been set + * @param {Function} [options.callback] This function will be executed after the menu page has been set + * @description Show the page specified in pageUrl in the side menu pane + */ + setMenuPage(pageUrl: string, options?: slidingMenuOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {Function} [options.callback] This function will be called after the menu has been opened + * @description Slide the above layer to reveal the layer behind + */ + openMenu(options?: slidingMenuOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {Function} [options.callback] This function will be called after the menu has been closed + * @description Slide the above layer to hide the layer behind + */ + closeMenu(options?: slidingMenuOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {Function} [options.callback] This function will be called after the menu has been opened or closed + * @description Slide the above layer to reveal the layer behind if it is currently hidden, otherwise, hide the layer behind + */ + toggleMenu(options?: slidingMenuOptions): void; + /** + * @return {Boolean} true if the menu is currently open + * @description Returns true if the menu page is open, otherwise false + */ + isMenuOpened(): boolean; + /** + * @return {Object} Device back button handler + * @description Retrieve the back-button handler + */ + getDeviceBackButtonHandler(): any; + /** + * @param {Boolean} swipeable If true the menu will be swipeable + * @description Specify if the menu should be swipeable or not + */ + setSwipeable(swipeable: boolean): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface tabbarOptions { + keepPage?: boolean; +} + +/** + * @description A component to display a tab bar on the bottom of a page. Used with ons-tab to manage pages using tabs + */ +interface TabbarView { + /** + * @param {Number} index Tab index + * @param {Object} [options] Parameter object + * @param {Boolean} [options.keepPage] If true the page will not be changed + * @param {String} [options.animation] Animation name. Available animations are "fade" and "none" + * @return {Boolean} true if the change was successful + * @description Show specified tab page. Animations and other options can be specified by the second parameter + */ + setActiveTab(index: number, options?: tabbarOptions): boolean; + /** + * @return {Number} The index of the currently active tab + * @description Returns tab index on current active tab. If active tab is not found, returns -1 + */ + getActiveTab(): number; + /** + * @param {String} url Page URL. Can be either an HTML document or an <ons-template> + * @description Displays a new page without changing the active index + */ + loadPage(url: string): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface popoverOptions { + animation?: string; +} + +/** + * @modifier android Display an Android style popover + * @description A component that displays a popover next to an element + */ +interface PopoverView { + /** + * @param {String|Event|HTMLElement} target Target element. Can be either a CSS selector, an event object or a DOM element + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "fade" and "none" + * @description Open the popover and point it at a target. The target can be either an event, a css selector or a DOM element + */ + show(target: any, options?: popoverOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "fade" and "none" + * @description Close the popover + */ + hide(options?: popoverOptions): void; + /** + * @return {Boolean} true if the popover is visible + * @description Returns whether the popover is visible or not + */ + isShown(): boolean; + /** + * @description Destroy the popover and remove it from the DOM tree + */ + destroy(): void; + /** + * @param {Boolean} cancelable If true the popover will be cancelable + * @description Set whether the popover can be canceled by the user when it is shown + */ + setCancelable(cancelable: boolean): void; + /** + * @return {Boolean} true if the popover is cancelable + * @description Returns whether the popover is cancelable or not + */ + isCancelable(): boolean; + /** + * @param {Boolean} disabled If true the popover will be disabled + * @description Disable or enable the popover + */ + setDisabled(disabled: boolean): void; + /** + * @return {Boolean} true if the popover is disabled + * @description Returns whether the popover is disabled or enabled + */ + isDisabled(): boolean; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +//# Onsen Objects + +/** + * @description A global object that's used in Onsen UI. This object can be reached from the AngularJS scope + */ +interface onsStatic { + /** + * @description Method used to wait for app initialization. The callback will not be executed until Onsen UI has been completely initialized + * @param {Function} callback Function that executes after Onsen UI has been initialized + */ + ready(callback: any): void; + /** + * @description Initialize Onsen UI. Can be used to load Onsen UI without using the ng-app attribute from AngularJS + * @param {String} [moduleName] AngularJS module name + * @param {Array} [dependencies] List of AngularJS module dependencies + * @return {Object} An AngularJS module object + */ + bootstrap(moduleName?: string, dependencies?: objectArray): any; + /** + * @description Enable status bar fill feature on iOS7 and above + */ + enableAutoStatusBarFill(): void; + /** + * @description Disable status bar fill feature on iOS7 and above + */ + disableAutoStatusBarFill(): void; + /** + * @param {String} name Name of component, i.e. 'ons-page' + * @param {Object|jqLite|HTMLElement} [dom] $event, jqLite or HTMLElement object + * @return {Object} Component object. Will return null if no component was found + * @description Find parent component object of dom element + */ + findParentComponentUntil(name: string, dom?: any): any; + /** + * @param {String} selector CSS selector + * @param {HTMLElement} [dom] DOM element to search from + * @return {Object} Component object. Will return null if no component was found + * @description Find component object using CSS selector + */ + findComponent(selector: string, dom?: HTMLElement): any; + /** + * @param {Function} listener Function that executes when device back button is pressed + * @description Set default handler for device back button + */ + setDefaultDeviceBackButtonListener(listener: (eventObject: any) => any): void; + /** + * @description Disable device back button event handler + */ + disableDeviceBackButtonHandler(): void; + /** + * @description Enable device back button event handler + */ + enableDeviceBackButtonHandler(): void; + /** + * @return {Boolean} Will be true if Onsen UI is initialized + * @description Returns true if Onsen UI is initialized + */ + isReady(): boolean; + /** + * @param {HTMLElement} dom Element to compile + * @description Compile Onsen UI components + */ + compile(dom: HTMLElement): void; + /** + * @return {Boolean} Will be true if the app is running in Cordova + * @description Returns true if running inside Cordova + */ + isWebView(): boolean; + /** + * @param {String} page Page name. Can be either an HTML file or an containing a component + * @param {Object} [options] Parameter object + * @param {Object} [options.parentScope] Parent scope of the dialog. Used to bind models and access scope methods from the dialog + * @return {Promise} Promise object that resolves to the alert dialog component object + * @description Create a alert dialog instance from a template + */ + createAlertDialog(page: string): any; + /** + * @param {String} page Page name. Can be either an HTML file or an containing a component + * @param {Object} [options] Parameter object + * @param {Object} [options.parentScope] Parent scope of the dialog. Used to bind models and access scope methods from the dialog + * @return {Promise} Promise object that resolves to the dialog component object + * @description Create a dialog instance from a template + */ + createDialog(page: string): any; + /** + * @param {String} page Page name. Can be either an HTML file or an containing a component + * @param {Object} [options] Parameter object + * @param {Object} [options.parentScope] Parent scope of the dialog. Used to bind models and access scope methods from the dialog + * @return {Promise} Promise object that resolves to the popover component object + * @description Create a popover instance from a template + */ + createPopover(page: string): any; + + /** + * @description Utility methods to create different kinds of alert dialogs. There are three methods available: alert, confirm and prompt + */ + notification: onsNotification; + + /** + * @description Utility methods for orientation detection + */ + orientation: onsOrientation; + + /** + * @description Utility methods to detect current platform + */ + platform: onsPlatform; +} + + +interface alertOptions { + message?: string; + messageHTML?: string; + buttonLabel?: string; + buttonLabels?: stringArray; + primaryButtonIndex?: number; + cancelable?: boolean; + animation?: string; + title?: string; + modifier?: string; + callback?: any; +} + +interface onsNotification { + /** + * @param {Object} options Parameter object + * @param {String} [options.message] Alert message + * @param {String} [options.messageHTML] Alert message in HTML + * @param {String} [options.buttonLabel] Label for confirmation button. Default is "OK" + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {String} [options.title] Dialog title. Default is "Alert" + * @param {String} [options.modifier] Modifier for the dialog + * @param {Function} [options.callback] Function that executes after dialog has been closed + * @description + * Display an alert dialog to show the user a message + * The content of the message can be either simple text or HTML + * Must specify either message or messageHTML + */ + alert(options: alertOptions): void; + /** + * @param {Object} options Parameter object + * @param {String} [options.message] Confirmation question + * @param {String} [options.messageHTML] Dialog content in HTML + * @param {Array} [options.buttonLabels] Labels for the buttons. Default is ["Cancel", "OK"] + * @param {Number} [options.primaryButtonIndex] Index of primary button. Default is 1 + * @param {Boolean} [options.cancelable] Whether the dialog is cancelable or not. Default is false + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {String} [options.title] Dialog title. Default is "Confirm" + * @param {String} [options.modifier] Modifier for the dialog + * @param {Function} [options.callback] + * Function that executes after the dialog has been closed + * Argument for the function is the index of the button that was pressed or -1 if the dialog was canceled + * @description + * Display a dialog to ask the user for confirmation + * The default button labels are "Cancel" and "OK" but they can be customized + * Must specify either message or messageHTML + */ + confirm(options: alertOptions): void; + /** + * @param {Object} options Parameter object + * @param {String} [options.message] Prompt question + * @param {String} [options.messageHTML] Dialog content in HTML + * @param {String} [options.buttonLabel] Label for confirmation button. Default is "OK" + * @param {Number} [options.primaryButtonIndex] Index of primary button. Default is 1 + * @param {Boolean} [options.cancelable] Whether the dialog is cancelable or not. Default is false + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {String} [options.title] Dialog title. Default is "Alert" + * @param {String} [options.modifier] Modifier for the dialog + * @param {Function} [options.callback] + * Function that executes after the dialog has been closed + * Argument for the function is the value of the input field or null if the dialog was canceled + * @description + * Display a dialog with a prompt to ask the user a question + * Must specify either message or messageHTML + */ + prompt(options: alertOptions): void; +} + +interface onsOrientation { + /** + * @return {Boolean} Will be true if the current orientation is portrait mode + * @description Returns whether the current screen orientation is portrait or not + */ + isPortrait(): boolean; + /** + * @return {Boolean} Will be true if the current orientation is landscape mode + * @description Returns whether the current screen orientation is landscape or not + */ + isLandscape(): boolean; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface onsPlatform { + /** + * @description Returns whether app is running in Cordova + * @return {Boolean} + */ + isWebView(): boolean; + + /** + * @description Returns whether the OS is iOS + * @return {Boolean} + */ + isIOS(): boolean; + + /** + * @description Returns whether the OS is Android + * @return {Boolean} + */ + isAndroid(): boolean; + + /** + * @description Returns whether the device is iPhone + * @return {Boolean} + */ + isIPhone(): boolean; + + /** + * @description Returns whether the device is iPad + * @return {Boolean} + */ + isIPad(): boolean; + + /** + * @description Returns whether the device is BlackBerry + * @return {Boolean} + */ + isBlackBerry(): boolean; + + /** + * @description Returns whether the browser is Opera + * @return {Boolean} + */ + isOpera(): boolean; + + /** + * @description Returns whether the browser is Firefox + * @return {Boolean} + */ + isFirefox(): boolean; + + /** + * @description Returns whether the browser is Safari + * @return {Boolean} + */ + isSafari(): boolean; + + /** + * @description Returns whether the browser is Chrome + * @return {Boolean} + */ + isChrome(): boolean; + + /** + * @description Returns whether the browser is Internet Explorer + * @return {Boolean} + */ + isIE(): boolean; + + /** + * @description Returns whether the iOS version is 7 or above + * @return {Boolean} + */ + isIOS7above(): boolean; +} + +declare var ons: onsStatic; diff --git a/passport-local/passport-local.d.ts b/passport-local/passport-local.d.ts index 6b3cbef38..d61e51b15 100644 --- a/passport-local/passport-local.d.ts +++ b/passport-local/passport-local.d.ts @@ -13,6 +13,7 @@ declare module 'passport-local' { interface IStrategyOptions { usernameField?: string; passwordField?: string; + passReqToCallback?: boolean; } interface IVerifyOptions { @@ -20,6 +21,7 @@ declare module 'passport-local' { } interface VerifyFunction { + (req: express.Request, username: string, password: string, done: (error: any, user?: any, options?: IVerifyOptions) => void): void; (username: string, password: string, done: (error: any, user?: any, options?: IVerifyOptions) => void): void; } diff --git a/sanitizer/sanitizer-tests.ts b/sanitizer/sanitizer-tests.ts new file mode 100644 index 000000000..6a4c8982d --- /dev/null +++ b/sanitizer/sanitizer-tests.ts @@ -0,0 +1,53 @@ +/// + +import sanitizer = require('sanitizer'); + +// example copied from the tests https://github.com/theSmaw/Caja-HTML-Sanitizer/blob/master/test/test-sanitizer.js#L346 +var events:any[] = []; +var addTextEvent = function(type:string, text:string, param:any) { + var n = events.length; + + if (events[n - 3] === type && events[n - 1] === param) { + events[n - 2] += text; + } else { + events.push(type, text, param); + } +}; + +sanitizer.makeSaxParser({ + startTag: function(name, attribs, param) { + events.push('startTag', name + '[' + attribs.join(';') + ']', param); + }, + + endTag: function(name, param) { + events.push('endTag', name, param); + }, + + pcdata: function(text, param) { + addTextEvent('pcdata', text, param); + }, + + cdata: function(text, param) { + addTextEvent('cdata', text, param); + }, + + rcdata: function(text, param) { + addTextEvent('rcdata', text, param); + }, + + comment: function(text, param) { + events.push('comment', text, param); + }, + + startDoc: function(param) { + events.push('startDoc', '', param); + }, + + endDoc: function(param) { + events.push('endDoc', '', param); + } +}); +sanitizer.escape(''); +sanitizer.sanitize(''); +sanitizer.normalizeRCData(''); +sanitizer.unescapeEntities(''); diff --git a/sanitizer/sanitizer.d.ts b/sanitizer/sanitizer.d.ts new file mode 100644 index 000000000..16d9448c9 --- /dev/null +++ b/sanitizer/sanitizer.d.ts @@ -0,0 +1,27 @@ +// Type definitions for Sanitizer +// Project: https://github.com/theSmaw/Caja-HTML-Sanitizer +// Definitions by: Dave Taylor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'sanitizer' { + export interface ISaxHandler { + startTag(name:string, attribs:string[], param:any):void; + endTag(name:string, param:any):void; + pcdata(text:string, param:any):void; + cdata(text:string, param:any):void; + rcdata(text:string, param:any):void; + comment(text:string, param:any):void; + startDoc(param:any):void; + endDoc(param:any):void; + } + + export function escape(s:string):string; + + export function makeSaxParser(yourHandler:ISaxHandler):(...any:any[])=>any; + + export function normalizeRCData(s:string):string; + + export function sanitize(s:string):string; + + export function unescapeEntities(s:string):string; +} diff --git a/stripe/stripe-node-tests.ts b/stripe/stripe-node-tests.ts new file mode 100644 index 000000000..3217b78fb --- /dev/null +++ b/stripe/stripe-node-tests.ts @@ -0,0 +1,310 @@ +/// + +import StripeNode = require('stripe'); + +var stripe = new StripeNode("sk_test_BF573NobVn98OiIsPAv7A04K"); + +stripe.setApiVersion('2015-02-18'); +stripe.customers.list({ limit: 3 }, function (err, customers) { + // asynchronously called +}); + +stripe.charges.create({ + amount: 400, + currency: "usd", + source: "tok_15V2YhEe31JkLCeQy9iUgsJX", // obtained with Stripe.js + description: "Charge for test@example.com" +}, function (err, charge) { + // asynchronously called +}); + +stripe.charges.retrieve( + "ch_15fvyXEe31JkLCeQOo0SwFk9", + function (err, charge) { + // asynchronously called + } + ); + +stripe.charges.update( + "ch_15fvyXEe31JkLCeQOo0SwFk9", + { + description: "Charge for test@example.com" + }, + function (err, charge) { + // asynchronously called + } + ); + +stripe.charges.capture("ch_15fvyXEe31JkLCeQOo0SwFk9", function (err, charge) { + // asynchronously called +}); + +stripe.charges.list({ limit: 3 }, function (err, charges) { + // asynchronously called +}); + +stripe.charges.createRefund( + "ch_15fvyXEe31JkLCeQOo0SwFk9", + {}, + function (err, refund) { + // asynchronously called + } + ); + +stripe.charges.retrieveRefund( + "ch_15fvyXEe31JkLCeQOo0SwFk9", + "re_15jzA4Ee31JkLCeQcxbTbjaL", + function (err, refund) { + // asynchronously called + } + ); + +stripe.charges.updateRefund( + "ch_15fvyXEe31JkLCeQOo0SwFk9", + "re_15jzA4Ee31JkLCeQcxbTbjaL", + { metadata: { key: "value" } }, + function (err, refund) { + // asynchronously called + } + ); + +stripe.charges.listRefunds('ch_15fvyXEe31JkLCeQOo0SwFk9', null, function (err, refunds) { + // asynchronously called +}); + +stripe.customers.create({ + description: 'Customer for test@example.com', + source: "tok_15V2YhEe31JkLCeQy9iUgsJX" // obtained with Stripe.js +}, function (err, customer) { + // asynchronously called + }); + +stripe.customers.retrieve( + "cus_5rfJKDJkuxzh5Q", + function (err, customer) { + // asynchronously called + } + ); + +stripe.customers.update("cus_5rfJKDJkuxzh5Q", { + description: "Customer for test@example.com" +}, function (err, customer) { + // asynchronously called + }); + +stripe.customers.del( + "cus_5rfJKDJkuxzh5Q", + function (err, confirmation) { + // asynchronously called + } + ); + +stripe.customers.list({ limit: 3 }, function (err, customers) { + // asynchronously called +}); + +stripe.customers.createCard( + "cus_5rfJKDJkuxzh5Q", + { card: "tok_15V2YhEe31JkLCeQy9iUgsJX" }, + function (err, card) { + // asynchronously called + } + ); + +stripe.customers.retrieveCard( + "cus_5rfJKDJkuxzh5Q", + "card_15fvyXEe31JkLCeQ9KMktP5S", + function (err, card) { + // asynchronously called + } + ); + +stripe.customers.retrieveCard( + "cus_5rfJKDJkuxzh5Q", + "card_15fvyXEe31JkLCeQ9KMktP5S", + function (err, card) { + // asynchronously called + } + ); + +stripe.customers.updateCard( + "cus_5rfJKDJkuxzh5Q", + "card_15fvyXEe31JkLCeQ9KMktP5S", + { name: "Jane Austen" }, + function (err, card) { + // asynchronously called + } + ); + +stripe.customers.updateCard( + "cus_5rfJKDJkuxzh5Q", + "card_15fvyXEe31JkLCeQ9KMktP5S", + { name: "Jane Austen" }, + function (err, card) { + // asynchronously called + } + ); + +stripe.customers.deleteCard( + "cus_5rfJKDJkuxzh5Q", + "card_15fvyXEe31JkLCeQ9KMktP5S", + function (err, confirmation) { + // asynchronously called + } + ); + +stripe.customers.listCards('cu_15fvyVEe31JkLCeQvr155iqc', null, function (err, cards) { + // asynchronously called +}); + +stripe.customers.retrieveSubscription( + "cus_5rfJKDJkuxzh5Q", + "sub_5rfJxnBLGSwsYp", + function (err, subscription) { + // asynchronously called + } + ); + +stripe.customers.updateSubscription( + "cus_5rfJKDJkuxzh5Q", + "sub_5rfJxnBLGSwsYp", + { plan: "platypi-dev" }, + function (err, subscription) { + // asynchronously called + } + ); + +stripe.customers.cancelSubscription( + "cus_5rfJKDJkuxzh5Q", + "sub_5rfJxnBLGSwsYp", + null, + function (err, confirmation) { + // asynchronously called + } + ); + +stripe.customers.listSubscriptions('cu_15fvyVEe31JkLCeQvr155iqc', null, function (err, subscriptions) { + // asynchronously called +}); + +stripe.plans.create({ + amount: 2000, + interval: "month", + name: "Amazing Gold Plan", + currency: "usd", + id: "gold" +}, function (err, plan) { + // asynchronously called + }); + +stripe.plans.retrieve( + "platypi-dev", + function (err, plan) { + // asynchronously called + } + ); + +stripe.plans.update("platypi-dev", { + name: "New plan name" +}, function (err, plan) { + // asynchronously called + }); + +stripe.plans.del( + "platypi-dev", + function (err, confirmation) { + // asynchronously called + } + ); + +stripe.plans.list(null, function (err, plans) { + // asynchronously called +}); + +stripe.coupons.create({ + percent_off: 25, + duration: 'repeating', + duration_in_months: 3, + id: '25OFF' +}, function (err, coupon) { + // asynchronously called + }); + +stripe.coupons.retrieve( + "25OFF", + function (err, coupon) { + // asynchronously called + } + ); + +stripe.coupons.update("25OFF", { + metadata: { key: "value" } +}, function (err, coupon) { + // asynchronously called + }); + +stripe.coupons.del("25OFF", function (err, confirmation) { + +}); + +stripe.coupons.list({ limit: 3 }, function (err, coupons) { + // asynchronously called +}); + +stripe.customers.deleteDiscount("cus_5rfJKDJkuxzh5Q", function (err, confirmation) { + // asynchronously called +}); + +stripe.customers.deleteSubscriptionDiscount("cus_5rfJKDJkuxzh5Q", "sub_5rfJxnBLGSwsYp", function (err, confirmation) { + // asynchronously called +}); + +stripe.invoices.create({ + customer: "cus_5rfJKDJkuxzh5Q" +}, function (err, invoice) { + // asynchronously called + }); + +stripe.invoices.retrieve( + "in_15fvyXEe31JkLCeQH7QbgZZb", + function (err, invoice) { + // asynchronously called + } + ); + +stripe.invoices.retrieveLines( + "in_15fvyXEe31JkLCeQH7QbgZZb", + { limit: 5 }, + function (err, lines) { + // asynchronously called + } + ); + +stripe.invoices.retrieveUpcoming( + "cus_5rfJKDJkuxzh5Q", + null, + function (err, upcoming) { + // asynchronously called + } + ); + +stripe.invoices.update( + "in_15fvyXEe31JkLCeQH7QbgZZb", + { + closed: true + }, + function (err, invoice) { + // asynchronously called + } + ); + +stripe.invoices.pay("in_15fvyXEe31JkLCeQH7QbgZZb", function (err, invoice) { + // asynchronously called +}); + +stripe.invoices.list( + { customer: "cus_5rfJKDJkuxzh5Q", limit: 3 }, + function (err, invoices) { + // asynchronously called + } + ); diff --git a/stripe/stripe-node.d.ts b/stripe/stripe-node.d.ts new file mode 100644 index 000000000..cb5932086 --- /dev/null +++ b/stripe/stripe-node.d.ts @@ -0,0 +1,3107 @@ +// Type definitions for stripe-node +// Project: https://github.com/stripe/stripe-node/ +// Definitions by: William Johnston +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'stripe' { + var out: typeof StripeNode.Stripe; + export = out; +} + +declare module StripeNode { + class Stripe { + static DEFAULT_HOST: string; + static DEFAULT_PORT: string; + static DEFAULT_BASE_PATH: string; + static DEFAULT_API_VERSION: string; + static DEFAULT_TIMEOUT: number; + static PACKAGE_VERSION: string; + static USER_AGENT: { + bindings_version: string; + lang: string; + lang_version: string; + platform: string; + publisher: string; + uname: string; + }; + static USER_AGENT_SERIALIZED: string; + + static resources: typeof resources; + static StripeResource: typeof StripeResource; + + account: resources.Account; + balance: resources.Balance; + charges: resources.Charges; + coupons: resources.Coupons; + customers: resources.Customers; + events: resources.Events; + invoices: resources.Invoices; + invoiceItems: resources.InvoiceItems; + plans: resources.Plans; + recipientCards: resources.RecipientCards; + recipients: resources.Recipients; + tokens: resources.Tokens; + yransfers: resources.Transfers; + applicationFees: resources.ApplicationFees; + fileUploads: resources.FileUploads; + bitcoinReceivers: resources.BitcoinReceivers; + customerCards: resources.CustomerCards; + customerSubscriptions: resources.CustomerSubscriptions; + chargeRefunds: resources.ChargeRefunds; + applicationFeeRefunds: resources.ApplicationFeeRefunds; + transferReversals: resources.TransferReversals; + + constructor(apiKey: string, version?: string); + + setHost(host: string): void; + setHost(host: string, port: string|number): void; + setHost(host: string, port: string|number, protocol: string): void; + + setProtocol(protocol: string): void; + setPort(port: string|number): void; + setApiVersion(version?: string): void; + setApiKey(key?: string): void; + setTimeout(timeout?: number): void; + setHttpAgent(agent: string): void; + getConstant(c: string): any; + getClientUserAgent(response: (userAgent: string) => void): void; + } + + module account { } + + module balance { + interface IBalanceTransaction { + id: string; + + /** + * Value is 'balance_transaction' + */ + object: string; + + /** + * Gross amount of the transaction, in cents. + */ + amount: number; + + /** + * The date the transaction’s net funds will become available in the Stripe balance. + */ + available_on: number; + created: number; + + /** + * Three-letter ISO currency code representing the currency. + */ + currency: string; + + /** + * Fee (in cents) paid for this transaction + */ + fee: number; + + /** + * Detailed breakdown of fees (in cents) paid for this transaction + */ + fee_details: Array<{ + amount: number; + + /** + * Three-letter ISO currency code representing the currency of the amount that was disputed. + */ + currency: string; + + /** + * Type of the fee, one of: application_fee, stripe_fee or tax. + */ + type: string; + application: string; + description: string; + }>; + + /** + * Net amount of the transaction, in cents. + */ + net: number; + + /** + * If the transaction’s net funds are available in the Stripe balance yet. Either available or pending. + */ + status: string; + + /** + * Type of the transaction, one of: charge, refund, adjustment, application_fee, + * application_fee_refund, transfer, transfer_cancel or transfer_failure. + */ + type: string; + description?: string; + + /** + * The Stripe object this transaction is related to. + */ + source?: IPaymentToken | ICard; + source_transfers: IList; + } + } + + module charges { + + /** + * To charge a credit or a debit card, you create a charge object. You can retrieve and refund individual + * charges as well as list all charges. Charges are identified by a unique random ID. + */ + interface ICharge { + id: string; + + /** + * Value is 'charge' + */ + object: string; + + livemode: boolean; + + /** + * Amount charged in cents, positive integer or zero. + */ + amount: number; + + /** + * If the charge was created without capturing, this boolean represents whether or not it is + * still uncaptured or has since been captured. + */ + captured: boolean; + + created: number; + + /** + * Three-letter ISO currency code representing the currency in which the charge was made. + */ + currency: string; + + paid: boolean; + + /** + * Whether or not the charge has been fully refunded. If the charge is only partially refunded, + * this attribute will still be false. + */ + refunded: boolean; + + /** + * A list of refunds that have been applied to the charge. + */ + refunds: IList; + + /** + * For most Stripe users, the source of every charge is a credit or debit card. + * This hash is then the card object describing that card. + */ + source: ICard; + + /** + * The status of the payment is either succeeded or failed. + */ + status: string; + + /** + * Amount in cents refunded (can be less than the amount attribute on the charge if a partial refund was issued). + */ + amount_refunded: number; + + /** + * ID of the balance transaction that describes the impact of this charge on your account balance (not including refunds or disputes). + */ + balance_transaction: string; + + /** + * ID of the customer this charge is for if one exists. + */ + customer: string; + description?: string; + + /** + * Details about the dispute if the charge has been disputed. + */ + dispute?: IDispute; + + /** + * Error code explaining reason for charge failure if available (see the errors section for a list of + * codes: https://stripe.com/docs/api#errors). + */ + failure_code: string; + + /** + * Message to user further explaining reason for charge failure if available. + */ + failure_message: string; + + /** + * ID of the invoice this charge is for if one exists. + */ + invoice: string; + metadata: IMetadata; + + /** + * This is the email address that the receipt for this charge was sent to. + */ + receipt_email: string; + + /** + * This is the transaction number that appears on email receipts sent for this charge. + */ + receipt_number: string; + application_fee?: string; + + /** + * Hash with information on fraud assessments for the charge. + */ + fraud_details: { + /** + * Assessments reported by you have the key user_report and, if set, possible values of safe and fraudulent. + */ + user_report?: string; + + /** + * Assessments from Stripe have the key stripe_report and, if set, the value fraudulent. + */ + stripe_report?: string; + }; + + /** + * Shipping information for the charge. + */ + shipping?: IShippingInformation; + } + } + + module coupons { + /** + * A discount represents the actual application of a coupon to a particular customer. It contains information + * about when the discount began and when it will end. + */ + interface IDiscount { + /** + * Value is 'discount' + */ + object: string; + + /** + * Hash describing the coupon applied to create this discount + */ + coupon: ICoupon; + customer: string; + + /** + * Date that the coupon was applied + */ + start: number; + + /** + * If the coupon has a duration of once or repeating, the date that this discount will end. If the coupon + * used has a forever duration, this attribute will be null. + */ + end: number; + + /** + * The subscription that this coupon is applied to, if it is applied to a particular subscription + */ + subscription: string; + } + + /** + * A coupon contains information about a percent-off or amount-off discount you might want to apply to a customer. + * Coupons only apply to invoices; they do not apply to one-off charges. + */ + interface ICoupon { + id: string; + + /** + * Value is 'coupon' + */ + object: string; + livemode: boolean; + created: number; + + /** + * One of forever, once, and repeating. Describes how long a customer who applies this coupon will get the discount. + */ + duration: string; + + /** + * Amount (in the currency specified) that will be taken off the subtotal of any invoices for this customer. + */ + amount_off: number; + + /** + * If amount_off has been set, the currency of the amount to take off. + */ + currency: string; + + /** + * If duration is repeating, the number of months the coupon applies. Null if coupon duration is forever or once. + */ + duration_in_months: number; + + /** + * Maximum number of times this coupon can be redeemed, in total, before it is no longer valid. + */ + max_redemptions: number; + + /** + * A set of key/value pairs that you can attach to a coupon object. It can be useful for storing + * additional information about the coupon in a structured format. + */ + metadata: IMetadata; + + /** + * Percent that will be taken off the subtotal of any invoices for this customer for the duration + * of the coupon. For example, a coupon with percent_off of 50 will make a $100 invoice $50 instead. + */ + percent_off: number; + + /** + * Date after which the coupon can no longer be redeemed + */ + redeem_by: number; + + /** + * Number of times this coupon has been applied to a customer. + */ + times_redeemed: number; + + /** + * Taking account of the above properties, whether this coupon can still be applied to a customer + */ + valid: boolean; + } + } + module customers { + /** + * Customer objects allow you to perform recurring charges and track multiple charges that are associated + * with the same customer. The API allows you to create, delete, and update your customers. You can + * retrieve individual customers as well as a list of all your customers. + */ + interface ICustomer { + id: string; + + /** + * Value is 'customer' + */ + object: string; + livemode: boolean; + created: number; + + /** + * Current balance, if any, being stored on the customer’s account. If negative, the customer has credit to apply to + * the next invoice. If positive, the customer has an amount owed that will be added to the next invoice. The balance + * does not refer to any unpaid invoices; it solely takes into account amounts that have yet to be successfully applied + * to any invoice. This balance is only taken into account for recurring charges. + */ + account_balance?: number; + + /** + * The currency the customer can be charged in for recurring billing purposes (subscriptions, invoices, invoice items). + */ + currency: string; + + /** + * ID of the default source attached to this customer. + */ + default_source: string; + + /** + * Whether or not the latest charge for the customer’s latest invoice has failed + */ + delinquent: boolean; + + /** + * Describes the current discount active on the customer, if there is one. + */ + discount: coupons.IDiscount; + description?: string; + email?: string; + + /** + * A set of key/value pairs that you can attach to a customer object. It can be useful for storing + * additional information about the customer in a structured format. + */ + metadata?: IMetadata; + + sources?: IList; + + /** + * The customer’s current subscriptions, if any + */ + subscriptions: IList; + } + } + module events { } + module invoices { + /** + * Invoices are statements of what a customer owes for a particular billing period, including subscriptions, + * invoice items, and any automatic proration adjustments if necessary. Once an invoice is created, payment + * is automatically attempted. Note that the payment, while automatic, does not happen exactly at the time of + * invoice creation. If you have configured webhooks, the invoice will wait until one hour after the last + * webhook is successfully sent (or the last webhook times out after failing). Any customer credit on the + * account is applied before determining how much is due for that invoice (the amount that will be actually + * charged). If the amount due for the invoice is less than 50 cents (the minimum for a charge), we add the + * amount to the customer's running account balance to be added to the next invoice. If this amount is + * negative, it will act as a credit to offset the next invoice. Note that the customer account balance does + * not include unpaid invoices; it only includes balances that need to be taken into account when calculating + * the amount due for the next invoice. + */ + interface IInvoice { + id: string; + + /** + * Value is 'invoice' + */ + object: string; + livemode: boolean; + + /** + * Final amount due at this time for this invoice. If the invoice’s total is smaller than the minimum charge + * amount, for example, or if there is account credit that can be applied to the invoice, the amount_due may + * be 0. If there is a positive starting_balance for the invoice (the customer owes money), the amount_due + * will also take that into account. The charge that gets generated for the invoice will be for the amount + * specified in amount_due. + */ + amount_due: number; + + /** + * Number of payment attempts made for this invoice, from the perspective of the payment retry schedule. Any + * payment attempt counts as the first attempt, and subsequently only automatic retries increment the attempt + * count. In other words, manual payment attempts after the first attempt do not affect the retry schedule. + */ + attempt_count: number; + + /** + * Whether or not an attempt has been made to pay the invoice. An invoice is not attempted until 1 hour after + * the invoice.created webhook, for example, so you might not want to display that invoice as unpaid to your + * users. + */ + attempted: boolean; + + /** + * Whether or not the invoice is still trying to collect payment. An invoice is closed if it’s either paid or + * it has been marked closed. A closed invoice will no longer attempt to collect payment. + */ + closed: boolean; + currency: string; + customer: string; + date: number; + + /** + * Whether or not the invoice has been forgiven. Forgiving an invoice instructs us to update the subscription + * status as if the invoice were succcessfully paid. Once an invoice has been forgiven, it cannot be unforgiven + * or reopened + */ + forgiven: boolean; + + /** + * The individual line items that make up the invoice + */ + lines: IList; + + /** + * Whether or not payment was successfully collected for this invoice. An invoice can be paid (most commonly) + * with a charge or with credit from the customer’s account balance. + */ + paid: boolean; + + /** + * End of the usage period during which invoice items were added to this invoice + */ + period_end: number; + + /** + * Start of the usage period during which invoice items were added to this invoice + */ + period_start: number; + + /** + * Starting customer balance before attempting to pay invoice. If the invoice has not been attempted yet, + * this will be the current customer balance. + */ + starting_balance: number; + + /** + * Total of all subscriptions, invoice items, and prorations on the invoice before any discount is applied + */ + subtotal: number; + + /** + * Total after discount + */ + total: number; + + /** + * The fee in cents that will be applied to the invoice and transferred to the application owner’s + * Stripe account when the invoice is paid. + */ + application_fee: number; + + /** + * ID of the latest charge generated for this invoice, if any. + */ + charge: string; + description: string; + discount: coupons.IDiscount; + + /** + * Ending customer balance after attempting to pay invoice. If the invoice has not been attempted yet, + * this will be null. + */ + ending_balance: number; + + /** + * The time at which payment will next be attempted. + */ + next_payment_attempt: number; + + /** + * This is the transaction number that appears on email receipts sent for this invoice. + */ + receipt_number: string; + + /** + * Extra information about an invoice for the customer’s credit card statement. + */ + statement_descriptor: string; + + /** + * The subscription that this invoice was prepared for, if any. + */ + subscription: string; + + /** + * The time at which webhooks for this invoice were successfully delivered (if the invoice had no webhooks to + * deliver, this will match date). Invoice payment is delayed until webhooks are delivered, or until all webhook + * delivery attempts have been exhausted. + */ + webhooks_delivered_at: number; + + /** + * A set of key/value pairs that you can attach to an invoice object. It can be useful for storing additional + * information about the invoice in a structured format. + */ + metadata: IMetadata; + + /** + * The amount of tax included in the total, calculated from tax_percent and the subtotal. If no tax_percent + * is defined, this value will be null. + */ + tax: number; + + /** + * This percentage of the subtotal has been added to the total amount of the invoice, including invoice line + * items and discounts. This field is inherited from the subscription’s tax_percent field, but can be changed + * before the invoice is paid. This field defaults to null. + */ + tax_percent: number; + } + } + module invoiceItems { + interface InvoiceLineItem { + /** + * The ID of the source of this line item, either an invoice item or a subscription + */ + id: string; + + /** + * Value is 'line_item' + */ + object: string; + + /** + * Whether or not this is a test line item + */ + livemode: boolean; + + /** + * The amount, in cents + */ + amount: number; + currency: string; + + /** + * If true, discounts will apply to this line item. Always false for prorations. + */ + discountable: boolean; + + /** + * The period this line_item covers + */ + period: { + /** + * The period start date + */ + start: number; + /** + * The period end date + */ + end: number; + }; + + /** + * Whether or not this is a proration + */ + proration: boolean; + + /** + * A string identifying the type of the source of this line item, either an invoiceitem or a subscription + */ + type: string; + + /** + * A text description of the line item, if the line item is an invoice item + */ + description: string; + + /** + * Key-value pairs attached to the line item, if the line item is an invoice item + */ + metadata: IMetadata; + + /** + * The plan of the subscription, if the line item is a subscription or a proration + */ + plan: plans.IPlan; + + /** + * The quantity of the subscription, if the line item is a subscription or a proration + */ + quantity: number; + + /** + * When type is invoiceitem, the subscription that the invoice item pertains to, if any. Left blank when + * type is already subscription, as it’d be redundant with id. + */ + subscription: string; + } + } + module plans { + /** + * A subscription plan contains the pricing information for different products and feature levels on your site. + * For example, you might have a $10/month plan for basic features and a different $20/month plan for premium features. + */ + interface IPlan { + id: string; + + /** + * Value is 'plan' + */ + object: string; + livemode: boolean; + + /** + * The amount in cents to be charged on the interval specified + */ + amount: number; + created: number; + + /** + * Currency in which subscription will be charged + */ + currency: string; + + /** + * One of day, week, month or year. The frequency with which a subscription should be billed. + */ + interval: string; + + /** + * The number of intervals (specified in the interval property) between each subscription billing. For example, + * interval=month and interval_count=3 bills every 3 months. + */ + interval_count: number; + + /** + * Display name of the plan + */ + name: string; + + /** + * A set of key/value pairs that you can attach to a plan object. It can be useful for storing additional information + * about the plan in a structured format. + */ + metadata: IMetadata; + + /** + * Number of trial period days granted when subscribing a customer to this plan. Null if the plan has no trial period. + */ + trial_period_days: number; + + /** + * Extra information about a charge for the customer’s credit card statement. + */ + statement_descriptor: string; + } + } + module recipientCards { } + module recipients { } + module tokens { } + module transfers { + interface ITransfer { + id: string; + object: string; + livemode: boolean; + + /** + * Amount (in cents) to be transferred to your bank account + */ + amount: number; + + /** + * Time that this record of the transfer was first created. + */ + created: number; + + /** + * Three-letter ISO currency code representing the currency. + */ + currency: string; + + /** + * Date the transfer is scheduled to arrive in the bank. This doesn’t factor in delays like weekends or bank holidays. + */ + date: number; + + /** + * A list of reversals that have been applied to the transfer. + */ + reversals: IList; + + /** + * Whether or not the transfer has been fully reversed. If the transfer is only partially reversed, this attribute + * will still be false. + */ + reversed: boolean; + + /** + * Current status of the transfer (paid, pending, canceled or failed). A transfer will be pending until it is submitted, at which + * point it becomes paid. If it does not go through successfully, its status will change to failed or canceled. + */ + status: string; + + /** + * The type of this type of this transfer. Can be card or bank_account. + */ + type: string; + + /** + * Amount in cents reversed (can be less than the amount attribute on the transfer if a partial reversal was issued). + */ + amount_reversed: number; + + /** + * Balance transaction that describes the impact of this transfer on your account balance. + */ + balance_transaction: string; + + /** + * Internal-only description of the transfer + */ + description: string; + + /** + * Error code explaining reason for transfer failure if available. See Types of transfer failures for a + * list of failure codes: https://stripe.com/docs/api#transfer_failures + */ + failure_code: string; + + /** + * Message to user further explaining reason for transfer failure if available. + */ + failure_message: string; + metadata: IMetadata; + application_fee: string; + + /** + * Hash describing the bank account this transfer was sent to + */ + bank_account: IBankAccount; + + /** + * Hash describing the debit card this transfer was sent to + */ + card: ICard; + + /** + * ID of the recipient this transfer is for if one exists. Transfers to your bank account do not have a recipient. + */ + recipient: string; + source_transaction: string; + + /** + * Extra information about a transfer to be displayed on the user’s bank statement. + */ + statement_descriptor: string; + } + } + module applicationFees { } + module fileUploads { } + module bitcoinReceivers { + /** + * A Bitcoin receiver wraps a Bitcoin address so that a customer can push a payment to you. This guide describes how to use + * receivers to create Bitcoin payments. + */ + interface IBitcoinReceiver { + id: string; + + /** + * Value is 'bitcoin_receiver' + */ + object: string; + livemode: boolean; + + /** + * True when this bitcoin receiver has received a non-zero amount of bitcoin. + */ + active: boolean; + + /** + * The amount of currency that you are collecting as payment. + */ + amount: number; + + /** + * The amount of currency to which bitcoin_amount_received has been converted. + */ + amount_received: number; + + /** + * The amount of bitcoin that the customer should send to fill the receiver. The bitcoin_amount is denominated in Satoshi: + * there are 10^8 Satoshi in one bitcoin. + */ + bitcoin_amount: number; + + /** + * The amount of bitcoin that has been sent by the customer to this receiver. + */ + bitcoin_amount_received: number; + + /** + * This URI can be displayed to the customer as a clickable link (to activate their bitcoin client) or as a QR code (for mobile wallets). + */ + bitcoin_uri: number; + created: number; + + /** + * Three-letter ISO currency code representing the currency to which the bitcoin will be converted. + */ + currency: string; + + /** + * This flag is initially false and updates to true when the customer sends the bitcoin_amount to this receiver. + */ + filled: boolean; + + /** + * A bitcoin address that is specific to this receiver. The customer can send bitcoin to this address to fill the receiver. + */ + inbound_address: string; + + /** + * A list with one entry for each time that the customer sent bitcoin to the receiver. Hidden when viewing the + * receiver with a publishable key. + */ + transactions: IList; + + /** + * This receiver contains uncaptured funds that can be used for a payment or refunded. + */ + uncaptured_funds: boolean; + description: string; + + /** + * The customer’s email address, set by the API call that creates the receiver. + */ + email: string; + + /** + * A set of key/value pairs that you can attach to a customer object. It can be useful for storing additional information + * about the customer in a structured format. + */ + metadata: IMetadata; + + /** + * The ID of the payment created from the receiver, if any. Hidden when viewing the receiver with a publishable key. + */ + payment: string; + + /** + * The refund address for these bitcoin, if communicated by the customer. + */ + refund_address: string; + customer: string; + } + + interface IBitcoinTransaction { + id: string; + + /** + * Value is 'list' + */ + object: string; + + /** + * The amount of currency that the transaction was converted to in real-time. + */ + amount: number; + + /** + * The amount of bitcoin contained in the transaction. + */ + bitcoin_amount: number; + created: number; + + /** + * The currency to which this transaction was converted. + */ + currency: string; + + /** + * The receiver to which this transaction was sent. + */ + receiver: string; + } + } + module customerCards { } + + module customerSubscriptions { + /** + * Subscriptions allow you to charge a customer's card on a recurring basis. A subscription ties a customer to + * a particular plan you've created: https://stripe.com/docs/api#create_plan + */ + interface ISubscription { + id: string; + + /** + * Value is 'subscription' + */ + object: string; + + /** + * If the subscription has been canceled with the at_period_end flag set to true, cancel_at_period_end on the + * subscription will be true. You can use this attribute to determine whether a subscription that has a status + * of active is scheduled to be canceled at the end of the current period. + */ + cancel_at_period_end: boolean; + customer: string; + + /** + * Hash describing the plan the customer is subscribed to + */ + plan: plans.IPlan; + + /** + * The number of subscriptions for the associated plan + */ + quantity: number; + + /** + * Date the subscription started + */ + start: number; + + /** + * Possible values are trialing, active, past_due, canceled, or unpaid. A subscription still in its trial period is trialing + * and moves to active when the trial period is over. When payment to renew the subscription fails, the subscription becomes + * past_due. After Stripe has exhausted all payment retry attempts, the subscription ends up with a status of either canceled + * or unpaid depending on your retry settings. Note that when a subscription has a status of unpaid, no subsequent invoices + * will be attempted (invoices will be created, but then immediately automatically closed. Additionally, updating customer + * card details will not lead to Stripe retrying the latest invoice.). After receiving updated card details from a customer, + * you may choose to reopen and pay their closed invoices. + */ + status: string; + + /** + * A positive decimal that represents the fee percentage of the subscription invoice amount that will be transferred to + * the application owner’s Stripe account each billing period. + */ + application_fee_percent: number; + + /** + * If the subscription has been canceled, the date of that cancellation. If the subscription was canceled with + * cancel_at_period_end, canceled_at will still reflect the date of the initial cancellation request, not the end of the + * subscription period when the subscription is automatically moved to a canceled state. + */ + canceled_at: number; + + /** + * End of the current period that the subscription has been invoiced for. At the end of this period, a new invoice will be created. + */ + current_period_end: number; + + /** + * Start of the current period that the subscription has been invoiced for + */ + current_period_start: number; + + /** + * Describes the current discount applied to this subscription, if there is one. When billing, a discount applied to a + * subscription overrides a discount applied on a customer-wide basis. + */ + discount: coupons.IDiscount; + + /** + * If the subscription has ended (either because it was canceled or because the customer was switched to a subscription + * to a new plan), the date the subscription ended + */ + ended_at: number; + + /** + * A set of key/value pairs that you can attach to a subscription object. It can be useful for storing additional + * information about the subscription in a structured format. + */ + metadata: IMetadata; + + /** + * If the subscription has a trial, the end of that trial. + */ + trial_end: number; + + /** + * If the subscription has a trial, the beginning of that trial. + */ + trial_start: number; + + /** + * If provided, each invoice created by this subscription will apply the tax rate, increasing the amount billed to the customer. + */ + tax_percent: number; + } + } + + module chargeRefunds { + interface IRefund { + id: string; + + /** + * Value is 'list' + */ + object: string; + + /** + * Amount reversed in cents. + */ + amount: number; + + created: number; + + /** + * Three-letter ISO currency code representing the currency in which the charge was made. + */ + currency: string; + + /** + * Balance transaction that describes the impact of this reversal on your account balance. + */ + balance_transaction: string; + + /** + * ID of the charge that was refunded. + */ + charge: string; + + metadata: IMetadata; + + /** + * Reason for the refund. If set, possible values are duplicate, fraudulent, and requested_by_customer. + */ + reason: string; + + /** + * This is the transaction number that appears on email receipts sent for this refund. + */ + receipt_number: string; + + description: string; + } + } + + module applicationFeeRefunds { } + module transferReversals { } + + class StripeResource { + constructor(stripe: Stripe, urlData: any); + } + + module resources { + class Account extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + } + + class ApplicationFeeRefunds extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + } + + class ApplicationFees extends StripeResource { + list(): void; + retrieve(id: string): void; + } + + class Balance extends StripeResource { + retrieve(id: string): void; + } + + class BitcoinReceivers extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + } + + class ChargeRefunds extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + } + + class Charges extends StripeResource { + /** + * To charge a credit card, you create a charge object. If your API key is in test mode, the supplied card won't actually be charged, though + * everything else will occur as if in live mode. (Stripe assumes that the charge would have completed successfully). + * + * @returns Returns a charge object if the charge succeeded. Throws an error if something goes wrong. A common source of error is an invalid or + * expired card, or a valid card with insufficient available balance. If the cvc parameter is provided, Stripe will attempt to check the CVC's + * correctness, and the check's result will be returned. Similarly, If address_line1 or address_zip are provided, Stripe will similarly try to + * check the validity of those parameters. Some banks do not support checking one or more of these parameters, in which case Stripe will return + * an 'unavailable' result. Also note that, depending on the bank, charges can succeed even when passed incorrect CVC and address information. + * + * @param options Options for creating a charge. + * @param response A callback to receive the response and newly created charge, or errors if they exist. + */ + create(options: { + /** + * A positive integer in the smallest currency unit (e.g 100 cents to charge $1.00, or 1 to charge ¥1, a 0-decimal currency) + * representing how much to charge the card. The minimum amount is $0.50 (or equivalent in charge currency). + */ + amount: number; + + /** + * 3-letter ISO code for currency. + */ + currency: string; + + /** + * The ID of an existing customer that will be charged in this request. + */ + customer?: string; + + /** + * A payment source to be charged, such as a credit card. If you also pass a customer ID, the source must be the ID of + * a source belonging to the customer. Otherwise, if you do not pass a customer ID, the source you provide must either + * be a token, like the ones returned by Stripe.js, or a object containing a user's credit card details, with the options + * described below. Although not all information is required, the extra info helps prevent fraud. + */ + source?: string | IPaymentToken | ICard; + + /** + * An arbitrary string which you can attach to a charge object. It is displayed when in the web interface alongside the + * charge. Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include + * the description of the charge(s) that they are describing. + */ + description?: string; + metadata?: IMetadata; + + /** + * Whether or not to immediately capture the charge. When false, the charge issues an authorization (or pre-authorization), + * and will need to be captured later. Uncaptured charges expire in 7 days. For more information, see authorizing charges + * and settling later: https://support.stripe.com/questions/can-i-authorize-a-charge-and-then-wait-to-settle-it-later + */ + capture?: boolean; + + /** + * An arbitrary string to be displayed on your customer's credit card statement. This may be up to 22 characters. + * As an example, if your website is RunClub and the item you're charging for is a race ticket, you may want to + * specify a statement_descriptor of RunClub 5K race ticket. The statement description may not include <>"' characters, + * and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + * While most banks display this information consistently, some may display it incorrectly or not at all. + */ + statement_descriptor?: string; + + /** + * The email address to send this charge's receipt to. The receipt will not be sent until the charge is paid. + * If this charge is for a customer, the email address specified here will override the customer's email address. + * Receipts will not be sent for test mode charges. If receipt_email is specified for a charge in live mode, a receipt + * will be sent regardless of your email settings. + */ + receipt_email?: string; + + /** + * A fee in cents that will be applied to the charge and transferred to the application owner's Stripe account. + * The request must be made with an OAuth key in order to take an application fee. For more information, + * see the application fees documentation: https://stripe.com/docs/connect/collecting-fees + */ + application_fee?: string; + + /** + * Shipping information for the charge. Helps prevent fraud on charges for physical goods. + */ + shipping?: IShippingInformation; + }, response: IResponseFn): void; + + /** + * Retrieves the details of a charge that has previously been created. Supply the unique charge ID that was returned + * from your previous request, and Stripe will return the corresponding charge information. The same information is + * returned when creating or refunding the charge. + * + * @param id The identifier of the charge to be retrieved + * @param response A callback that takes in a potential error and a charge object. + */ + retrieve(id: string, response: IResponseFn): void; + + /** + * Updates the specified charge by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + * This request accepts only the description, metadata, receipt_emailand fraud_details as arguments. + * + * @param id The identifier of the charge to be updated + * @param update An object containing the updated properties. + */ + update(id: string, update: { + /** + * An arbitrary string which you can attach to a charge object. It is displayed when in the web interface alongside the charge. + * Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the description + * of the charge(s) that they are describing. This can be unset by updating the value to null and then saving. + */ + description?: string; + + /** + * You can unset an individual key by setting its value to null and then saving. To clear all keys, set metadata to null, then save. + */ + metadata?: IMetadata; + + /** + * This is the email address that the receipt for this charge will be sent to. + * If this field is updated, then a new email receipt will be sent to the updated address. + */ + receipt_email?: string; + + /** + * A set of key/value pairs you can attach to a charge giving information about its riskiness. + */ + fraud_details?: { + /** + * If you believe a charge is fraudulent, include a user_report key with a value of fraudulent. If you believe a + * charge is safe, include a user_report key with a value of safe. Note that you must refund a charge before setting + * the user_report to fraudulent. Stripe will use the information you send to improve our fraud detection algorithm + */ + user_report?: string; + } + }, response: IResponseFn): void; + + /** + * Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step payment flow, where first + * you created a charge with the capture option set to false. Uncaptured payments expire exactly seven days after they are + * created. If they are not captured by that point in time, they will be marked as refunded and will no longer be capturable. + */ + capture(id: string, response: IResponseFn): void; + + /** + * Returns a list of charges you've previously created. The charges are returned in sorted order, with the most recent charges + * appearing first. + * + * @returns An object with a data property that contains an array of up to limit charges, starting after charge starting_after. + * Each entry in the array is a separate charge object. If no more charges are available, the resulting array will be empty. + * If you provide a non-existent customer ID, this call throws an error. You can optionally request that the response include + * the total count of all charges that match your filters. To do so, specify include[]=total_count in your request. + * + * @param options Filtering options for the returned items. + */ + list(options: IListOptions, response: IResponseFn>): void; + + /** + * When you get a dispute, contacting your customer is always the best first step. If that doesn't work, you can submit evidence in + * order to help us resolve the dispute in your favor. You can do this in your dashboard, but if you prefer, you can use the API to + * submit evidence programmatically. Depending on your dispute type, different evidence fields will give you a better chance of winning + * your dispute. You may want to consult our guide to dispute types to help you figure out which evidence fields to provide: + * https://stripe.com/help/dispute-types + * + * @param chargeId The ID for the disputed charge + * @param options The fields to update + */ + updateDispute(chargeId: string, options: { + /** + * Evidence to upload to respond to a dispute. Updating any field in the hash will submit all fields in the hash for review. + */ + evidence?: IDisputeEvidence; + /** + * A set of key/value pairs that you can attach to a dispute object. It can be useful for storing additional information about the + * dispute in a structured format. This can be unset by updating the value to null and then saving. + */ + metadata?: IMetadata; + }, response: IResponseFn): void; + + + /** + * Closing the dispute for a charge indicates that you do not have any evidence to submit and are essentially 'dismissing' the dispute, + * acknowledging it as lost. The status of the dispute will change from under_review to lost. + * + * IMPORTANT: Closing a dispute is irreversible. + * + * @param chargeId The ID of the disputed charge + */ + closeDispute(chargeId: string): void; + + /** + * When you create a new refund, you must specify a charge to create it on. Creating a new refund will refund a charge that has previously + * been created but not yet refunded. Funds will be refunded to the credit or debit card that was originally charged. The fees you were + * originally charged are also refunded. You can optionally refund only part of a charge. You can do so as many times as you wish until + * the entire charge has been refunded. Once entirely refunded, a charge can't be refunded again. This method will throw an error when + * called on an already-refunded charge, or when trying to refund more money than is left on a charge. + * + * @returns Returns the refund object if the refund succeeded. Throws an error if the charge has already been refunded or an invalid + * charge identifier was provided. + * + * @param id The identifier of the charge to be refunded. + * @param options Options for specifying reasons and refund amount + * @param response The refund. + */ + createRefund(id: string, options: { + /** + * A positive integer in cents representing how much of this charge to refund. Can only refund up to the unrefunded amount remaining + * of the charge. + */ + amount?: number; + + /** + * Boolean indicating whether the application fee should be refunded when refunding this charge. If a full charge refund is given, the + * full application fee will be refunded. Else, the application fee will be refunded with an amount proportional to the amount of the + * charge refunded. An application fee can only be refunded by the application that created the charge. + */ + refund_applcation_fee?: boolean; + + /** + * String indicating the reason for the refund. If set, possible values are duplicate, fraudulent, and requested_by_customer. Specifying + * fraudulent as the reason when you believe the charge to be fraudulent will help us improve our fraud detection algorithms. + */ + reason?: string; + + /** + * A set of key/value pairs that you can attach to a refund object. It can be useful for storing additional information about the refund + * in a structured format. You can unset an individual key by setting its value to null and then saving. To clear all keys, set metadata + * to null, then save. + */ + metadata?: IMetadata; + }, response: IResponseFn): void; + + /** + * By default, you can see the 10 most recent refunds stored directly on the charge object, but you can also retrieve details about a specific + * refund stored on the charge. + * + * @param chargeId The ID of the charge refunded + * @param refundId The ID of the refund to retrieve + */ + retrieveRefund(chargeId: string, refundId: string, response: IResponseFn): void; + + /** + * Updates the specified refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + * This request only accepts metadata as an argument. + * + * @param chargeId The ID of the charge refunded + * @param refundId The ID of the refund to update + */ + updateRefund(chargeId: string, refundId: string, options: { + /** + * A set of key/value pairs that you can attach to a refund object. It can be useful for storing additional information about the refund + * in a structured format. You can unset an individual key by setting its value to null and then saving. To clear all keys, set metadata + * to null, then save. + */ + metadata: IMetadata; + }, response: IResponseFn): void; + + /** + * You can see a list of the refunds belonging to a specific charge. Note that the 10 most recent refunds are always available by default on + * the charge object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through + * additional refunds. + * + * @returns A object with a data property that contains an array of up to limit refunds, starting after refund starting_after. + * Each entry in the array is a separate refund object. If no more refunds are available, the resulting array will be empty. If you provide + * a non-existent customer ID or charge ID, this call throws an error. You can optionally request that the response include the total count + * of all refunds that match your filters. To do so, specify include[]=total_count in your request. + * + * @param chargeId The ID of the charge refunded + * @param options Used to filter the refunds returned + */ + listRefunds(chargeId: string, options: IListOptions, response: IResponseFn>): void; + } + + class Coupons extends StripeResource { + /** + * You can create coupons easily via the coupon management page of the Stripe dashboard. Coupon creation is also accessible via the API if + * you need to create coupons on the fly. A coupon has either a percent_off or an amount_off and currency. If you set an amount_off, that + * amount will be subtracted from any invoice's subtotal. For example, an invoice with a subtotal of $10 will have a final total of $0 if + * a coupon with an amount_off of 2000 is applied to it and an invoice with a subtotal of $30 will have a final total of $10 if a coupon + * with an amount_off of 2000 is applied to it. + * + * @returns Returns the coupon object. + * + * @param options Options for creating the coupon. + */ + create(options: { + /** + * Unique string of your choice that will be used to identify this coupon when applying it a customer. This is often a specific code + * you’ll give to your customer to use when signing up (e.g. FALL25OFF). If you don’t want to specify a particular code, you can leave + * the ID blank and we’ll generate a random code for you. + */ + id?: string; + + /** + * Specifies how long the discount will be in effect. Can be forever, once, or repeating. + */ + duration: string; + + /** + * A positive integer representing the amount to subtract from an invoice total (required if percent_off is not passed) + */ + amount_off?: number; + + /** + * Currency of the amount_off parameter (required if amount_off is passed) + */ + currency?: string; + + /** + * required only if duration is repeating If duration is repeating, a positive integer that specifies the number of months the + * discount will be in effect + */ + duration_in_months?: number; + + /** + * A positive integer specifying the number of times the coupon can be redeemed before it’s no longer valid. For example, you might + * have a 50% off coupon that the first 20 readers of your blog can use. + */ + max_redemptions?: number; + + /** + * A set of key/value pairs that you can attach to a coupon object. It can be useful for storing additional information about the + * coupon in a structured format. This can be unset by updating the value to null and then saving. + */ + metadata?: IMetadata; + + /** + * A positive integer between 1 and 100 that represents the discount the coupon will apply (required if amount_off is not passed) + */ + percent_off?: number; + + /** + * Unix timestamp specifying the last time at which the coupon can be redeemed. After the redeem_by date, the coupon can no longer + * be applied to new customers. + */ + redeem_by?: number; + }, response: IResponseFn): void; + + /** + * Retrieves the coupon with the given ID. + * + * @returns Returns a coupon if a valid coupon ID was provided. Throws an error otherwise. + * + * @param id The ID of the desired coupon + */ + retrieve(id: string, response: IResponseFn): void; + + /** + * Updates the metadata of a coupon. Other coupon details (currency, duration, amount_off) are, by design, not editable. + * + * @returns The newly updated coupon object if the call succeeded. Otherwise, this call throws an error, such as if the coupon has + * been deleted. + * + * @param id The ID of the coupon to be updated + * @param options Metadata to update + */ + update(id: string, options: { + /** + * A set of key/value pairs that you can attach to a coupon object. It can be useful for storing additional information about the + * coupon in a structured format. + */ + metadata?: IMetadata; + }, response: IResponseFn): void; + + /** + * You can delete coupons via the coupon management page of the Stripe dashboard. However, deleting a coupon does not affect any + * customers who have already applied the coupon; it means that new customers can't redeem the coupon. You can also delete coupons + * via the API. + * + * @returns An object with the deleted coupon's ID and a deleted flag upon success. Otherwise, this call throws an error, such as + * if the coupon has already been deleted. + * + * @param id The ID of the coupon to be deleted. + */ + del(id: string, response: IResponseFn): void; + + /** + * Returns a list of your coupons. + * + * @returns A object with a data property that contains an array of up to limit coupons, starting after coupon starting_after. Each + * entry in the array is a separate coupon object. If no more coupons are available, the resulting array will be empty. This request + * should never throw an error. You can optionally request that the response include the total count of all coupons. To do so, specify + * include[]=total_count in your request. + * + * @param options Filtering options for the list. + */ + list(options: IListOptions, response: IResponseFn): void; + } + + class CustomerCards extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + del(id: string): void; + } + + class Customers extends StripeResource { + /** + * Creates a new customer object. + * + * @returns Returns a customer object if the call succeeded. The returned object will have information about subscriptions, discount, + * and payment sources, if that information has been provided. If a non-free plan is specified and a source is not provided (unless + * the plan has a trial period), the call will throw an error. If a non-existent plan or a non-existent or expired coupon is provided, + * the call will throw an error. If a source has been attached to the customer, the returned customer object will have a default_source + * attribute, which is an ID that can be expanded into the full source details when retrieving the customer. + * + * @param options The options for the new customer + */ + create(options: { + /** + * An integer amount in cents that is the starting account balance for your customer. A negative amount represents a credit that + * will be used before attempting any charges to the customer’s card; a positive amount will be added to the next invoice. + */ + account_balance?: number; + + /** + * If you provide a coupon code, the customer will have a discount applied on all recurring charges. Charges you create through the + * API will not have the discount. + */ + coupon?: string; + + /** + * An arbitrary string that you can attach to a customer object. It is displayed alongside the customer in the dashboard. This can + * be unset by updating the value to null and then saving. + */ + description?: string; + + /** + * Customer’s email address. It’s displayed alongside the customer in your dashboard and can be useful for searching and tracking. + * This can be unset by updating the value to null and then saving. + */ + email?: string; + + /** + * A set of key/value pairs that you can attach to a customer object. It can be useful for storing additional information about the + * customer in a structured format. This can be unset by updating the value to null and then saving. + */ + metadata?: IMetadata; + + /** + * The identifier of the plan to subscribe the customer to. If provided, the returned customer object will have a list of subscriptions + * that the customer is currently subscribed to. If you subscribe a customer to a plan without a free trial, the customer must have a + * valid card as well. + */ + plan?: string; + + /** + * The quantity you’d like to apply to the subscription you’re creating (if you pass in a plan). For example, if your plan is + * 10 cents/user/month, and your customer has 5 users, you could pass 5 as the quantity to have the customer charged 50 cents + * (5 x 10 cents) monthly. Defaults to 1 if not set. Only applies when the plan parameter is also provided. + */ + quantity?: number; + source?: string | ICard; + + /** + * Unix timestamp representing the end of the trial period the customer will get before being charged. If set, trial_end will + * override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to + * end the customer’s trial immediately. Only applies when the plan parameter is also provided. + */ + trial_end?: number; + }, response: IResponseFn): void; + + /** + * Returns a list of your customers. The customers are returned sorted by creation date, with the most recently created customers + * appearing first. + * + * @returns A object with a data property that contains an array of up to limit customers, starting after customer starting_after. + * Each entry in the array is a separate customer object. If no more customers are available, the resulting array will be empty. + * This request should never throw an error. You can optionally request that the response include the total count of all customers + * that match your filters. To do so, specify include[]=total_count in your request. + * + * @param options Allows you to filter the customers you want. + */ + list(options: IListOptions, response: IResponseFn>): void; + + /** + * Updates the specified customer by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + * For example, if you pass the card parameter, that becomes the customer's active card to be used for all charges in the future. + * When you update a customer to a new valid card: for each of the customer's current subscriptions, if the subscription is in the + * past_due state, then the latest unpaid, unclosed invoice for the subscription will be retried (note that this retry will not count + * as an automatic retry, and will not affect the next regularly scheduled payment for the invoice). (Note also that no invoices + * pertaining to subscriptions in the unpaid state, or invoices pertaining to canceled subscriptions, will be retried as a result + * of updating the customer's card.) This request accepts mostly the same arguments as the customer creation call. + * + * @returns Returns the customer object if the update succeeded. Throws an error if update parameters are invalid (e.g. specifying + * an invalid coupon or an invalid card). + */ + update(id: string, options: { + /** + * An integer amount in cents that is the starting account balance for your customer. A negative amount represents a credit that + * will be used before attempting any charges to the customer’s card; a positive amount will be added to the next invoice. + */ + account_balance?: number; + + /** + * If you provide a coupon code, the customer will have a discount applied on all recurring charges. Charges you create through the + * API will not have the discount. + */ + coupon?: string; + + /** + * An arbitrary string that you can attach to a customer object. It is displayed alongside the customer in the dashboard. This can + * be unset by updating the value to null and then saving. + */ + description?: string; + + /** + * Customer’s email address. It’s displayed alongside the customer in your dashboard and can be useful for searching and tracking. + * This can be unset by updating the value to null and then saving. + */ + email?: string; + + /** + * A set of key/value pairs that you can attach to a customer object. It can be useful for storing additional information about the + * customer in a structured format. This can be unset by updating the value to null and then saving. + */ + metadata?: IMetadata; + + /** + * The identifier of the plan to subscribe the customer to. If provided, the returned customer object will have a list of subscriptions + * that the customer is currently subscribed to. If you subscribe a customer to a plan without a free trial, the customer must have a + * valid card as well. + */ + plan?: string; + + /** + * The quantity you’d like to apply to the subscription you’re creating (if you pass in a plan). For example, if your plan is + * 10 cents/user/month, and your customer has 5 users, you could pass 5 as the quantity to have the customer charged 50 cents + * (5 x 10 cents) monthly. Defaults to 1 if not set. Only applies when the plan parameter is also provided. + */ + quantity?: number; + source?: ICard; + + /** + * Unix timestamp representing the end of the trial period the customer will get before being charged. If set, trial_end will + * override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to + * end the customer’s trial immediately. Only applies when the plan parameter is also provided. + */ + trial_end?: number; + }, response: IResponseFn): void; + + /** + * Retrieves the details of an existing customer. You need only supply the unique customer identifier that was returned upon customer + * creation. + * + * @returns Returns a customer object if a valid identifier was provided. When requesting the ID of a customer that has been deleted, + * a subset of the customer's information will be returned, including a "deleted" property, which will be true. + * + * @param id The identifier of the customer to be retrieved. + */ + retrieve(id: string, response: IResponseFn): void; + + /** + * Permanently deletes a customer. It cannot be undone. Also immediately cancels any active subscriptions on the customer. + * + * @returns Returns an object with a deleted parameter on success. If the customer ID does not exist, this call throws an error. Unlike + * other objects, deleted customers can still be retrieved through the API, in order to be able to track the history of customers while + * still removing their credit card details and preventing any further operations to be performed (such as adding a new subscription). + * + * @param id The identifier of the customer to be deleted. + */ + del(id: string, response: IResponseFn): void; + + /** + * When you create a new credit card, you must specify a customer or recipient to create it on. If the card's owner has no default card, + * then the new card will become the default. However, if the owner already has a default then it will not change. To change the default, + * you should either update the customer to have a new default_source or update the recipient to have a new default_card. + * + * @returns Returns the card object. + * + * @param customerId The customer ID to which to add the card. + */ + createCard(customerId: string, options: { + /** + * The source can either be a token, like the ones returned by our Stripe.js, or a dictionary containing a user’s credit card details + * (with the options shown below). Whenever you create a new card for a customer, Stripe will automatically validate the card. + */ + source?: string | ICard; + card?: string | IPaymentToken; + }, response: IResponseFn): void; + + /** + * By default, you can see the 10 most recent cards stored on a customer or recipient directly on the customer or recipient object, but + * you can also retrieve details about a specific card stored on the customer or recipient. + * + * @returns Returns the card object. + * + * @param customerId The ID of the customer whose card needs to be retrieved. + * @param cardId The ID of the card to be retrieved. + */ + retrieveCard(customerId: string, cardId: string, response: IResponseFn): void; + + /** + * If you need to update only some card details, like the billing address or expiration date, you can do so without having to re-enter the + * full card details. Stripe also works directly with card networks so that your customers can continue using your service without + * interruption. When you update a card, Stripe will automatically validate the card. + * + * @returns Returns the card object. + * + * @param customerId The ID of the customer whose card needs to be retrieved. + * @param cardId The ID of the card to be retrieved. + */ + updateCard(customerId: string, cardId: string, options: { + /** + * The card number + */ + 'number'?: number; + exp_month?: number; + exp_year?: number; + address_city?: string; + + /** + * Billing address country, if provided when creating card + */ + address_country?: string; + address_line1?: string; + address_line2?: string; + address_state?: string; + address_zip?: string; + + /** + * Two-letter ISO code representing the country of the card. You could use this + * attribute to get a sense of the international breakdown of cards you’ve collected. + */ + country?: string; + + /** + * Cardholder name + */ + name?: string; + }, response: IResponseFn): void; + + /** + * You can delete cards from a customer or recipient. If you delete a card that is currently the + * default source on a customer, then the most recently added source will become the new default. + * If you delete a card that is the last remaining source on the customer then the default_source + * attribute will become null. Similarly, if you delete the default card on a recipient, then the + * most recently added card will become the new default. If you delete the last remaining card on + * a recipient, then the default_card attribute will become null. Note that for cards belonging to + * customers, you may want to prevent customers on paid subscriptions from deleting all cards on + * file so that there is at least one default card for the next invoice payment attempt. + * + * @returns Returns the deleted card object. + * + * @param customerId The ID of the customer whose card needs to be retrieved. + * @param cardId The ID of the card to be retrieved. + */ + deleteCard(customerId: string, cardId: string, response: IResponseFn): void; + + /** + * You can see a list of the cards belonging to a customer or recipient. Note that the 10 most recent + * cards are always available by default on the customer or recipient object. If you need more than + * those 10, you can use this API method and the limit and starting_after parameters to page through + * additional cards. + * + * @returns Returns a list of the cards stored on the customer or recipient. You can optionally request + * that the response include the total count of all cards for the customer or recipient. To do so, + * specify include[]=total_count in your request. + * + * @param customerId The ID of the customer whose cards will be retrieved + * @param options Filtering options + */ + listCards(customerId: string, options: IListOptions, response: IResponseFn>): void; + + /** + * Creates a new subscription on an existing customer. + * + * @returns The newly created subscription object if the call succeeded. If the customer has no card or the + * attempted charge fails, this call throws an error (unless the specified plan is free or has a trial + * period). + * + * @param customerId The customer to which the add the subscription. + * @param options The options for the new subscription + */ + createSubscription(customerId: string, options: { + /** + * The identifier of the plan to subscribe the customer to. + */ + plan: string; + + /** + * The code of the coupon to apply to this subscription. A coupon applied to a subscription will only + * affect invoices created for that particular subscription. + */ + coupon?: string; + + /** + * Unix timestamp representing the end of the trial period the customer will get before being charged + * for the first time. If set, trial_end will override the default trial period of the plan the customer + * is being subscribed to. The special value now can be provided to end the customer's trial immediately. + */ + trial_end?: number; + + /** + * The source can either be a token, like the ones returned by our Stripe.js, or a object containing a + * user's credit card details (with the options shown below). You must provide a source if the customer + * does not already have a valid source attached, and you are subscribing the customer for a plan that + * is not free. Passing source will create a new source object, make it the customer default source, and + * delete the old customer default if one exists. If you want to add an additional source to use with + * subscriptions, instead use the card creation API to add the card and then the customer update API to + * set it as the default. Whenever you attach a card to a customer, Stripe will automatically validate + * the card. + */ + source?: IPaymentToken | ICard; + + /** + * The quantity you'd like to apply to the subscription you're creating. For example, if your plan is + * $10/user/month, and your customer has 5 users, you could pass 5 as the quantity to have the customer + * charged $50 (5 x $10) monthly. If you update a subscription but don't change the plan ID (e.g. + * changing only the trial_end), the subscription will inherit the old subscription's quantity attribute + * unless you pass a new quantity parameter. If you update a subscription and change the plan ID, the new + * subscription will not inherit the quantity attribute and will default to 1 unless you pass a quantity + * parameter. + */ + quantity?: number; + + /** + * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage + * of the subscription invoice subtotal that will be transferred to the application owner’s Stripe account. + * The request must be made with an OAuth key in order to set an application fee percentage. For more + * information, see the application fees documentation: https://stripe.com/docs/connect/collecting-fees#subscriptions + */ + application_fee_percent?: number; + + /** + * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage + * of the subscription invoice subtotal that will be calculated and added as tax to the final amount each + * billing period. For example, a plan which charges $10/month with a tax_percent of 20.0 will charge + * $12 per invoice. + */ + tax_percent?: number; + + /** + * A set of key/value pairs that you can attach to a subscription object. It can be useful for + * storing additional information about the subscription in a structured format. + */ + metadata?: IMetadata; + }, response: IResponseFn): void; + + /** + * By default, you can see the 10 most recent active subscriptions stored on a customer directly on the customer + * object, but you can also retrieve details about a specific active subscription for a customer. + * + * @returns Returns the subscription object. + * + * @param customerId The customer ID for the subscription + * @param subscriptionId The ID of the subscription to retrieve + */ + retrieveSubscription(customerId: string, subscriptionId: string, response: IResponseFn): void; + + /** + * Updates an existing subscription on a customer to match the specified parameters. When changing plans or quantities, + * we will optionally prorate the price we charge next month to make up for any price changes. + * + * By default, we prorate subscription changes. For example, if a customer signs up on May 1 for a $10 plan, she'll be billed + * $10 immediately. If she then switches to a $20 plan on May 15, on June 1 she'll be billed $25 ($20 for a renewal of her + * subscription and a $5 prorating adjustment for the previous month). Similarly, a downgrade will generate a credit to be + * applied to the next invoice. We also prorate when you make quantity changes. Switching plans does not change the billing + * date or generate an immediate charge unless you're switching between different intervals (e.g. monthly to yearly), in which + * case we apply a credit for the time unused on the old plan and charge for the new plan starting right away, resetting the + * billing date. (Note that if we charge for the new plan, and that payment fails, the plan change will not go into effect). If + * you'd like to charge for an upgrade immediately, just pass prorate as true as usual, and then invoice the customer as soon + * as you make the subscription change. That'll collect the proration adjustments into a new invoice, and Stripe will automatically + * attempt to pay the invoice. If you don't want to prorate at all, set the prorate option to false and the customer would be billed + * $10 on May 1 and $20 on June 1. Similarly, if you set prorate to false when switching between different billing intervals + * (monthly to yearly, for example), we won't generate any credits for the old subscription's unused time, although we will still + * reset the billing date and bill immediately for the new subscription. + * + * @returns The newly updated subscription object if the call succeeded. If a charge is required for the update, and + * the charge fails, this call raises throws an error, and the subscription update does not go into effect. + * + * @param customerId The ID of the customer whose subscription needs to be updated. + * @param subscriptionId The ID of the subscription to update. + * @param options The fields to update + */ + updateSubscription(customerId: string, subscriptionId: string, options: { + /** + * The identifier of the plan to update the subscription to. If omitted, the subscription will not change plans. + */ + plan?: string; + + /** + * The code of the coupon to apply to the customer if you would like to apply it at the same time as updating the subscription. + */ + coupon?: string; + + /** + * Flag telling us whether to prorate switching plans during a billing cycle. + */ + prorate?: boolean; + + /** + * Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. If set, + * trial_end will override the default trial period of the plan the customer is being subscribed to. The special value now can be + * provided to end the customer's trial immediately. + */ + trial_end?: number; + + /** + * The source can either be a token, like the ones returned by our Stripe.js, or a object containing a user's credit card details + * (with the options shown below). You must provide a source if the customer does not already have a valid source attached, and + * you are subscribing the customer for a plan that is not free. Passing source will create a new source object, make it the + * customer default source, and delete the old customer default if one exists. If you want to add an additional source to use + * with subscriptions, instead use the card creation API to add the card and then the customer update API to set it as the default. + * Whenever you attach a card to a customer, Stripe will automatically validate the card. + */ + source?: IPaymentToken | ICard; + + /** + * The quantity you'd like to apply to the subscription you're updating. For example, if your plan is $10/user/month, and your + * customer has 5 users, you could pass 5 as the quantity to have the customer charged $50 (5 x $10) monthly. If you update a + * subscription but don't change the plan ID (e.g. changing only the trial_end), the subscription will inherit the old subscription's + * quantity attribute unless you pass a new quantity parameter. If you update a subscription and change the plan ID, the new + * subscription will not inherit the quantity attribute and will default to 1 unless you pass a quantity parameter. + */ + quantity?: number; + + /** + * A positive decimal (with at most two decimal places) between 1 and 100 that represents the percentage of the subscription + * invoice amount due each billing period (including any bundled invoice items) that will be transferred to the application + * owner’s Stripe account. The request must be made with an OAuth key in order to set an application fee percentage . For more + * information, see the application fees documentation: https://stripe.com/docs/connect/collecting-fees#subscriptions + */ + application_fee_percent?: number; + + /** + * Update the amount of tax applied to this subscription. Changing the tax_percent of a subscription will only affect future + * invoices. + */ + tax_percent?: number; + + /** + * A set of key/value pairs that you can attach to a subscription object. It can be useful for storing additional information + * about the subscription in a structured format. + */ + metadata?: IMetadata; + }, response: IResponseFn): void; + + /** + * Cancels a customer's subscription. If you set the at_period_end parameter to true, the subscription will remain active until + * the end of the period, at which point it will be canceled and not renewed. By default, the subscription is terminated + * immediately. In either case, the customer will not be charged again for the subscription. Note, however, that any pending + * invoice items that you've created will still be charged for at the end of the period unless manually deleted. If you've set + * the subscription to cancel at period end, any pending prorations will also be left in place and collected at the end of the + * period, but if the subscription is set to cancel immediately, pending prorations will be removed. By default, all unpaid + * invoices for the customer will be closed upon subscription cancellation. We do this in order to prevent unexpected payment + * retries once the customer has canceled a subscription. However, you can reopen the invoices manually after subscription + * cancellation to have us proceed with automatic retries, or you could even re-attempt payment yourself on all unpaid invoices + * before allowing the customer to cancel the subscription at all. + * + * @returns The canceled subscription object. Its subscription status will be set to "canceled" unless you've set at_period_end + * to true when canceling, in which case the status will remain "active" but the cancel_at_period_end attribute will change to true. + * + * @param customerId The ID of the customer whose subscription needs to be cancelled. + * @param subscriptionId The ID of the subscription to cancel. + * @param options Specify when to cancel the subscription + */ + cancelSubscription(customerId: string, subscriptionId: string, options: { + /** + * A flag that if set to true will delay the cancellation of the subscription until the end of the current period. + */ + at_period_end?: boolean; + }, response: IResponseFn): void; + + /** + * You can see a list of the customer's active subscriptions. Note that the 10 most recent active subscriptions are always available + * by default on the customer object. If you need more than those 10, you can use the limit and starting_after parameters to page + * through additional subscriptions. + * + * @returns Returns a list of the customer's active subscriptions. You can optionally request that the response include the total + * count of all subscriptions for the customer. To do so, specify include[]=total_count in your request. + * + * @param customerId The ID of the customer whose subscriptions will be retrieved + * @param options Filtering options + */ + listSubscriptions(customerId: string, options: IListOptions, response: IResponseFn>): void; + + /** + * Removes the currently applied discount on a customer. + * + * @returns An object with a deleted flag set to true upon success. This call throws an error otherwise, such as if no + * discount exists on this customer. + * + * @param customerId The ID of the customer. + */ + deleteDiscount(customerId: string, response: IResponseFn): void; + + /** + * Removes the currently applied discount on a subscription. + * + * @returns An object with a deleted flag set to true upon success. This call throws an error otherwise, such as if no + * discount exists on this subscription. + * + * @param customerId The ID of the customer. + * @param subscriptionId The ID of the subscription. + */ + deleteSubscriptionDiscount(customerId: string, subscriptionId: string, response: IResponseFn): void; + } + + class CustomerSubscriptions extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + del(id: string): void; + } + + class Events extends StripeResource { + list(): void; + retrieve(id: string): void; + } + + class FileUploads extends StripeResource { + list(): void; + retrieve(id: string): void; + } + + class InvoiceItems extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + del(id: string): void; + } + + class Invoices extends StripeResource { + /** + * If you need to invoice your customer outside the regular billing cycle, you can create an invoice that + * pulls in all pending invoice items, including prorations. The customer's billing cycle and regular subscription + * won't be affected. Once you create the invoice, it'll be picked up and paid automatically, though you can + * choose to pay it right away: https://stripe.com/docs/api#pay_invoice + * + * @returns Returns the invoice object if there are pending invoice items to invoice. Throws an error if there + * are no pending invoice items or if the customer ID provided is invalid. + * + * @param options Options used to create the invoice. + */ + create(options: { + customer: string; + + /** + * A fee in cents that will be applied to the invoice and transferred to the application owner’s Stripe account. + * The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. + * For more information, see the application fees documentation. + */ + application_fee?: number; + description?: string; + metadata?: IMetadata; + + /** + * Extra information about a charge for the customer’s credit card statement. + */ + statement_descriptor?: string; + + /** + * The ID of the subscription to invoice. If not set, the created invoice will include all pending invoice items + * for the customer. If set, the created invoice will exclude pending invoice items that pertain to other + * subscriptions. + */ + subscription?: string; + + /** + * The percent tax rate applied to the invoice, represented as a decimal number. + */ + tax_percent?: number; + }, response: IResponseFn): void; + + /** + * Retrieves the invoice with the given ID. The invoice object contains a + * lines hash that contains information about the subscriptions and invoice items that have been applied to the + * invoice, as well as any prorations that Stripe has automatically calculated. Each line on the invoice has an + * amount attribute that represents the amount actually contributed to the invoice's total. For invoice items and + * prorations, the amount attribute is the same as for the invoice item or proration respectively. For + * subscriptions, the amount may be different from the plan's regular price depending on whether the invoice + * covers a trial period or the invoice period differs from the plan's usual interval. The invoice object has + * both a subtotal and a total. The subtotal represents the total before any discounts, while the total is the final + * amount to be charged to the customer after all coupons have been applied. The invoice also has a + * next_payment_attempt attribute that tells you the next time (as a Unix timestamp) payment for the invoice will be + * automatically attempted. For invoices that have been closed or that have reached the maximum number of retries + * (specified in your retry settings), the next_payment_attempt will be null. + * + * @returns Returns an invoice object if a valid invoice ID was provided. Throws an error otherwise. + * + * @param id The ID of the desired invoice. + */ + retrieve(id: string, response: IResponseFn): void; + + /** + * When retrieving an invoice, you'll get a lines property containing the total count of line items and the first + * handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. + * + * @returns Returns a list of line_item objects. + * + * @param id The id of the invoice containing the lines to be retrieved + * @param options Filtering options + */ + retrieveLines(id: string, options: { + /** + * In the case of upcoming invoices, the customer of the upcoming invoice is required. In other cases it is ignored. + */ + customer?: string; + + /** + * A cursor for use in pagination. ending_before is an object ID that defines your place in the list. + * For instance, if you make a list request and receive 100 objects, starting with obj_bar, your subsequent + * call can include ending_before=obj_bar in order to fetch the previous page of the list. + */ + ending_before?: string; + + /** + * A limit on the number of objects to be returned. Limit can range between 1 and 100 items. + */ + limit?: number; + + /** + * A cursor for use in pagination. starting_after is an object ID that defines your place in the list. For instance, + * if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include + * starting_after=obj_foo in order to fetch the next page of the list. + */ + starting_after?: string; + + /** + * In the case of upcoming invoices, the subscription of the upcoming invoice is optional. In other cases it is ignored. + */ + subscription?: string; + }, response: IResponseFn>): void; + + /** + * At any time, you can preview the upcoming invoice for a customer. This will show you all the charges that are pending, + * including subscription renewal charges, invoice item charges, etc. It will also show you any discount that is applicable + * to the customer. Note that when you are viewing an upcoming invoice, you are simply viewing a preview -- the invoice has + * not yet been created. As such, the upcoming invoice will not show up in invoice listing calls, and you cannot use the API + * to pay or edit the invoice. If you want to change the amount that your customer will be billed, you can add, remove, or + * update pending invoice items, or update the customer's discount. + * + * @returns Returns an invoice if a valid customer ID was provided. Throws an error otherwise. + * + * @param id The identifier of the customer whose upcoming invoice you'd like to retrieve. + */ + retrieveUpcoming(id: string, options: { + /** + * The identifier of the subscription for which you'd like to retrieve the upcoming invoice. If not provided, you will + * retrieve the next upcoming invoice from among the customer's subscriptions. + */ + subscription?: string; + }, response: IResponseFn): void; + + /** + * Until an invoice is paid, it is marked as open (closed=false). If you'd like to stop Stripe from automatically attempting + * payment on an invoice or would simply like to close the invoice out as no longer owed by the customer, you can update the + * closed parameter. + * + * @returns Returns the invoice object. + * + * @param id The ID of the invoice to update + * @param options Fields to update + */ + update(id: string, options: { + /** + * A fee in cents that will be applied to the invoice and transferred to the application owner’s Stripe account. The request + * must be made with an OAuth key or the Stripe-Account header in order to take an application fee. For more information, + * see the application fees documentation: https://stripe.com/docs/connect/collecting-fees#subscriptions + */ + application_fee?: number; + + /** + * Boolean representing whether an invoice is closed or not. To close an invoice, pass true. + */ + closed?: boolean; + description?: string; + + /** + * Boolean representing whether an invoice is forgiven or not. To forgive an invoice, pass true. Forgiving an invoice instructs + * us to update the subscription status as if the invoice were succcessfully paid. Once an invoice has been forgiven, it + * cannot be unforgiven or reopened. + */ + forgiven?: string; + metadata?: IMetadata; + + /** + * Extra information about a charge for the customer’s credit card statement. + */ + statement_descriptor?: string; + + /** + * The percent tax rate applied to the invoice, represented as a decimal number. The tax rate of a paid or forgiven invoice + * cannot be changed. + */ + tax_percent?: number; + }, response: IResponseFn): void; + + /** + * Stripe automatically creates and then attempts to pay invoices for customers on subscriptions. We'll also retry unpaid + * invoices according to your retry settings. However, if you'd like to attempt to collect payment on an invoice out of the + * normal retry schedule or for some other reason, you can do so. + * + * @returns Returns the invoice object. + * + * @param id The ID of the invoice to pay. + */ + pay(id: string, response: IResponseFn): void; + + /** + * You can list all invoices, or list the invoices for a specific customer. The invoices are returned + * sorted by creation date, with the most recently created invoices appearing first. + * + * @returns A object with a data property that contains an array of invoice objects. Throws an error if the + * customer ID is invalid. + * + * @param options Filtering options + */ + list(options: IListOptions, response: IResponseFn>): void; + } + + class Plans extends StripeResource { + /** + * You can create plans easily via the plan management page of the Stripe dashboard. Plan creation is also + * accessible via the API if you need to create plans on the fly. + * + * @returns The newly created plan + * + * @param options Options for the new plan. + */ + create(options: { + /** + * Unique string of your choice that will be used to identify this plan when subscribing a customer. + * This could be an identifier like "gold" or a primary key from your own database. + */ + id: string; + + /** + * A positive integer in cents (or 0 for a free plan) representing how much to charge (on a recurring basis). + */ + amount: number; + + /** + * 3-letter ISO code for currency. + */ + currency: string; + + /** + * Specifies billing frequency. Either day, week, month or year. + */ + interval: string; + + /** + * The number of intervals between each subscription billing. For example, interval=month and + * interval_count=3 bills every 3 months. Maximum of one year interval allowed (1 year, 12 months, + * or 52 weeks). + */ + interval_count?: number; + + /** + * Name of the plan, to be displayed on invoices and in the web interface. + */ + name: string; + + /** + * Specifies a trial period in (an integer number of) days. If you include a trial period, the customer + * won't be billed for the first time until the trial period ends. If the customer cancels before the + * trial period is over, she'll never be billed at all. + */ + trial_period_days?: number; + + /** + * A set of key/value pairs that you can attach to a plan object. It can be useful for storing additional + * information about the plan in a structured format. + */ + metadata?: IMetadata; + + /** + * An arbitrary string to be displayed on your customer's credit card statement. This may be up to 22 characters. + * As an example, if your website is RunClub and the item you're charging for is your Silver Plan, you may want + * to specify a statement_descriptor of RunClub Silver Plan. The statement description may not include <>"' + * characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are + * automatically stripped. While most banks display this information consistently, some may display it incorrectly + * or not at all. + */ + statement_descriptor?: string; + }, response: IResponseFn): void; + + /** + * Retrieves the plan with the given ID. + * + * @returns Returns a plan if a valid plan ID was provided. Throws an error otherwise. + * + * @param id The ID of the desired plan. + */ + retrieve(id: string, response: IResponseFn): void; + + /** + * Updates the name of a plan. Other plan details (price, interval, etc.) are, by design, not editable. + * + * @returns The updated plan object is returned upon success. Otherwise, this call throws an error. + * + * @param id The plan ID to update + * @param options The fields to update + */ + update(id: string, options: { + /** + * Name of the plan, to be displayed on invoices and in the web interface. + */ + name?: string; + + /** + * A set of key/value pairs that you can attach to a plan object. It can be useful for storing additional information + * about the plan in a structured format. You can unset an individual key by setting its value to null and then saving. + * To clear all keys, set metadata to null, then save. + */ + metadata?: IMetadata; + + /** + * An arbitrary string to be displayed on your customer's credit card statement. This may be up to 22 characters. + * As an example, if your website is RunClub and the item you're charging for is your Silver Plan, you may want + * to specify a statement_descriptor of RunClub Silver Plan. The statement description may not include <>"' + * characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are + * automatically stripped. While most banks display this information consistently, some may display it incorrectly + * or not at all. + */ + statement_descriptor?: string; + }, response: IResponseFn): void; + + /** + * You can delete plans via the plan management page of the Stripe dashboard. However, deleting a plan does not affect + * any current subscribers to the plan; it merely means that new subscribers can't be added to that plan. You can also + * delete plans via the API. + * + * @returns An object with the deleted plan's ID and a deleted flag upon success. Otherwise, this call throws an error, such as if the plan has already been deleted. + * + * @param id The identifier of the plan to be deleted. + */ + del(id: string, response: IResponseFn): void; + + /** + * Returns a list of your plans. + * + * @returns An object with a data property that contains an array of up to limit plans, starting after plan starting_after. + * Each entry in the array is a separate plan object. If no more plans are available, the resulting array will be empty. This + * request should never throw an error. You can optionally request that the response include the total count of all plans. To + * do so, specify include[]=total_count in your request. + */ + list(options: IListOptions, response: IResponseFn>): void; + } + + class RecipientCards extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + del(id: string): void; + } + + class Recipients extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + del(id: string): void; + } + + class Tokens extends StripeResource { + create(): void; + retrieve(id: string): void; + } + + class TransferReversals extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + } + + class Transfers extends StripeResource { + create(): void; + list(): void; + update(id: string): void; + retrieve(id: string): void; + } + } + + interface IResponseFn { + (err: IStripeError, value: R): void; + } + + interface IDeleteConfirmation { id: string; deleted: boolean; } + + /** + * Options for filtering a list by created period. + */ + interface IDateFilter { + /** + * Return values where the created field is after this timestamp. + */ + gt?: string; + + /** + * Return values where the created field is after or equal to this timestamp. + */ + gte?: string; + + /** + * Return values where the created field is before this timestamp. + */ + lt?: string; + + /** + * Return values where the created field is before or equal to this timestamp. + */ + lte?: string; + } + + /** + * A dispute occurs when a customer questions your charge with their bank or credit card company. + * When a customer disputes your charge, you're given the opportunity to respond to the dispute with + * evidence that shows the charge is legitimate. You can find more information about the dispute process + * in our disputes FAQ: https://stripe.com/help/disputes + */ + interface IDispute { + /** + * Valud is 'dispute' + */ + object: string; + livemode: boolean; + + /** + * Disputed amount. Usually the amount of the charge, but can differ (usually because of currency + * fluctuation or because only part of the order is disputed). + */ + amount: number; + + /** + * ID of the charge that was disputed + */ + charge: string; + + /** + * Date dispute was opened + */ + created: number; + + /** + * Three-letter ISO currency code representing the currency of the amount that was disputed. + */ + currency: string; + + /** + * Reason given by cardholder for dispute. Possible values are duplicate, fraudulent, subscription_canceled, + * product_unacceptable, product_not_received, unrecognized, credit_not_processed, general. + * Read more about dispute reasons: https://stripe.com/help/disputes#reasons + */ + reason: string; + + /** + * Current status of dispute. Possible values are warning_needs_response, warning_under_review, warning_closed, + * needs_response, response_disabled, under_review, charge_refunded, won, lost. + */ + status: string; + + /** + * List of zero, one, or two balance transactions that show funds withdrawn and reinstated to your + * Stripe account as a result of this dispute. + */ + balance_transactions: Array; + + /** + * Evidence provided to respond to a dispute. Updating any field in the hash will submit all fields in the hash for review. + */ + evidence: IDisputeEvidence; + + /** + * Information about the evidence submission. + */ + evidence_details?: { + /** + * Whether or not evidence has been saved for this dispute. + */ + has_evidence: boolean; + + /** + * The number of times the evidence has been submitted. You may submit evidence a maximum of 5 times + */ + submission_count: number; + + /** + * Date by which evidence must be submitted in order to successfully challenge dispute. Will be null + * if the customer’s bank or credit card company doesn’t allow a response for this particular dispute. + */ + due_by: number; + + /** + * Whether or not the last evidence submission was submitted past the due date. Defaults to false + * if no evidence submissions have occurred. If true, then delivery of the latest evidence is not guaranteed. + */ + past_due: boolean; + }; + + /** + * If true, it is still possible to refund the disputed payment. Once the payment has been fully + * refunded, no further funds will be withdrawn from your Stripe account as a result of this dispute. + */ + is_charge_refundable: boolean; + metadata: IMetadata; + } + + interface IBankAccount { + id: string; + object: string; + + /** + * Two-letter ISO code representing the country the bank account is located in. + */ + country: string; + + /** + * Three-letter ISO currency code representing the currency paid out to the bank account. + */ + currency: string; + default_for_currency: boolean; + last4: string; + + /** + * Possible values are new, validated, verified, or errored. A bank account that hasn’t had any activity or validation performed + * is new. If Stripe can determine that the bank account exists, its status will be validated. Note that there often isn’t enough + * information to know (e.g. for smaller credit unions), and the validation is not always run. If the recipient or customer proves + * that they own the bank account (via microdeposit or login), the status will be verified. If a transfer sent to this bank account + * fails, we’ll set the status to errored and will not continue to send transfers until the bank details are updated. + */ + status: string; + + /** + * Name of the bank associated with the routing number, e.g. WELLS FARGO. + */ + bank_name: string; + + /** + * Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + */ + fingerprint: string; + + /** + * The routing transit number for the bank account. + */ + routing_number: string; + } + + interface IReversal { + id: string; + + /** + * Value is 'list' + */ + object: string; + + /** + * Amount reversed, in cents. + */ + amount: number; + created: number; + + /** + * Three-letter ISO currency code representing the currency. + */ + currency: string; + + /** + * Balance transaction that describes the impact of this reversal on your account balance. + */ + balance_transaction: string; + metadata: IMetadata; + + /** + * ID of the transfer that was reversed. + */ + transfer: string; + } + + interface IDisputeEvidence { + /** + * Any server or activity logs showing proof that the customer accessed or downloaded the purchased + * digital product. This information should include IP addresses, corresponding timestamps, and any + * detailed recorded activity. + */ + access_activity_log?: string; + + /** + * The billing addess provided by the customer. + */ + billing_address?: string; + + /** + * (ID of a file upload) Your subscription cancellation policy, as shown to the customer. + */ + cancellation_policy?: string; + + /** + * An explanation of how and when the customer was shown your refund policy prior to purchase. + */ + cancellation_policy_disclosure?: string; + + /** + * A justification for why the customer’s subscription was not canceled. + */ + cancellation_rebuttal?: string; + + /** + * (ID of a file upload) Any communication with the customer that you feel is relevant to your case (for + * example emails proving that they received the product or service, or demonstrating their use of or + * satisfaction with the product or service). + */ + customer_communication?: string; + + /** + * The email address of the customer. + */ + customer_email_address?: string; + + /** + * The name of the customer. + */ + customer_name?: string; + + /** + * The IP address that the customer used when making the purchase. + */ + customer_purchase_ip?: string; + + /** + * (ID of a file upload) A relevant document or contract showing the customer’s signature. + */ + customer_signature?: string; + + /** + * (ID of a file upload) Documentation for the prior charge that can uniquely identify the charge, + * such as a receipt, shipping label, work order, etc. This document should be paired with a similar + * document from the disputed payment that proves the two payments are separate. + */ + duplicate_charge_documentation?: string; + + /** + * An explanation of the difference between the disputed charge and the prior charge that appears to be a duplicate. + */ + duplicate_charge_explanation?: string; + + /** + * The Stripe ID for the prior charge which appears to be a duplicate of the disputed charge. + */ + duplicate_charge_id?: string; + + /** + * A description of the product or service which was sold. + */ + product_description?: string; + + /** + * (ID of a file upload) Any receipt or message sent to the customer notifying them of the charge. + */ + receipt?: string; + + /** + * (ID of a file upload) Your refund policy, as shown to the customer. + */ + refund_policy?: string; + + /** + * Documentation demonstrating that the customer was shown your refund policy prior to purchase. + */ + refund_policy_disclosure?: string; + + /** + * A justification for why the customer is not entitled to a refund. + */ + refund_refusal_explanation?: string; + + /** + * The date on which the customer received or began receiving the purchased service, in a clear human-readable format. + */ + service_date?: string; + + /** + * (ID of a file upload) Documentation showing proof that a service was provided to the customer. This could + * include a copy of a signed contract, work order, or other form of written agreement. + */ + service_documentation?: string; + + /** + * The address to which a physical product was shipped. You should try to include as much complete address information as possible. + */ + shipping_address?: string; + + /** + * The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. If multiple carriers were used + * for this purchase, please separate them with commas. + */ + shipping_carrier?: string; + + /** + * The date on which a physical product began its route to the shipping address, in a clear human-readable format. + */ + shipping_date?: string; + + /** + * (ID of a file upload) Documentation showing proof that a product was shipped to the customer at the same address + * the customer provided to you. This could include a copy of the shipment receipt, shipping label, etc, and should + * show the full shipping address of the customer, if possible. + */ + shipping_documentation?: string; + + /** + * The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers + * were generated for this purchase, please separate them with commas. + */ + shipping_tracking_number?: string; + + /** + * (ID of a file upload) Any additional evidence or statements. + */ + uncategorized_file?: string; + + /** + * Any additional evidence or statements. + */ + uncategorized_text?: string; + } + + /** + * To safely retry an API request without accidentally performing the same operation twice, + * you can attach a unique key to any POST request made to the Stripe API via the Idempotency-Key: header. + * For example, if a request to create a charge fails due to a network connection error, you can make + * a second request with the same key to guarantee that only a single charge is created. + * The creation of the key is completely up to you — we suggest using random strings or UUIDs. + * We'll always send back the same response for requests made with the same key, even if you make the request + * with different request parameters. The keys expire after 24 hours. + */ + interface IIdempotentOptions { + idempotency_key: string; + } + + /** + * A set of key/value pairs that you can attach to a reversal. It can be useful for storing + * additional information about the reversal in a structured format. + */ + interface IMetadata extends Object { } + + interface IShippingInformation { + /** + * Shipping address. + */ + address: { + /** + * Address line 1 (Street address/PO Box/Company name) + */ + line1: string; + + /** + * Address line 2 (Apartment/Suite/Unit/Building) + */ + line2: string; + + /** + * City/Suburb/Town/Village + */ + city: string; + + /** + * State/Province/County + */ + state: string; + + /** + * Zip/Postal Code + */ + postal_code: string; + + /** + * 2-letter country code + */ + country: string; + }; + + /** + * Recipient name. + */ + name: string; + + /** + * The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + */ + carrier: string; + + /** + * Recipient phone (including extension). + */ + phone: string; + + /** + * The tracking number for a physical product, obtained from the delivery service. If multiple + * tracking numbers were generated for this purchase, please separate them with commas. + */ + tracking_number: string; + } + + + interface IList { + /** + * Value is 'list' + */ + object: string; + + data: Array; + + has_more: boolean; + + /** + * The URL where this list can be accessed. + */ + url: string; + + /** + * The total number of items available. This value is not included by default, + * but you can request it by specifying ?include[]=total_count + */ + total_count: number; + } + + interface IPaymentToken { + id: string; + card: { + name: string; + address_line1: string; + address_line2: string; + address_city: string; + address_state: string; + address_zip: string; + address_country: string; + country: string; + exp_month: number; + exp_year: number; + last4: string; + object: string; + brand: string; + funding: string; + }; + created: number; + livemode: boolean; + type: string; + object: string; + used: boolean; + } + + /** + * You can store multiple cards on a customer in order to charge the customer later. You + * can also store multiple debit cards on a recipient in order to transfer to those cards later. + */ + interface ICard { + /** + * ID of card (used in conjunction with a customer or recipient ID) + */ + id: string; + + /** + * Value is 'card' + */ + object: string; + + /** + * The card number + */ + 'number': number; + + /** + * Card brand. Can be Visa, American Express, MasterCard, Discover, JCB, Diners Club, or Unknown. + */ + brand: string; + exp_month: number; + exp_year: number; + + /** + * Card funding type. Can be credit, debit, prepaid, or unknown + */ + funding: string; + last4: string; + address_city: string; + + /** + * Billing address country, if provided when creating card + */ + address_country: string; + address_line1: string; + + /** + * If address_line1 was provided, results of the check: pass, fail, unavailable, or unchecked. + */ + address_line1_check: string; + address_line2: string; + address_state: string; + address_zip: string; + + /** + * If address_zip was provided, results of the check: pass, fail, unavailable, or unchecked. + */ + address_zip_check: string; + + /** + * Two-letter ISO code representing the country of the card. You could use this + * attribute to get a sense of the international breakdown of cards you’ve collected. + */ + country: string; + + /** + * The customer that this card belongs to. This attribute will not be in the card object + * if the card belongs to a recipient instead. + */ + customer: string; + + /** + * If a CVC was provided, results of the check: pass, fail, unavailable, or unchecked + */ + cvc_check: string; + + /** + * (For Apple Pay integrations only.) The last four digits of the device account number. + */ + dynamic_last4: string; + + /** + * Cardholder name + */ + name: string; + + /** + * The recipient that this card belongs to. This attribute will not be in the card object if + * the card belongs to a customer instead. + */ + recipient: string; + + /** + * Uniquely identifies this particular card number. You can use this attribute to check + * whether two customers who’ve signed up with you are using the same card number, for example. + */ + fingerprint: string; + } + + interface IListOptions { + /** + * A filter on the list based on the object created field. The value can be a string with an integer Unix timestamp, or it can + * be a dictionary. + */ + created?: string | IDateFilter; + + /** + * A filter on the list based on the object date field. The value can be a string with an integer Unix timestamp, + * or it can be a dictionary. + */ + date?: string | IDateFilter; + + /** + * Only return charges for the customer specified by this customer ID. + */ + customer?: string; + + /** + * A cursor for use in pagination. ending_before is an object ID that defines your place in the list. For instance, if you make + * a list request and receive 100 objects, starting with obj_bar, your subsequent call can include ending_before=obj_bar in + * order to fetch the previous page of the list. + */ + ending_before?: string; + + /** + * A limit on the number of objects to be returned. Limit can range between 1 and 100 items. + */ + limit?: number; + + /** + * A cursor for use in pagination. starting_after is an object ID that defines your place in the list. For instance, if you make + * a list request and receive 100 objects, ending with obj_foo, your subsequent call can include starting_after=obj_foo in order + * to fetch the next page of the list. + */ + starting_after?: string; + } + + /** + * Stripe uses conventional HTTP response codes to indicate success or failure of an API request. + * In general, codes in the 2xx range indicate success, codes in the 4xx range indicate an error that + * resulted from the provided information (e.g. a required parameter was missing, a charge failed, etc.), + * and codes in the 5xx range indicate an error with Stripe's servers. Not all errors map cleanly onto HTTP + * response codes, however. When a request is valid but does not complete successfully (e.g. a card is + * declined), we return a 402 error code. + * + * 200 - OK Everything worked as expected. + * 400 - Bad Request Often missing a required parameter. + * 401 - Unauthorized No valid API key provided. + * 402 - Request Failed Parameters were valid but request failed. + * 404 - Not Found The requested item doesn't exist. + * 500, 502, 503, 504 - Server Errors Something went wrong on Stripe's end. + */ + interface IStripeError { + /** + * The type of error returned. Can be invalid_request_error, api_error, or card_error. + * + * + * invalid_request_error Invalid request errors arise when your request has invalid parameters. + * + * api_error API errors cover any other type of problem (e.g. a temporary problem with Stripe's + * servers) and should turn up only very infrequently. + * + * card_error Card errors are the most common type of error you should expect to handle. They result + * when the user enters a card that can't be charged for some reason. + */ + type: string; + + /** + * A human-readable message giving more details about the error. For card errors, these messages can + * be shown to your users. + */ + message?: string; + + /** + * For card errors, a short string from amongst those listed on the right describing the kind of card + * error that occurred. + * + * incorrect_number The card number is incorrect. + * invalid_number The card number is not a valid credit card number. + * invalid_expiry_month The card's expiration month is invalid. + * invalid_expiry_year The card's expiration year is invalid. + * invalid_cvc The card's security code is invalid. + * expired_card The card has expired. + * incorrect_cvc The card's security code is incorrect. + * incorrect_zip The card's zip code failed validation. + * card_declined The card was declined. + * missing There is no card on a customer that is being charged. + * processing_error An error occurred while processing the card. + * rate_limit An error occurred due to requests hitting the API too + * quickly. Please let us know if you're consistently running + * into this error. + */ + code?: string; + + /** + * The parameter the error relates to if the error is parameter-specific. You can use this to display a + * message near the correct form field, for example. + */ + param?: string; + } +} diff --git a/stripe/stripe.d.ts b/stripe/stripe.d.ts index 2d5005618..ca589e133 100644 --- a/stripe/stripe.d.ts +++ b/stripe/stripe.d.ts @@ -4,12 +4,12 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped interface StripeStatic { - setPublishableKey(key: string); + setPublishableKey(key: string): void; validateCardNumber(cardNumber: string): boolean; validateExpiry(month: string, year: string): boolean; validateCVC(cardCVC: string): boolean; cardType(cardNumber: string): string; - getToken(token: string, responseHandler: (status: number, response: StripeTokenResponse) => void); + getToken(token: string, responseHandler: (status: number, response: StripeTokenResponse) => void): void; card: StripeCardData; } @@ -58,7 +58,7 @@ interface StripeCardData { address_zip?: string; address_country?: string; - createToken(data: StripeTokenData, responseHandler: (status: number, response: StripeTokenResponse) => void); + createToken(data: StripeTokenData, responseHandler: (status: number, response: StripeTokenResponse) => void): void; } declare var Stripe: StripeStatic; diff --git a/strophe/strophe-tests.ts b/strophe/strophe-tests.ts new file mode 100644 index 000000000..78ffb3941 --- /dev/null +++ b/strophe/strophe-tests.ts @@ -0,0 +1,102 @@ +/// + +function log(msg: string): void { + console.log(msg); +} + +function rawInput(data: string): void { + log('RECV: ' + data); +} + +function rawOutput(data: string): void { + log('SENT: ' + data); +} + +function onOwnMessage(msg: HTMLElement): boolean { + + console.log(msg); + var elems = msg.getElementsByTagName('own-message'); + if (elems.length > 0) { + var own = elems[0]; + var to = msg.getAttribute('to'); + var from = msg.getAttribute('from'); + var iq = $iq({ + to: from, + type: 'error', + id: msg.getAttribute('id') + }).cnode(own).up().c('error', { type: 'cancel', code: '501' }) + .c('feature-not-implemented', { xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' }); + + connection.sendIQ(iq); + } + + return true; +} + +function onMessage(msg: Element): boolean { + var to = msg.getAttribute('to'); + var from = msg.getAttribute('from'); + var type = msg.getAttribute('type'); + var elems = msg.getElementsByTagName('body'); + + if (type == "chat" && elems.length > 0) { + var body = elems[0]; + + log('ECHOBOT: I got a message from ' + from + ': ' + + Strophe.getText(body)); + + var text = Strophe.getText(body) + " (this is echo)"; + + //var reply = $msg({to: from, from: to, type: 'chat', id: 'purple4dac25e4'}).c('active', {xmlns: "http://jabber.org/protocol/chatstates"}).up().cnode(body); + //.cnode(Strophe.copyElement(body)); + //connection.send(reply.tree()); + + log('ECHOBOT: I sent ' + from + ': ' + Strophe.getText(body)); + } + + // we must return true to keep the handler alive. + // returning false would remove it after it finishes. + return true; +} + + +function sendMessage() { + var message = "some message"; + var to = "some recipient"; + if (message && to) { + var reply = $msg({ + to: to, + type: 'chat' + }) + .cnode(Strophe.xmlElement('body', message)).up() + .c('active', { xmlns: "http://jabber.org/protocol/chatstates" }); + + connection.send(reply); + + log('I sent ' + to + ': ' + message); + } +} + +var connection = new Strophe.Connection("someservice"); +connection.rawInput = rawInput; +connection.rawOutput = rawOutput; + +function onConnect(status: Strophe.Status): void { + if (status == Strophe.Status.CONNECTING) { + log('Strophe is connecting.'); + } else if (status == Strophe.Status.CONNFAIL) { + log('Strophe failed to connect.'); + } else if (status == Strophe.Status.DISCONNECTING) { + log('Strophe is disconnecting.'); + } else if (status == Strophe.Status.DISCONNECTED) { + log('Strophe is disconnected.'); + } else if (status == Strophe.Status.CONNECTED) { + log('Strophe is connected.'); + log('ECHOBOT: Send a message to ' + connection.jid + + ' to talk to me.'); + + connection.addHandler(onMessage, null, 'message', null, null, null); + connection.addHandler(onOwnMessage, null, 'iq', 'set', null, null); + connection.send($pres().tree()); + } +} diff --git a/strophe/strophe.d.ts b/strophe/strophe.d.ts new file mode 100644 index 000000000..b8fc33989 --- /dev/null +++ b/strophe/strophe.d.ts @@ -0,0 +1,1068 @@ +// Type definitions for Strophe.js v1.2.0 +// Project: http://strophe.im/strophejs/ +// Definitions by: David Deutsch +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** Function: $build + * Create a Strophe.Builder. + * This is an alias for 'new Strophe.Builder(name, attrs)'. + * + * Parameters: + * (String) name - The root element name. + * (Object) attrs - The attributes for the root element in object notation. + * + * Returns: + * A new Strophe.Builder object. + */ +declare function $build(name: string, attrs?: any): Strophe.Builder; + +/** Function: $msg + * Create a Strophe.Builder with a element as the root. + * + * Parmaeters: + * (Object) attrs - The element attributes in object notation. + * + * Returns: + * A new Strophe.Builder object. + */ +declare function $msg(attrs?: any): Strophe.Builder; + +/** Function: $iq + * Create a Strophe.Builder with an element as the root. + * + * Parameters: + * (Object) attrs - The element attributes in object notation. + * + * Returns: + * A new Strophe.Builder object. + */ +declare function $iq(attrs?: any): Strophe.Builder; + +/** Function: $pres + * Create a Strophe.Builder with a element as the root. + * + * Parameters: + * (Object) attrs - The element attributes in object notation. + * + * Returns: + * A new Strophe.Builder object. + */ +declare function $pres(attrs?: any): Strophe.Builder; + +declare module Strophe { + /** Constant: VERSION + * The version of the Strophe library. Unreleased builds will have + * a version of head-HASH where HASH is a partial revision. + */ + var VERSION: string; + + /** Constants: XMPP Namespace Constants + * Common namespace constants from the XMPP RFCs and XEPs. + * + * NS.HTTPBIND - HTTP BIND namespace from XEP 124. + * NS.BOSH - BOSH namespace from XEP 206. + * NS.CLIENT - Main XMPP client namespace. + * NS.AUTH - Legacy authentication namespace. + * NS.ROSTER - Roster operations namespace. + * NS.PROFILE - Profile namespace. + * NS.DISCO_INFO - Service discovery info namespace from XEP 30. + * NS.DISCO_ITEMS - Service discovery items namespace from XEP 30. + * NS.MUC - Multi-User Chat namespace from XEP 45. + * NS.SASL - XMPP SASL namespace from RFC 3920. + * NS.STREAM - XMPP Streams namespace from RFC 3920. + * NS.BIND - XMPP Binding namespace from RFC 3920. + * NS.SESSION - XMPP Session namespace from RFC 3920. + * NS.XHTML_IM - XHTML-IM namespace from XEP 71. + * NS.XHTML - XHTML body namespace from XEP 71. + */ + var NS: { + HTTPBIND: string; + BOSH: string; + CLIENT: string; + AUTH: string; + ROSTER: string; + PROFILE: string; + DISCO_INFO: string; + DISCO_ITEMS: string; + MUC: string; + SASL: string; + STREAM: string; + FRAMING: string; + BIND: string; + SESSION: string; + VERSION: string; + STANZAS: string; + XHTML_IM: string; + XHTML: string; + } + + /** Constants: Connection Status Constants + * Connection status constants for use by the connection handler + * callback. + * + * Status.ERROR - An error has occurred + * Status.CONNECTING - The connection is currently being made + * Status.CONNFAIL - The connection attempt failed + * Status.AUTHENTICATING - The connection is authenticating + * Status.AUTHFAIL - The authentication attempt failed + * Status.CONNECTED - The connection has succeeded + * Status.DISCONNECTED - The connection has been terminated + * Status.DISCONNECTING - The connection is currently being terminated + * Status.ATTACHED - The connection has been attached + */ + enum Status { + ERROR, + CONNECTING, + CONNFAIL, + AUTHENTICATING, + AUTHFAIL, + CONNECTED, + DISCONNECTED, + DISCONNECTING, + ATTACHED, + REDIRECT + } + + /** Constants: Log Level Constants + * Logging level indicators. + * + * LogLevel.DEBUG - Debug output + * LogLevel.INFO - Informational output + * LogLevel.WARN - Warnings + * LogLevel.ERROR - Errors + * LogLevel.FATAL - Fatal errors + */ + enum LogLevel { + DEBUG, + INFO, + WARN, + ERROR, + FATAL + } + + /** Function: addNamespace + * This function is used to extend the current namespaces in + * Strophe.NS. It takes a key and a value with the key being the + * name of the new namespace, with its actual value. + * For example: + * Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub"); + * + * Parameters: + * (String) name - The name under which the namespace will be + * referenced under Strophe.NS + * (String) value - The actual namespace. + */ + function addNamespace(name: string, value: string): void; + + /** Function: forEachChild + * Map a function over some or all child elements of a given element. + * + * This is a small convenience function for mapping a function over + * some or all of the children of an element. If elemName is null, all + * children will be passed to the function, otherwise only children + * whose tag names match elemName will be passed. + * + * Parameters: + * (XMLElement) elem - The element to operate on. + * (String) elemName - The child element tag name filter. + * (Function) func - The function to apply to each child. This + * function should take a single argument, a DOM element. + */ + function forEachChild(elem: Element, elemName: string, func:(child: Element) => any): void; + + /** Function: isTagEqual + * Compare an element's tag name with a string. + * + * This function is case sensitive. + * + * Parameters: + * (XMLElement) el - A DOM element. + * (String) name - The element name. + * + * Returns: + * true if the element's tag name matches _el_, and false + * otherwise. + */ + function isTagEqual(el: Element, name: string): boolean; + + /** Function: xmlGenerator + * Get the DOM document to generate elements. + * + * Returns: + * The currently used DOM document. + */ + function xmlGenerator(): Document; + + /** Function: xmlElement + * Create an XML DOM element. + * + * This function creates an XML DOM element correctly across all + * implementations. Note that these are not HTML DOM elements, which + * aren't appropriate for XMPP stanzas. + * + * Parameters: + * (String) name - The name for the element. + * (Array|Object) attrs - An optional array or object containing + * key/value pairs to use as element attributes. The object should + * be in the format {'key': 'value'} or {key: 'value'}. The array + * should have the format [['key1', 'value1'], ['key2', 'value2']]. + * (String) text - The text child data for the element. + * + * Returns: + * A new XML DOM element. + */ + function xmlElement(name: string, attrs?: any, text?: string): Element; + function xmlElement(name: string, text?: string, attrs?: any): Element; + + /* Function: xmlescape + * Excapes invalid xml characters. + * + * Parameters: + * (String) text - text to escape. + * + * Returns: + * Escaped text. + */ + function xmlescape(text: string): string; + + /* Function: xmlunescape + * Unexcapes invalid xml characters. + * + * Parameters: + * (String) text - text to unescape. + * + * Returns: + * Unescaped text. + */ + function xmlunescape(text: string): string; + + /** Function: xmlTextNode + * Creates an XML DOM text node. + * + * Provides a cross implementation version of document.createTextNode. + * + * Parameters: + * (String) text - The content of the text node. + * + * Returns: + * A new XML DOM text node. + */ + function xmlTextNode(text: string): Text; + + /** Function: xmlHtmlNode + * Creates an XML DOM html node. + * + * Parameters: + * (String) html - The content of the html node. + * + * Returns: + * A new XML DOM text node. + */ + function xmlHtmlNode(html: string): Document; + + /** Function: getText + * Get the concatenation of all text children of an element. + * + * Parameters: + * (XMLElement) elem - A DOM element. + * + * Returns: + * A String with the concatenated text of all text element children. + */ + function getText(elem: Element): string; + + /** Function: copyElement + * Copy an XML DOM element. + * + * This function copies a DOM element and all its descendants and returns + * the new copy. + * + * Parameters: + * (XMLElement) elem - A DOM element. + * + * Returns: + * A new, copied DOM element tree. + */ + function copyElement(elem: Element): Element; + + /** Function: createHtml + * Copy an HTML DOM element into an XML DOM. + * + * This function copies a DOM element and all its descendants and returns + * the new copy. + * + * Parameters: + * (Element) elem - A DOM element. + * + * Returns: + * A new, copied DOM element tree. + */ + function createHtml(elem: Element): Element; + + /** Function: escapeNode + * Escape the node part (also called local part) of a JID. + * + * Parameters: + * (String) node - A node (or local part). + * + * Returns: + * An escaped node (or local part). + */ + function escapeNode(node: string): string; + + /** Function: unescapeNode + * Unescape a node part (also called local part) of a JID. + * + * Parameters: + * (String) node - A node (or local part). + * + * Returns: + * An unescaped node (or local part). + */ + function unescapeNode(node: string): string; + + /** Function: getNodeFromJid + * Get the node portion of a JID String. + * + * Parameters: + * (String) jid - A JID. + * + * Returns: + * A String containing the node. + */ + function getNodeFromJid(jid: string): string; + + /** Function: getDomainFromJid + * Get the domain portion of a JID String. + * + * Parameters: + * (String) jid - A JID. + * + * Returns: + * A String containing the domain. + */ + function getDomainFromJid(jid: string): string; + + /** Function: getResourceFromJid + * Get the resource portion of a JID String. + * + * Parameters: + * (String) jid - A JID. + * + * Returns: + * A String containing the resource. + */ + function getResourceFromJid(jid: string): string; + + /** Function: getBareJidFromJid + * Get the bare JID from a JID String. + * + * Parameters: + * (String) jid - A JID. + * + * Returns: + * A String containing the bare JID. + */ + function getBareJidFromJid(jid: string): string; + + /** Function: log + * User overrideable logging function. + * + * This function is called whenever the Strophe library calls any + * of the logging functions. The default implementation of this + * function does nothing. If client code wishes to handle the logging + * messages, it should override this with + * > Strophe.log = function (level, msg) { + * > (user code here) + * > }; + * + * Please note that data sent and received over the wire is logged + * via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput(). + * + * The different levels and their meanings are + * + * DEBUG - Messages useful for debugging purposes. + * INFO - Informational messages. This is mostly information like + * 'disconnect was called' or 'SASL auth succeeded'. + * WARN - Warnings about potential problems. This is mostly used + * to report transient connection errors like request timeouts. + * ERROR - Some error occurred. + * FATAL - A non-recoverable fatal error occurred. + * + * Parameters: + * (Integer) level - The log level of the log message. This will + * be one of the values in Strophe.LogLevel. + * (String) msg - The log message. + */ + function log(level: LogLevel, msg: string): void; + + /** Functions: debug, info, warn, error + * Log a message at the appropriate Strophe.LogLevel + * + * Parameters: + * (String) msg - The log message. + */ + function debug(msg: string): void; + function info(msg: string): void; + function warn(msg: string): void; + function error(msg: string): void; + function fatal(msg: string): void; + + /** Function: serialize + * Render a DOM element and all descendants to a String. + * + * Parameters: + * (XMLElement) elem - A DOM element. + * + * Returns: + * The serialized element tree as a String. + */ + function serialize(elem: Element | Builder): string; + + /** Function: addConnectionPlugin + * Extends the Strophe.Connection object with the given plugin. + * + * Parameters: + * (String) name - The name of the extension. + * (Object) ptype - The plugin's prototype. + */ + function addConnectionPlugin(name: string, ptype: any): void; + + var Builder: { + /** Constructor: Strophe.Builder + * Create a Strophe.Builder object. + * + * The attributes should be passed in object notation. For example + * > var b = new Builder('message', {to: 'you', from: 'me'}); + * or + * > var b = new Builder('messsage', {'xml:lang': 'en'}); + * + * Parameters: + * (String) name - The name of the root element. + * (Object) attrs - The attributes for the root element in object notation. + * + * Returns: + * A new Strophe.Builder. + */ + new (name: string, attrs?: any): Builder; + prototype: any; + } + + + /** Class: Strophe.Builder + * XML DOM builder. + * + * This object provides an interface similar to JQuery but for building + * DOM element easily and rapidly. All the functions except for toString() + * and tree() return the object, so calls can be chained. Here's an + * example using the $iq() builder helper. + * > $iq({to: 'you', from: 'me', type: 'get', id: '1'}) + * > .c('query', {xmlns: 'strophe:example'}) + * > .c('example') + * > .toString() + * The above generates this XML fragment + * > + * > + * > + * > + * > + * The corresponding DOM manipulations to get a similar fragment would be + * a lot more tedious and probably involve several helper variables. + * + * Since adding children makes new operations operate on the child, up() + * is provided to traverse up the tree. To add two children, do + * > builder.c('child1', ...).up().c('child2', ...) + * The next operation on the Builder will be relative to the second child. + */ + interface Builder { + /** Function: tree + * Return the DOM tree. + * + * This function returns the current DOM tree as an element object. This + * is suitable for passing to functions like Strophe.Connection.send(). + * + * Returns: + * The DOM tree as a element object. + */ + tree(): Element; + + /** Function: toString + * Serialize the DOM tree to a String. + * + * This function returns a string serialization of the current DOM + * tree. It is often used internally to pass data to a + * Strophe.Request object. + * + * Returns: + * The serialized DOM tree in a String. + */ + toString(): string; + + /** Function: up + * Make the current parent element the new current element. + * + * This function is often used after c() to traverse back up the tree. + * For example, to add two children to the same element + * > builder.c('child1', {}).up().c('child2', {}); + * + * Returns: + * The Stophe.Builder object. + */ + up(): Builder; + + /** Function: attrs + * Add or modify attributes of the current element. + * + * The attributes should be passed in object notation. This function + * does not move the current element pointer. + * + * Parameters: + * (Object) moreattrs - The attributes to add/modify in object notation. + * + * Returns: + * The Strophe.Builder object. + */ + attrs(moreattrs: any): Builder; + + /** Function: c + * Add a child to the current element and make it the new current + * element. + * + * This function moves the current element pointer to the child, + * unless text is provided. If you need to add another child, it + * is necessary to use up() to go back to the parent in the tree. + * + * Parameters: + * (String) name - The name of the child. + * (Object) attrs - The attributes of the child in object notation. + * (String) text - The text to add to the child. + * + * Returns: + * The Strophe.Builder object. + */ + c(name: string, attrs?: any, text?: string): Builder; + + /** Function: cnode + * Add a child to the current element and make it the new current + * element. + * + * This function is the same as c() except that instead of using a + * name and an attributes object to create the child it uses an + * existing DOM element object. + * + * Parameters: + * (XMLElement) elem - A DOM element. + * + * Returns: + * The Strophe.Builder object. + */ + cnode(elem: Node): Builder; + + /** Function: t + * Add a child text element. + * + * This *does not* make the child the new current element since there + * are no children of text elements. + * + * Parameters: + * (String) text - The text data to append to the current element. + * + * Returns: + * The Strophe.Builder object. + */ + t(text: string): Builder; + + /** Function: h + * Replace current element contents with the HTML passed in. + * + * This *does not* make the child the new current element + * + * Parameters: + * (String) html - The html to insert as contents of current element. + * + * Returns: + * The Strophe.Builder object. + */ + h(html: string): Builder; + } + + interface ConnectionOptions { + protocol?: string; + sync?: boolean; + } + var Connection: { + /** Constructor: Strophe.Connection + * Create and initialize a Strophe.Connection object. + * + * The transport-protocol for this connection will be chosen automatically + * based on the given service parameter. URLs starting with "ws://" or + * "wss://" will use WebSockets, URLs starting with "http://", "https://" + * or without a protocol will use BOSH. + * + * To make Strophe connect to the current host you can leave out the protocol + * and host part and just pass the path, e.g. + * + * > var conn = new Strophe.Connection("/http-bind/"); + * + * WebSocket options: + * + * If you want to connect to the current host with a WebSocket connection you + * can tell Strophe to use WebSockets through a "protocol" attribute in the + * optional options parameter. Valid values are "ws" for WebSocket and "wss" + * for Secure WebSocket. + * So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call + * + * > var conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"}); + * + * Note that relative URLs _NOT_ starting with a "/" will also include the path + * of the current site. + * + * Also because downgrading security is not permitted by browsers, when using + * relative URLs both BOSH and WebSocket connections will use their secure + * variants if the current connection to the site is also secure (https). + * + * BOSH options: + * + * by adding "sync" to the options, you can control if requests will + * be made synchronously or not. The default behaviour is asynchronous. + * If you want to make requests synchronous, make "sync" evaluate to true: + * > var conn = new Strophe.Connection("/http-bind/", {sync: true}); + * You can also toggle this on an already established connection: + * > conn.options.sync = true; + * + * + * Parameters: + * (String) service - The BOSH or WebSocket service URL. + * (Object) options - A hash of configuration options + * + * Returns: + * A new Strophe.Connection object. + */ + new (service: string, options?: ConnectionOptions): Connection; + prototype: any; + } + + /** Class: Strophe.Connection + * XMPP Connection manager. + * + * This class is the main part of Strophe. It manages a BOSH connection + * to an XMPP server and dispatches events to the user callbacks as + * data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, SASL SCRAM-SHA1 + * and legacy authentication. + * + * After creating a Strophe.Connection object, the user will typically + * call connect() with a user supplied callback to handle connection level + * events like authentication failure, disconnection, or connection + * complete. + * + * The user will also have several event handlers defined by using + * addHandler() and addTimedHandler(). These will allow the user code to + * respond to interesting stanzas or do something periodically with the + * connection. These handlers will be active once authentication is + * finished. + * + * To send data to the connection, use send(). + */ + interface Connection { + + jid: string; + authzid: string; + pass: string; + authcid: string; + domain: string; + servtype: string; + maxRetries: number; + //todo: what other members are meant to be public? + + /** Function: reset + * Reset the connection. + * + * This function should be called after a connection is disconnected + * before that connection is reused. + */ + reset(): void; + + /** Function: pause + * Pause the request manager. + * + * This will prevent Strophe from sending any more requests to the + * server. This is very useful for temporarily pausing + * BOSH-Connections while a lot of send() calls are happening quickly. + * This causes Strophe to send the data in a single request, saving + * many request trips. + */ + pause(): void; + + /** Function: resume + * Resume the request manager. + * + * This resumes after pause() has been called. + */ + resume(): void; + + /** Function: getUniqueId + * Generate a unique ID for use in elements. + * + * All stanzas are required to have unique id attributes. This + * function makes creating these easy. Each connection instance has + * a counter which starts from zero, and the value of this counter + * plus a colon followed by the suffix becomes the unique id. If no + * suffix is supplied, the counter is used as the unique id. + * + * Suffixes are used to make debugging easier when reading the stream + * data, and their use is recommended. The counter resets to 0 for + * every new connection for the same reason. For connections to the + * same server that authenticate the same way, all the ids should be + * the same, which makes it easy to see changes. This is useful for + * automated testing as well. + * + * Parameters: + * (String) suffix - A optional suffix to append to the id. + * + * Returns: + * A unique string to be used for the id attribute. + */ + getUniqueId(suffix?: string | number): string; + + /** Function: connect + * Starts the connection process. + * + * As the connection process proceeds, the user supplied callback will + * be triggered multiple times with status updates. The callback + * should take two arguments - the status code and the error condition. + * + * The status code will be one of the values in the Strophe.Status + * constants. The error condition will be one of the conditions + * defined in RFC 3920 or the condition 'strophe-parsererror'. + * + * The Parameters _wait_, _hold_ and _route_ are optional and only relevant + * for BOSH connections. Please see XEP 124 for a more detailed explanation + * of the optional parameters. + * + * Parameters: + * (String) jid - The user's JID. This may be a bare JID, + * or a full JID. If a node is not supplied, SASL ANONYMOUS + * authentication will be attempted. + * (String) pass - The user's password. + * (Function) callback - The connect callback function. + * (Integer) wait - The optional HTTPBIND wait value. This is the + * time the server will wait before returning an empty result for + * a request. The default setting of 60 seconds is recommended. + * (Integer) hold - The optional HTTPBIND hold value. This is the + * number of connections the server will hold at one time. This + * should almost always be set to 1 (the default). + * (String) route - The optional route value. + */ + connect(jid?: string, pass?: string, callback?: (status: Status, condition: string) => any, wait?: number, hold?: number, route?: string): void; + + /** Function: attach + * Attach to an already created and authenticated BOSH session. + * + * This function is provided to allow Strophe to attach to BOSH + * sessions which have been created externally, perhaps by a Web + * application. This is often used to support auto-login type features + * without putting user credentials into the page. + * + * Parameters: + * (String) jid - The full JID that is bound by the session. + * (String) sid - The SID of the BOSH session. + * (String) rid - The current RID of the BOSH session. This RID + * will be used by the next request. + * (Function) callback The connect callback function. + * (Integer) wait - The optional HTTPBIND wait value. This is the + * time the server will wait before returning an empty result for + * a request. The default setting of 60 seconds is recommended. + * Other settings will require tweaks to the Strophe.TIMEOUT value. + * (Integer) hold - The optional HTTPBIND hold value. This is the + * number of connections the server will hold at one time. This + * should almost always be set to 1 (the default). + * (Integer) wind - The optional HTTBIND window value. This is the + * allowed range of request ids that are valid. The default is 5. + */ + attach(jid: string, sid: string, rid: string, callback?: (status: Status, condition: string) => any, wait?: number, hold?: number, wind?: number): void; + + /** Function: xmlInput + * User overrideable function that receives XML data coming into the + * connection. + * + * The default function does nothing. User code can override this with + * > Strophe.Connection.xmlInput = function (elem) { + * > (user code) + * > }; + * + * Due to limitations of current Browsers' XML-Parsers the opening and closing + * tag for WebSocket-Connoctions will be passed as selfclosing here. + * + * BOSH-Connections will have all stanzas wrapped in a tag. See + * if you want to strip this tag. + * + * Parameters: + * (XMLElement) elem - The XML data received by the connection. + */ + xmlInput(elem: Element): void; + + /** Function: xmlOutput + * User overrideable function that receives XML data sent to the + * connection. + * + * The default function does nothing. User code can override this with + * > Strophe.Connection.xmlOutput = function (elem) { + * > (user code) + * > }; + * + * Due to limitations of current Browsers' XML-Parsers the opening and closing + * tag for WebSocket-Connoctions will be passed as selfclosing here. + * + * BOSH-Connections will have all stanzas wrapped in a tag. See + * if you want to strip this tag. + * + * Parameters: + * (XMLElement) elem - The XMLdata sent by the connection. + */ + xmlOutput(elem: Element): void; + + /** Function: rawInput + * User overrideable function that receives raw data coming into the + * connection. + * + * The default function does nothing. User code can override this with + * > Strophe.Connection.rawInput = function (data) { + * > (user code) + * > }; + * + * Parameters: + * (String) data - The data received by the connection. + */ + rawInput(data: string): void; + + /** Function: rawOutput + * User overrideable function that receives raw data sent to the + * connection. + * + * The default function does nothing. User code can override this with + * > Strophe.Connection.rawOutput = function (data) { + * > (user code) + * > }; + * + * Parameters: + * (String) data - The data sent by the connection. + */ + rawOutput(data: string): void; + + /** Function: send + * Send a stanza. + * + * This function is called to push data onto the send queue to + * go out over the wire. Whenever a request is sent to the BOSH + * server, all pending data is sent and the queue is flushed. + * + * Parameters: + * (XMLElement | + * [XMLElement] | + * Strophe.Builder) elem - The stanza to send. + */ + send(elem: Element | Element[]| Builder): void; + + /** Function: flush + * Immediately send any pending outgoing data. + * + * Normally send() queues outgoing data until the next idle period + * (100ms), which optimizes network use in the common cases when + * several send()s are called in succession. flush() can be used to + * immediately send all pending data. + */ + flush(): void; + + /** Function: sendIQ + * Helper function to send IQ stanzas. + * + * Parameters: + * (XMLElement) elem - The stanza to send. + * (Function) callback - The callback function for a successful request. + * (Function) errback - The callback function for a failed or timed + * out request. On timeout, the stanza will be null. + * (Integer) timeout - The time specified in milliseconds for a + * timeout to occur. + * + * Returns: + * The id used to send the IQ. + */ + sendIQ(elem: Element | Builder, callback?: (stanza: Element) => any, errback?: (stanza: Element) => any, timeout?: number): string; //todo: Is callback correct? + + /** Function: addTimedHandler + * Add a timed handler to the connection. + * + * This function adds a timed handler. The provided handler will + * be called every period milliseconds until it returns false, + * the connection is terminated, or the handler is removed. Handlers + * that wish to continue being invoked should return true. + * + * Because of method binding it is necessary to save the result of + * this function if you wish to remove a handler with + * deleteTimedHandler(). + * + * Note that user handlers are not active until authentication is + * successful. + * + * Parameters: + * (Integer) period - The period of the handler. + * (Function) handler - The callback function. + * + * Returns: + * A reference to the handler that can be used to remove it. + */ + addTimedHandler(period: number, handler: () => boolean): any; + + /** Function: deleteTimedHandler + * Delete a timed handler for a connection. + * + * This function removes a timed handler from the connection. The + * handRef parameter is *not* the function passed to addTimedHandler(), + * but is the reference returned from addTimedHandler(). + * + * Parameters: + * (Strophe.TimedHandler) handRef - The handler reference. + */ + deleteTimedHandler(handRef: any): void; + + + /** Function: addHandler + * Add a stanza handler for the connection. + * + * This function adds a stanza handler to the connection. The + * handler callback will be called for any stanza that matches + * the parameters. Note that if multiple parameters are supplied, + * they must all match for the handler to be invoked. + * + * The handler will receive the stanza that triggered it as its argument. + * *The handler should return true if it is to be invoked again; + * returning false will remove the handler after it returns.* + * + * As a convenience, the ns parameters applies to the top level element + * and also any of its immediate children. This is primarily to make + * matching /iq/query elements easy. + * + * The options argument contains handler matching flags that affect how + * matches are determined. Currently the only flag is matchBare (a + * boolean). When matchBare is true, the from parameter and the from + * attribute on the stanza will be matched as bare JIDs instead of + * full JIDs. To use this, pass {matchBare: true} as the value of + * options. The default value for matchBare is false. + * + * The return value should be saved if you wish to remove the handler + * with deleteHandler(). + * + * Parameters: + * (Function) handler - The user callback. + * (String) ns - The namespace to match. + * (String) name - The stanza name to match. + * (String) type - The stanza type attribute to match. + * (String) id - The stanza id attribute to match. + * (String) from - The stanza from attribute to match. + * (String) options - The handler options + * + * Returns: + * A reference to the handler that can be used to remove it. + */ + addHandler(handler: (stanza: Element) => boolean, ns: string, name: string, type?: string, id?: string, from?: string, options?: { matchBare: boolean }): any; //todo: is callback correct? Also, are the elements specified as optional truly optional? + + /** Function: deleteHandler + * Delete a stanza handler for a connection. + * + * This function removes a stanza handler from the connection. The + * handRef parameter is *not* the function passed to addHandler(), + * but is the reference returned from addHandler(). + * + * Parameters: + * (Strophe.Handler) handRef - The handler reference. + */ + deleteHandler(handRef: any): void; + + /** Function: disconnect + * Start the graceful disconnection process. + * + * This function starts the disconnection process. This process starts + * by sending unavailable presence and sending BOSH body of type + * terminate. A timeout handler makes sure that disconnection happens + * even if the BOSH server does not respond. + * If the Connection object isn't connected, at least tries to abort all pending requests + * so the connection object won't generate successful requests (which were already opened). + * + * The user supplied connection callback will be notified of the + * progress as this process happens. + * + * Parameters: + * (String) reason - The reason the disconnect is occuring. + */ + disconnect(reason: string): void; + } + + /** Interface: Strophe.SASLMechanism + * + * encapsulates SASL authentication mechanisms. + * + * User code may override the priority for each mechanism or disable it completely. + * See for information about changing priority and for informatian on + * how to disable a mechanism. + * + * By default, all mechanisms are enabled and the priorities are + * + * SCRAM-SHA1 - 40 + * DIGEST-MD5 - 30 + * Plain - 20 + */ + interface SASLMechanism { + /** + * Function: test + * Checks if mechanism able to run. + * To disable a mechanism, make this return false; + * + * To disable plain authentication run + * > Strophe.SASLPlain.test = function() { + * > return false; + * > } + * + * See for a list of available mechanisms. + * + * Parameters: + * (Strophe.Connection) connection - Target Connection. + * + * Returns: + * (Boolean) If mechanism was able to run. + */ + test(connection: Connection): boolean; + + /** Variable: priority + * Determines which is chosen for authentication (Higher is better). + * Users may override this to prioritize mechanisms differently. + * + * In the default configuration the priorities are + * + * SCRAM-SHA1 - 40 + * DIGEST-MD5 - 30 + * Plain - 20 + * + * Example: (This will cause Strophe to choose the mechanism that the server sent first) + * + * > Strophe.SASLMD5.priority = Strophe.SASLSHA1.priority; + * + * See for a list of available mechanisms. + * + */ + priority: number; + } + + /** Constants: SASL mechanisms + * Available authentication mechanisms + * + * Strophe.SASLAnonymous - SASL Anonymous authentication. + * Strophe.SASLPlain - SASL Plain authentication. + * Strophe.SASLMD5 - SASL Digest-MD5 authentication + * Strophe.SASLSHA1 - SASL SCRAM-SHA1 authentication + */ + var SASLAnonymous: SASLMechanism; + var SASLPlain: SASLMechanism; + var SASLSHA1: SASLMechanism; + var SASLMD5: SASLMechanism; +} + diff --git a/sweetalert/sweetalert-tests.ts b/sweetalert/sweetalert-tests.ts new file mode 100644 index 000000000..1ccb93ba3 --- /dev/null +++ b/sweetalert/sweetalert-tests.ts @@ -0,0 +1,93 @@ +/// + +// A basic message +swal("Here's a message!"); + +// A title with a text under +swal("Here's a message!", "It's pretty, isn't it?"); + +// A success message! +swal("Good job!", "You clicked the button!", "success"); + +// A warning message, with a function attached to the "Confirm"-button... +swal({ + title: "Are you sure?", + text: "You will not be able to recover this imaginary file!", + type: "warning", + showCancelButton: true, + confirmButtonColor: "#DD6B55", + confirmButtonText: "Yes, delete it!", + closeOnConfirm: false +}, + function () { + swal("Deleted!", "Your imaginary file has been deleted.", "success"); + }); + +// ... and by passing a parameter, you can execute something else for "Cancel". +swal({ + title: "Are you sure?", + text: "You will not be able to recover this imaginary file!", + type: "warning", + showCancelButton: true, + confirmButtonColor: "#DD6B55", + confirmButtonText: "Yes, delete it!", + cancelButtonText: "No, cancel plx!", + closeOnConfirm: false, + closeOnCancel: false +}, + function (isConfirm) { + if (isConfirm) { + swal("Deleted!", "Your imaginary file has been deleted.", "success"); + } else { + swal("Cancelled", "Your imaginary file is safe :)", "error"); + } + }); + +// A message with a custom icon +swal({ + title: "Sweet!", + text: "Here's a custom image.", + imageUrl: "images/thumbs-up.jpg" +}); + +// An HTML message +swal({ + title: "HTML Title!", + text: "A custom html message.", + html: true +}); + +// A message with auto close timer +swal({ + title: "Auto close alert!", + text: "I will close in 2 seconds.", + timer: 2000, + showConfirmButton: false +}); + +// A replacement for the "prompt" function +swal({ + title: "An input!", + text: "Write something interesting:", + type: "input", + showCancelButton: true, + closeOnConfirm: false, + animation: "slide-from-top" +}, + function (inputValue) { + if (inputValue === false) return false; + + if (inputValue === "") { + swal.showInputError("You need to write something!"); + return false; + } + + swal("Nice!", "You wrote: " + inputValue, "success"); + } + ); + +swal.setDefaults({ confirmButtonColor: "#000000" }); + +swal.close(); + +swal.showInputError("Invalid email!"); \ No newline at end of file diff --git a/sweetalert/sweetalert.d.ts b/sweetalert/sweetalert.d.ts new file mode 100644 index 000000000..d5b4cd607 --- /dev/null +++ b/sweetalert/sweetalert.d.ts @@ -0,0 +1,181 @@ +// Type definitions for SweetAlert 0.5.0 +// Project: https://github.com/t4t5/sweetalert/ +// Definitions by: Markus Peloso +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var sweetAlert: SweetAlert.SweetAlertStatic; +declare var swal: SweetAlert.SweetAlertStatic; + +declare module "sweetalert" { + export = swal; +} + +declare module SweetAlert { + interface SettingsBase { + /** + * A description for the modal. + * Default: null + */ + text?: string; + + /** + * The type of the modal. SweetAlert comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". You can also set it as "input" to get a prompt modal. + * Default: null + */ + type?: string; + + /** + * If set to true, the user can dismiss the modal by pressing the Escape key. + * Default: true + */ + allowEsxcapeKey?: boolean; + + /** + * A custom CSS class for the modal. + * Default: null + */ + customClass?: string; + + /** + * If set to true, the user can dismiss the modal by clicking outside it. + * Default: false + */ + allowOutsideClick?: boolean; + + /** + * If set to true, a "Cancel"-button will be shown, which the user can click on to dismiss the modal. + * Default: false + */ + showCancelButton?: boolean; + + /** + * If set to false, the "OK/Confirm"-button will be hidden. Make sure you set a timer or set allowOutsideClick to true when using this, in order not to annoy the user. + * Default: true + */ + showConfirmButton?: boolean; + + /** + * Use this to change the text on the "Confirm"-button. If showCancelButton is set as true, the confirm button will automatically show "Confirm" instead of "OK". + * Default: "OK" + */ + confirmButtonText?: string; + + /** + * Use this to change the background color of the "Confirm"-button (must be a HEX value). + * Default: "#AEDEF4" + */ + confirmButtonColor?: string; + + /** + * Use this to change the text on the "Cancel"-button. + * Default: "Cancel" + */ + cancelButtonText?: string; + + /** + * Set to false if you want the modal to stay open even if the user presses the "Confirm"-button. This is especially useful if the function attached to the "Confirm"-button is another SweetAlert. + * Default: true + */ + closeOnConfirm?: boolean; + + /** + * Add a customized icon for the modal.Should contain a string with the path to the image. + * Default: null + */ + imageUrl?: string; + + /** + * If imageUrl is set, you can specify imageSize to describes how big you want the icon to be in px. Pass in a string with two values separated by an "x". The first value is the width, the second is the height. + * Default: "80x80" + */ + imageSize?: string; + + /** + * Auto close timer of the modal.Set in ms (milliseconds). + * Default: null + */ + timer?: number; + + /** + * If set to true, will not escape title and text parameters. (Set to false if you're worried about XSS attacks.) + * Default: false + */ + html?: boolean; + + /** + * If set to false, the modal's animation will be disabled. Possible animations: "slide-from-top", "slide-from-bottom", "pop" (use true instead) and "none" (use false instead). + * Default: true, "pop" + */ + animation?: boolean | string; + + /** + * Change the type of the input field when using type: "input" (this can be useful if you want users to type in their password for example). + * Default: "text" + */ + inputType?: string; + } + + interface Settings extends SettingsBase { + /** + * The title of the modal. + */ + title: string; + } + + interface SetDefaultsSettings extends SettingsBase { + /** + * The title of the modal. + * Default: null + */ + title?: string; + } + + /** + * Is true or false if the user confirms or cancels the alert. Except for the type "input", then when the user confirms the alert, this variable contains the value of the input element. + */ + type CallbackArgument = boolean | string; + + interface SweetAlertStatic { + /** + * SweetAlert automatically centers itself on the page and looks great no matter if you're using a desktop computer, mobile or tablet. An awesome replacement for JavaScript's alert. + * @param title The title of the modal. + */ + (title: string): void; + + /** + * SweetAlert automatically centers itself on the page and looks great no matter if you're using a desktop computer, mobile or tablet. An awesome replacement for JavaScript's alert. + * @param title The title of the modal. + * @param text A description for the modal. + */ + (title: string, text: string): void; + + /** + * SweetAlert automatically centers itself on the page and looks great no matter if you're using a desktop computer, mobile or tablet. An awesome replacement for JavaScript's alert. + * @param title The title of the modal. + * @param text A description for the modal. + * @param type The type of the modal. SweetAlert comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". You can also set it as "input" to get a prompt modal. + */ + (title: string, text: string, type: string): void; + + /** + * SweetAlert automatically centers itself on the page and looks great no matter if you're using a desktop computer, mobile or tablet. An awesome replacement for JavaScript's alert. + * @param callback The callback from the users action. The value is true or false if the user confirms or cancels the alert. Except for the type "input", then when the user confirms the alert, the argument contains the value of the input element. + */ + (settings: Settings, callback?: (isConfirmOrInputValue: CallbackArgument) => any): void; + + /** + * If you end up using a lot of the same settings when calling SweetAlert, you can use setDefaults at the start of your program to set them once and for all! + */ + setDefaults(settings: SetDefaultsSettings): void; + + /** + * Close the currently open SweetAlert programmatically. + */ + close(): void; + + /** + * Show an error message after validating the input field, if the user's data is bad. + */ + showInputError(errorMessage: string): void; + } +} \ No newline at end of file diff --git a/threejs/three.d.ts b/threejs/three.d.ts index b74844407..a9255f3b5 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1211,11 +1211,11 @@ declare module THREE { getObjectByProperty( name: string, value: string, recursive?: boolean ): Object3D; - getWorldPosition(optionalTarget: Vector3): Vector3; - getWorldQuaternion(optionalTarget: Quaternion): Quaternion; - getWorldRotation(optionalTarget: Euler): Euler; - getWorldScale(optionalTarget: Vector3): Vector3; - getWorldDirection(optionalTarget: Vector3): Vector3; + getWorldPosition(optionalTarget?: Vector3): Vector3; + getWorldQuaternion(optionalTarget?: Quaternion): Quaternion; + getWorldRotation(optionalTarget?: Euler): Euler; + getWorldScale(optionalTarget?: Vector3): Vector3; + getWorldDirection(optionalTarget?: Vector3): Vector3; /** * Translates object along arbitrary axis by distance. diff --git a/webcomponents.js/webcomponents.js-tests.ts b/webcomponents.js/webcomponents.js-tests.ts new file mode 100644 index 000000000..316f9dd8e --- /dev/null +++ b/webcomponents.js/webcomponents.js-tests.ts @@ -0,0 +1,39 @@ +/// + +/* + * Custom Elements + */ +var fooProto = Object.create(HTMLElement.prototype, { + createdCallback() { + // `this` should be the created element + this.getElementsByTagName("a"); + } +}); + +document.registerElement("x-foo", { + prototype: fooProto +}); + +window.CustomElements.hasNative; +window.CustomElements.flags; +window.CustomElements.ready; +window.CustomElements.useNative; + +/* + * HTMLImports + */ + +window.HTMLImports.isIE; +window.HTMLImports.rootDocument.querySelectorAll("div"); +window.HTMLImports.useNative; +window.HTMLImports.whenReady(() => { + return window.HTMLImports.ready === true; +}); + +document.querySelectorAll(`link[type=${window.HTMLImports.IMPORT_LINK_TYPE}`); + +/* + * Web Components + */ +window.WebComponents.flags; + diff --git a/webcomponents.js/webcomponents.js.d.ts b/webcomponents.js/webcomponents.js.d.ts new file mode 100644 index 000000000..43e85373f --- /dev/null +++ b/webcomponents.js/webcomponents.js.d.ts @@ -0,0 +1,48 @@ +// Type definitions for webcomponents.js 0.6.0 +// Project: https://github.com/webcomponents/webcomponentsjs +// Definitions by: Adi Dahiya +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module webcomponents { + + export interface CustomElementInit { + prototype: HTMLElement; + extends?: string; + } + + export interface CustomElementsPolyfill { + hasNative: boolean; + flags: any; + ready: boolean; + useNative: boolean; + } + + export interface HTMLImportsPolyfill { + IMPORT_LINK_TYPE: string; + isIE: boolean; + flags: any; + ready: boolean; + rootDocument: Document; + useNative: boolean; + whenReady(callback: () => void): void; + } + + export interface Polyfill { + flags: any; + } + +} + +declare module "webcomponents.js" { + export = webcomponents; +} + +interface Document { + registerElement(name: string, prototype: webcomponents.CustomElementInit): void; +} + +interface Window { + CustomElements: webcomponents.CustomElementsPolyfill; + HTMLImports: webcomponents.HTMLImportsPolyfill; + WebComponents: webcomponents.Polyfill; +} diff --git a/whatwg-fetch/whatwg-fetch-tests.ts b/whatwg-fetch/whatwg-fetch-tests.ts index cc3e6320a..5248f5d1d 100644 --- a/whatwg-fetch/whatwg-fetch-tests.ts +++ b/whatwg-fetch/whatwg-fetch-tests.ts @@ -11,6 +11,16 @@ function test_fetchUrlWithOptions() { handlePromise(window.fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions)); } +function test_fetchUrlWithHeadersObject() { + var requestOptions: RequestInit = { + method: "POST", + headers: { + 'Content-Type': 'application/json' + } + }; + handlePromise(window.fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions)); +} + function test_fetchUrl() { handlePromise(window.fetch("http://www.andlabs.net/html5/uCOR.php")); } @@ -21,4 +31,4 @@ function handlePromise(promise: Promise) { }).then((text) => { console.log(text); }); -} \ No newline at end of file +} diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index d847463bd..4a4a9612c 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -19,7 +19,7 @@ declare class Request { interface RequestInit { method?: string; - headers?: HeaderInit; + headers?: HeaderInit|{ [index: string]: string }; body?: BodyInit; mode?: RequestMode; credentials?: RequestCredentials; @@ -81,4 +81,4 @@ declare type RequestInfo = Request|string; interface Window { fetch(url: string, init?: RequestInit): Promise; -} \ No newline at end of file +} diff --git a/winrt/winrt.d.ts b/winrt/winrt.d.ts index 91c0a2801..883860b00 100644 --- a/winrt/winrt.d.ts +++ b/winrt/winrt.d.ts @@ -12203,8 +12203,8 @@ declare module Windows { createWithId(tileId: string): Windows.UI.StartScreen.SecondaryTile; } export class SecondaryTile implements Windows.UI.StartScreen.ISecondaryTile { - constructor(tileId: string, shortName: string, displayName: string, arguments: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri); - constructor(tileId: string, shortName: string, displayName: string, arguments: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri, wideLogoReference: Windows.Foundation.Uri); + constructor(tileId: string, shortName: string, displayName: string, args: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri); + constructor(tileId: string, shortName: string, displayName: string, args: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri, wideLogoReference: Windows.Foundation.Uri); constructor(tileId: string); constructor(); arguments: string; diff --git a/xrm/clientglobalcontext.d.ts b/xrm/clientglobalcontext.d.ts new file mode 100644 index 000000000..ae7bcc219 --- /dev/null +++ b/xrm/clientglobalcontext.d.ts @@ -0,0 +1,14 @@ +// Type definitions for Microsoft Dynamics xRM ClientGlobalContext.js.aspx +// Project: http://msdn.microsoft.com/en-us/library/gg328255.aspx +// Definitions by: David Berry +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * Gets the xRM application context, for HTML web resources + * @returns {Xrm.Context} The application context for the user's current session. + * @remarks The ClientGlobalContext.js.aspx page will include some global event handlers. These event handlers will + * cancel the onselectstart, contextmenu, and ondragstart events. + */ +declare function GetGlobalContext(): Xrm.Context; \ No newline at end of file diff --git a/xrm/parature.d.ts b/xrm/parature.d.ts new file mode 100644 index 000000000..030c97b68 --- /dev/null +++ b/xrm/parature.d.ts @@ -0,0 +1,143 @@ +// Type definitions for Microsoft Parature extentions to Xrm.Page - available for CRM Online Only +// Project: http://msdn.microsoft.com/en-us/library/gg328255.aspx +// Definitions by: David Berry +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Xrm.Page +{ + /** + * Interface for Parature's knowledge base search control. + * + * @sa Control + */ + export interface KbSearchControl extends Control + { + /** + * Use this method to add an event handler to the OnResultOpened event. + * + * @param {Function} handler The handler. + */ + addOnResultOpened( handler: () => void ): void; + + /** + * Use this method to add an event handler to the OnSelection event. + * + * @param {Function} handler The handler. + */ + addOnSelection( handler: () => void ): void; + + /** + * Use this method to get the text used as the search criteria for the knowledge base management control. + * + * @return The search query. + */ + getSearchQuery(): string; + + /** + * Use this method to get the currently selected result of the search control. The currently selected result also + * represents the result that is currently open. + * + * @return The selected result. + */ + getSelectedResult(): KbSearchResult; + + /** + * Use this method to remove an event handler from the OnResultOpened event. + * + * @param {Function} handler The handler. + */ + removeOnResultOpened( handler: () => void ): void; + + /** + * Use this method to remove an event handler from the OnSelection event. + * + * @param {Function} handler The handler. + */ + removeOnSelection( handler: () => void ): void; + + /** + * Use this method to set the text used as the search criteria for the knowledge base management control. + * + * @param {string} query The text for the search query. + */ + setSearchQuery( query: string ): void; + } + + /** + * Interface for a Parature knowledge base search result. + */ + export interface KbSearchResult + { + /** + * The HTML markup containing the content of the article. + */ + answer: string; + + /** + * The Article ID in a Parature department + */ + articleId: string; + + /** + * Unique Article ID for the Parature system. + */ + articleUid: string; + + /** + * The date the article was created. + */ + createdOn: Date; + + /** + * The date the article was or will be expired. + */ + expiredDate: Date; + + /** + * Whether the article is associated with the parent record or not + */ + isAssociated: boolean; + + /** + * Date on which the article was last modified. + */ + lastModifiedOn: Date; + + /** + * Support Portal URL of the article. + */ + publicUrl: string; + + /** + * Whether the Article is in published or draft state. + */ + published: boolean; + + /** + * The title of the article. + */ + question: string; + + /** + * The rating of the article. + */ + rating: number; + + /** + * A short snippet of article content which contains the areas where the search query was hit. + */ + searchBlurb: string; + + /** + * Link to the article in the Parature service desk. + */ + serviceDeskUri: string; + + /** + * The number of times an article is viewed on the Parature portal by customers. + */ + timesViewed: number; + } +} diff --git a/xrm/xrm-6.d.ts b/xrm/xrm-6.d.ts new file mode 100644 index 000000000..f2a88eb44 --- /dev/null +++ b/xrm/xrm-6.d.ts @@ -0,0 +1,2071 @@ +// Type definitions for Microsoft Dynamics xRM API v6 +// Project: http://msdn.microsoft.com/en-us/library/gg328255.aspx +// Definitions by: David Berry +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Xrm +{ + /** + * Interface for the client context. + */ + export interface ClientContext + { + /** + * Returns a value to indicate which client the script is executing in. + * + * @return The client, as either "Web", "Outlook", or "Mobile" + */ + getClient(): string; + + /** + * Gets client's current state. + * + * @return The client state, as either "Online" or "Offline" + */ + getClientState(): string; + } + + /** + * Interface for the xRM application context. + */ + export interface Context + { + /** + * The client's context instance. + */ + client: ClientContext; + + /** + * Gets client's base URL for Dynamics CRM + * + * @return The client's base URL + * @remarks For Dynamics CRM On-Premises: http(s)://server/org + * For Dynamics CRM Online: https://org.crm.dynamics.com + * For Dynamics CRM for Outlook (Offline): http://localhost:2525 + */ + getClientUrl(): string; + + /** + * Gets current styling theme. + * + * @return The name of the current theme, as either "default", "Office12Blue", or "Office14Silver" + * + * @remarks This function does not work with Dynamics CRM for tablets. + */ + getCurrentTheme(): string; + + /** + * Gets organization's LCID (language code). + * + * @return The organization language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getOrgLcid(): number; + + /** + * Gets organization's unique name. + * + * @return The organization's unique name. + * + * @remarks This value can be found on the Developer Resources page within Dynamics CRM + */ + getOrgUniqueName(): string; + + /** + * Gets query string parameters. + * + * @return The query string parameters, in a dictionary object representing name and value pairs. + */ + getQueryStringParameters(): { [index: string]: any }; + + /** + * Gets user's unique identifier. + * + * @return The user's identifier in Guid format. + * + * @remarks Example: "{B05EC7CE-5D51-DF11-97E0-00155DB232D0}" + */ + getUserId(): string; + + /** + * Gets user's LCID (language code). + * + * @return The user's language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getUserLcid(): number; + + /** + * Gets the name of the current user. + * + * @return The user's name. + */ + getUserName(): string; + + /** + * Gets all user security roles. + * + * @return An array of user role identifiers, in Guid format. + * + * @remarks Example: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"] + */ + getUserRoles(): string[]; + + /** + * Prefixes the current organization's unique name to a string; typically a URL path. + * + * @param {string} sPath Local pathname of the resource. + * + * @return A path string with the organization name. + * + * @remarks Format: "/"+ OrgName + sPath + */ + prependOrgName( sPath: string ): string; + } + + /** + * A definition module for asynchronous interface declarations. + */ + export module Async + { + /** + * Interface for success callbacks. + */ + export interface SuccessCallbackDelegate + { + /** + * Called when the operation is successful. + */ + (): void; + } + + /** + * Interface for error callbacks. + */ + export interface ErrorCallbackDelegate + { + /** + * Called when the operation fails. + * + * @param {number} errorCode The error code. + * @param {string} message The message. + */ + ( errorCode: number, message: string ): void; + } + + /** + * Interface for Xrm.Page.data promises. + */ + export interface XrmPromise + { + /** + * A basic 'then' promise. + * + * @param {SuccessCallbackDelegate} successCallback The success callback. + * @param {ErrorCallbackDelegate} errorCallback The error callback. + */ + then( successCallback: SuccessCallbackDelegate, errorCallback: ErrorCallbackDelegate ): void; + } + } + + /** + * A definition module for collection interface declarations. + */ + export module Collection + { + /** + * Interface for a matching delegate. + * + * @tparam T Generic type parameter. + */ + export interface MatchingDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + * + * @return true if the item matches, false if it does not. + */ + ( item: T, index?: number ): boolean; + } + + /** + * Interface for iterative delegate. + * + * @tparam T Generic type parameter. + */ + export interface IterativeDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + */ + ( item: T, index?: number ): void; + } + + /** + * Interface for an item collection. + * + * @tparam T Generic type parameter. + */ + export interface ItemCollection + { + /** + * Applies an operation to all items in this collection. + * + * @param {IterativeDelegate{T}} delegate An iterative delegate function + */ + forEach( delegate: IterativeDelegate ): void; + + /** + * Gets. + * + * @param {MatchingDelegate{T}} delegate A matching delegate function + * + * @return A T[] whose members have been validated by delegate. + */ + get( delegate: MatchingDelegate ): T[]; + + /** + * Gets the item given by the index. + * + * @param {number} itemNumber The item number to get. + * + * @return The T in the itemNumber-th place. + */ + get( itemNumber: number ): T; + + /** + * Gets the item given by the key. + * + * @param {string} itemName The item name to get. + * + * @return The T matching the key itemName. + * + * @see {@link Xrm.Page.Control.getName()} for Control-naming schemes. + */ + get( itemName: string ): T; + + /** + * Gets the entire array of T. + * + * @return A T[]. + */ + get(): T[]; + + /** + * Gets the length of the collection. + * + * @return The length. + */ + getLength(): number; + } + } + + /** + * The Xrm.Page API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Page + { + /** + * Enumeration of entity form states/types. + */ + export const enum FormType + { + Undefined = 0, + Create = 1, + Update = 2, + ReadOnly = 3, + Disabled = 4, + BulkEdit = 6 + } + + /** + * Enumeration of entity form save modes. + */ + export const enum SaveMode + { + Save = 1, + SaveAndClose = 2, + SaveAndNew = 59, + AutoSave = 70, + SaveAsCompleted = 58, + Deactivate = 5, + Reactivate = 6, + Assign = 47, + Send = 7, + Qualify = 16, + Disqualify = 15 + } + + /** + * Interface for the event context. + */ + export interface EventContext + { + /** + * Gets the Xrm context. + * + * @return The Xrm context. + */ + getContext(): Context; + + /** + * Gets the handler's depth, which is the order in which the handler is executed. + * + * @return The depth, a 0-based index. + */ + getDepth(): number; + + /** + * Gets save-event arguments. + * + * @return The event arguments. + * + * @remarks Returns null for all but the "save" event. + */ + getEventArgs(): SaveEventArguments; + + /** + * Gets a reference to the object for which event occurred. + * + * @return The event source. + */ + getEventSource(): Xrm.Page.Attribute | Xrm.Page.Entity; + + /** + * Gets the shared variable with the specified key. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * + * @return The shared variable. + * + * @remarks Used to pass values between handlers of an event. + */ + getSharedVariable( key: string ): T; + + /** + * Sets a shared variable. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * @param {T} value The value. + * + * @remarks Used to pass values between handlers of an event. + */ + setSharedVariable( key: string, value: T ): void; + } + + /** + * Interface for a context-sensitive handler. + */ + export interface ContextSensitiveHandler + { + /** + * @param {EventContext} context The context. + */ + ( context?: EventContext ): void; + } + + /** + * Base interface for UI elements. + */ + export interface UiElement + { + /** + * Gets the label. + * + * @return The label. + */ + getLabel(): string; + + /** + * Gets the visibility state. + * + * @return true if the tab is visible, otherwise false. + */ + getVisible(): boolean; + + /** + * Sets the label. + * + * @param {string} label The label. + */ + setLabel( label: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for focusable UI elements. + */ + export interface UiFocusable + { + /** + * Sets focus on the element. + */ + setFocus(): void; + } + + /** + * Interface for a Lookup value. + */ + export interface LookupValue + { + /** + * The identifier. + */ + id: string; + + /** + * The name + */ + name?: string; + + /** + * Type of the entity. + */ + entityType: string; + } + + /** + * Interface for an OptionSet value. + */ + export interface OptionSetValue + { + /** + * The label text. + */ + text: string; + + /** + * The value, as a string. + * + * @remarks You must use parseInt to convert this value to a number before you can use it to + * set the value of an OptionSetAttribute. + */ + value: string; + } + + /** + * Interface for a privilege. + */ + export interface Privilege + { + /** + * true if the user can read. + */ + canRead: boolean; + + /** + * true if the user can update. + */ + canUpdate: boolean; + + /** + * true if the user can create. + */ + canCreate: boolean; + } + + /** + * Interface for an Entity attribute. + */ + export interface Attribute + { + /** + * A collection of all the controls on the form that interface with this attribute. + */ + controls: Collection.ItemCollection; + + /** + * Adds a handler to be called when the attribute's value is changed. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Fire all "on change" event handlers. + */ + fireOnChange(): void; + + /** + * Gets attribute type. + * + * @return The attribute's type name. + * + * @remarks Values returned are: boolean + * datetime + * decimal + * double + * integer + * lookup + * memo + * money + * optionset + * string + */ + getAttributeType(): string; + + /** + * Gets the attribute format. + * + * @return The format of the attribute. + * + * @see {@link getAttributeType()} + * + * @remarks Values returned are: date (datetime) + * datetime (datetime) + * duration (integer) + * email (string) + * language (optionset) + * none (integer) + * phone (string) + * text (string) + * textarea (string) + * tickersymbol (string) + * timezone (optionset) + * url (string) + */ + getFormat(): string; + + /** + * Gets a boolean value indicating whether this Attribute has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the logical name of the attribute. + * + * @return The logical name. + */ + getName(): string; + + /** + * Gets a reference to the record context of this attribute. + * + * @return The parent record context. + */ + getParent(): Entity; + + /** + * Gets the current level of requirement for the attribute. + * + * @return The required level, as either "none", "required", or "recommended" + */ + getRequiredLevel(): string; + + /** + * Gets current submit mode for the attribute. + * + * @return The submit mode, as either "always", "never", or "dirty" + * + * @remarks The default value is "dirty" + */ + getSubmitMode(): string; + + /** + * Gets the current user's privileges for the attribute. + * + * @return The user privileges. + */ + getUserPrivilege(): Privilege; + + /** + * Removes the handler from the "on change" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Sets required level. + * + * @param {"none"} requirementLevel Not required. + */ + setRequiredLevel( requirementLevel: "none" ): void; + + /** + * Sets required level. + * + * @param {"required"} requirementLevel Required. + */ + setRequiredLevel( requirementLevel: "required" ): void; + + /** + * Sets required level. + * + * @param {"recommended"} requirementLevel Recommended. + */ + setRequiredLevel( requirementLevel: "recommended" ): void; + + /** + * Sets the required level. + * + * @param {string} requirementLevel The requirement level, as either "none", "required", or "recommended" + */ + setRequiredLevel( requirementLevel: string ): void; + + /** + * Sets submit mode. + * + * @param {"always"} submitMode Always submit this attribute. + */ + setSubmitMode( submitMode: "always" ): void; + + /** + * Sets submit mode. + * + * @param {"never"} submitMode Never submit this attribute. + */ + setSubmitMode( submitMode: "never" ): void; + + /** + * Sets submit mode. + * + * @param {"dirty"} submitMode Submit this attribute when changed. + */ + setSubmitMode( submitMode: "dirty" ): void; + + /** + * Sets the submit mode. + * + * @param {string} submitMode The submit mode, as either "always", "never", or "dirty". + * + * @remarks The default value is "dirty" + */ + setSubmitMode( submitMode: string ): void; + } + + /** + * Interface for a Number attribute. + * + * @sa Attribute + */ + export interface NumberAttribute extends Attribute + { + /** + * Gets the maximum value allowed. + * + * @return The maximum value allowed. + */ + getMax(): number; + + /** + * Gets the minimum value allowed. + * + * @return The minimum value allowed. + */ + getMin(): number; + + /** + * Gets the attribute's configured precision. + * + * @return The total number of allowed decimal places. + */ + getPrecision(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface for a String attribute. + * + * @sa Attribute + */ + export interface StringAttribute extends Attribute + { + /** + * Gets maximum length allowed. + * + * @return The maximum length allowed. + * + * @remarks The email form's "Description" attribute does not have the this method. + */ + getMaxLength(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): string; + + /** + * Sets the value. + * + * @param {string} value The value. + * + * @remarks A String field with the {@link Attribute.getFormat|email} format enforces email + * address formatting. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: string ): void; + } + + /** + * Common interface for enumeration attributes (OptionSet and Boolean). + * + * @sa Attribute + */ + export interface EnumAttribute extends Attribute + { + /** + * Gets the initial value of the attribute. + * + * @return The initial value. + * @remarks Valid for optionset and boolean attribute types + */ + getInitialValue(): number | boolean; + } + + /** + * Interface for a Boolean attribute. + * + * @sa EnumAttribute + */ + export interface BooleanAttribute extends EnumAttribute + { + /** + * Gets the value. + * + * @return true if it succeeds, false if it fails. + */ + getValue(): boolean; + + /** + * Sets the value. + * + * @param {boolean} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: boolean ): void; + } + + /** + * Interface for a Date attribute. + * + * @sa Attribute + */ + export interface DateAttribute extends Attribute + { + /** + * Gets the value. + * + * @return The value. + */ + getValue(): Date; + + /** + * Sets the value. + * + * @param {Date} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: Date ): void; + } + + /** + * Interface an OptionSet attribute. + * + * @sa EnumAttribute + */ + export interface OptionSetAttribute extends EnumAttribute + { + /** + * Gets the option matching a value. + * + * @param {number} value The enumeration value of the option desired. + * + * @return The option. + */ + getOption( value: number ): OptionSetValue; + + /** + * Gets the option matching a label. + * + * @param {string} label The label of the option desired. + * + * @return The option. + */ + getOption( label: string ): OptionSetValue; + + /** + * Gets all of the options. + * + * @return An array of options. + */ + getOptions(): OptionSetValue[]; + + /** + * Gets selected option. + * + * @return The selected option. + */ + getSelectedOption(): OptionSetValue; + + /** + * Gets the label of the currently selected option. + * + * @return The current value's label. + */ + getText(): string; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks The getOptions() method returns option values as strings. You must use parseInt + * to convert them to numbers before you can use those values to set the value of an + * OptionSet attribute. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface a Lookup attribute. + * + * @sa Attribute + */ + export interface LookupAttribute extends Attribute + { + /** + * Gets a boolean value indicating whether the Lookup is a multi-value PartyList. + * + * @return true the attribute is a PartyList, otherwise false. + */ + getIsPartyList(): boolean; + + /** + * Gets the value. + * + * @return An array of LookupValue. + */ + getValue(): LookupValue[]; + + /** + * Sets the value. + * + * @param {LookupValue[]} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: LookupValue[] ): void; + } + + /** + * Interface for the form's record context, Xrm.Page.data.entity + */ + export interface Entity + { + /** + * The collection of attributes for the record. + */ + attributes: Collection.ItemCollection; + + /** + * Adds a handler to be called when the record is saved. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + addOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Gets an serialized-XML string representing data that will be passed to the server upon saving + * the record. + * + * @return The XML in string format. + * + * @remarks This function does not work with Microsoft Dynamics CRM for tablets. Example: + * "Contoso55555425 + * 555-1234". + */ + getDataXml(): string; + + /** + * Gets entity's logical name. + * + * @return The logical name. + */ + getEntityName(): string; + + /** + * Gets the record's unique identifier. + * + * @return The identifier, in Guid format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Gets a boolean value indicating whether the record has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the record's primary attribute value. + * + * @return The primary attribute value. + * + * @remarks The value for this attribute is used when links to the record are displayed. + */ + getPrimaryAttributeValue(): string; + + /** + * Removes the handler from the "on save" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Saves the record. + * + * @remarks When using quick create forms in the web application the saveandnew option is not + * applied. It will always work as if saveandclose were used. Quick create forms in + * Microsoft Dynamics CRM for tablets will apply the saveandnew behavior. + */ + save(): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandclose"} saveMode Saves the record, and closes the form. + */ + save( saveMode: "saveandclose" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandnew"} saveMode Saves the record, and opens a blank form. + */ + save( saveMode: "saveandnew" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {string} saveMode (Optional) the save mode to save, as either "saveandclose" or + * "saveandnew". + */ + save( saveMode: string ): void; + } + + /** + * Interface for save event arguments. + */ + export interface SaveEventArguments + { + /** + * Gets save mode, as an integer. + * + * @return The save mode. + * @remarks Values returned are: 1 Save + * 2 Save and Close + * 59 Save and New + * 70 AutoSave (Where enabled; can be used with an OnSave handler + * to conditionally disable auto-saving) + * 58 Save as Completed (Activities) + * 5 Deactivate + * 6 Reactivate + * 47 Assign (All user- or team-owned entities) + * 7 Send (Email) + * 16 Qualify (Lead) + * 15 Disqualify (Lead) + */ + getSaveMode(): SaveMode; + + /** + * Returns a boolean value to indicate if the record's save has been prevented. + * + * @return true if saving is prevented, otherwise false. + */ + isDefaultPrevented(): boolean; + + /** + * Prevents the save operation from being submitted to the server. + * @remarks All remaining "on save" handlers will continue execution. + */ + preventDefault(): void; + } + + /** + * Interface for the Xrm.Page.data API. + */ + export interface Data + { + /** + * The record context of the form. + */ + entity: Entity; + + /** + * Asynchronously refreshes data on the form, without reloading the page. + * + * @param {boolean} save true to save the record, after the refresh + * + * @return An Async.XrmPromise. + */ + refresh( save: boolean ): Async.XrmPromise; + + /** + * Asynchronously saves the record. + * + * @return An Async.XrmPromise. + */ + save(): Async.XrmPromise; + } + + /** + * Interface for Xrm.Page.ui controls. + * + * @sa UiElement + */ + export interface Control extends UiElement + { + /** + * Clears the notification identified by uniqueId. + * + * @param {string} uniqueId (Optional) Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks If the uniqueId parameter is not used, the current notification shown will be removed. + */ + clearNotification( uniqueId?: string ): boolean; + + /** + * Gets the control's type. + * + * @return The control type. + * @remarks Values returned are: standard + * iframe + * lookup + * optionset + * subgrid + * webresource + * notes + * timercontrol + */ + getControlType(): string; + + /** + * Gets a boolean value, indicating whether the control is disabled. + * + * @return true if it is disabled, otherwise false. + */ + getDisabled(): boolean; + + /** + * Gets the name of the control on the form. + * + * @return The name of the control. + * + * @remarks The name assigned to a control is not determined until the form loads. Changes to + * the form may change the name assigned to a given control. + * When you use the control getName method the name of the first control will be the + * same as the name of the attribute. The second instance of a control for that + * attribute will be "1". The pattern +N + * will continue for each additional control added to the form for a specific + * attribute. When a form displays a business process flow control in the header, + * additional controls will be added for each attribute that is displayed in the + * business process flow. These controls have a unique name like the following: + * header_process_. + */ + getName(): string; + + /** + * Gets a reference to the Section parent of the control. + * + * @return The parent Section. + */ + getParent(): Section; + + /** + * Sets the state of the control to either enabled, or disabled. + * + * @param {boolean} disabled true to disable, false to enable. + */ + setDisabled( disabled: boolean ): void; + + /** + * Sets a control-local notification message. + * + * @param {string} message The message. + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks When this method is used on Microsoft Dynamics CRM for tablets a red "X" icon + * appears next to the control. Tapping on the icon will display the message. + */ + setNotification( message: string, uniqueId: string ): boolean; + } + + /** + * Interface for a standard control. + * + * @sa Control + */ + export interface StandardControl extends Control + { + /** + * Gets the control's bound attribute. + * + * @tparam T An Attribute type. + * + * @return The attribute. + */ + getAttribute(): T; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): Attribute; + } + + /** + * Interface for a Date control. + * + * @sa StandardControl + */ + export interface DateControl extends StandardControl + { + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): DateAttribute; + + /** + * Sets the visibility of the time component of the Date control. + * + * @param {boolean} showTimeValue true to show, false to hide the time value. + */ + setShowTime( showTimeValue: boolean ): void; + } + + /** + * Interface for a Lookup control. + * + * @sa StandardControl + */ + export interface LookupControl extends StandardControl + { + /** + * Adds a handler to the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + addPreSearch( handler: () => void ): void; + + /** + * Adds an additional custom filter to the lookup, with the "AND" filter operator. + * Can only be used within a "pre search" event handler + * + * @sa addPreSearch + * + * @param {string} filter Specifies the filter, as a serialized FetchXML + * "filter" node. + * @param {string} entityLogicalName (Optional) The logical name of the entity. + * + * @remarks If entityLogicalName is not specified, the filter will be applied to all entities + * valid for the Lookup control. + * Example filter: + * + * + */ + addCustomFilter( filter: string, entityLogicalName?: string ): void; + + /** + * Adds a custom view for the Lookup dialog. + * + * @param {string} viewId Unique identifier for the view, in Guid format. + * @param {string} entityName Name of the entity. + * @param {string} viewDisplayName Name of the view to display. + * @param {string} fetchXml The FetchXML query for the view's contents, serialized as a string. + * @param {string} layoutXml The Layout XML, serialized as a string. + * @param {boolean} isDefault true, to treat this view as default. + * + * @remarks Cannot be used on "Owner" Lookup controls. + * The viewId is never saved to CRM, but must be unique across available views. Generating + * a new value can be accomplished with a {@link http://www.guidgen.com/|Guid generator}. + * Example viewId value: "{00000000-0000-0000-0000-000000000001}" + * Layout XML Reference: {@link http://msdn.microsoft.com/en-us/library/gg334522.aspx} + */ + addCustomView( viewId: string, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean ): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): LookupAttribute; + + /** + * Gets the unique identifier of the default view. + * + * @return The default view, in Guid format. + * + * @remarks Example: "{00000000-0000-0000-0000-000000000000}" + */ + getDefaultView(): string; + + /** + * Removes the handler from the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + removePreSearch( handler: () => void ): void; + + /** + * Sets the Lookup's default view. + * + * @param {string} viewGuid Unique identifier for the view. + * + * @remarks Example viewGuid value: "{00000000-0000-0000-0000-000000000000}" + */ + setDefaultView( viewGuid: string ): void; + } + + /** + * Interface for an OptionSet control. + * + * @sa StandardControl + */ + export interface OptionSetControl extends StandardControl + { + /** + * Adds an option. + * + * @param {OptionSetValue} option The option. + * @param {number} index (Optional) zero-based index of the option. + * + * @remarks This method does not check that the values within the options you add are valid. + * If index is not provided, the new option will be added to the end of the list. + */ + addOption( option: OptionSetValue, index?: number ): void; + + /** + * Clears all options. + */ + clearOptions(): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): OptionSetAttribute; + + /** + * Removes the option matching the value. + * + * @param {number} value The value. + */ + removeOption( value: number ): void; + } + + /** + * Interface for a CRM grid control. + * + * @sa Control + */ + export interface GridControl extends Control + { + /** + * Refreshes the sub grid. + * + * @remarks Not available during the "on load" event of the form. + */ + refresh(): void; + } + + /** + * Interface for a framed control, which is either a Web Resource or an Iframe. + * + * @sa Control + * + * @remarks An Iframe control provides additional methods, so use {@link IframeControl} where + * appropriate. Silverlight controls should use {@link SilverlightControl}. + */ + export interface FramedControl extends Control + { + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLIFrameElement; + + /** + * Gets the URL value of the control. + * + * @return The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getSrc(): string; + + /** + * Sets the URL value of the control. + * + * @param {string} src The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setSrc( src: string ): void; + } + + /** + * Interface for an Iframe control. + * + * @sa FramedControl + */ + export interface IframeControl extends FramedControl + { + /** + * Gets initial URL defined for the Iframe. + * + * @return The initial URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getInitialUrl(): string; + } + + /** + * Interface for a Silverlight control. + * + * @sa Control + */ + export interface SilverlightControl extends Control + { + /** + * Gets the query string value passed to Silverlight. + * + * @return The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getData(): string; + + /** + * Sets the query string value passed to Silverlight. + * + * @param {string} data The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setData( data: string ): void; + + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLObjectElement; + } + + /** + * Interface for a form tab. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface Tab extends UiElement, UiFocusable + { + /** + * A reference to the collection of form sections within this tab. + */ + sections: Collection.ItemCollection
; + + /** + * Gets display state of the tab. + * + * @return The display state, as either "expanded" or "collapsed" + */ + getDisplayState(): string; + + /** + * Gets the name of the tab. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.ui parent of the tab. + * + * @return The parent. + */ + getParent(): Ui; + + /** + * Sets display state of the tab. + * + * @param {"collapsed"} displayState Collapsed tab. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the tab. + * + * @param {"expanded"} displayState Expanded tab. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the tab. + * + * @param {string} displayState Display state of the tab, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + } + + /** + * Interface for a form section. + * + * @sa UiElement + */ + export interface Section extends UiElement + { + /** + * A reference to the collection of controls within this tab. + */ + controls: Collection.ItemCollection; + + /** + * Gets the name of the section. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.Tab parent of this item. + * + * @return The parent. + */ + getParent(): Tab; + } + + /** + * Interface for Xrm.Page.ui API. + */ + export interface Ui + { + /** + * A reference to the collection of controls on the form. + */ + controls: Collection.ItemCollection; + + /** + * The form selector API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + formSelector: FormSelector; + + /** + * The navigation API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + navigation: Navigation; + + /** + * A reference to the collection of tabs on the form. + */ + tabs: Collection.ItemCollection; + + /** + * Clears the form notification described by uniqueId. + * + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, otherwise false. + */ + clearFormNotification( uniqueId: string ): boolean; + + /** + * Closes the form. + */ + close(): void; + + /** + * Gets form type. + * + * @return The form type. + * + * @remarks Values returned are: 0 Undefined + * 1 Create + * 2 Update + * 3 Read Only + * 4 Disabled + * 6 Bulk Edit + * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) + */ + getFormType(): FormType; + + /** + * Gets view port height. + * + * @return The view port height, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortHeight(): number; + + /** + * Gets view port width. + * + * @return The view port width, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortWidth(): number; + + /** + * Re-evaluates the ribbon's configured EnableRules + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + refreshRibbon(): void; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"ERROR"} level An error message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + setFormNotification( message: string, level: "ERROR", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"WARNING"} level A warning message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + setFormNotification( message: string, level: "WARNING", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"INFO"} level An informational message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + setFormNotification( message: string, level: "INFO", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {string} level The level, as either "ERROR", "WARNING", or "INFO". + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, otherwise false. + */ + setFormNotification( message: string, level: string, uniqueId: string ): boolean; + } + + /** + * Interface for a navigation item. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface NavigationItem extends UiElement, UiFocusable + { + /** + * Gets the name of the item. + * + * @return The identifier. + */ + getId(): string; + } + + /** + * Interface for Xrm.Page.ui.navigation. + */ + export interface Navigation + { + /** + * A reference to the collection of available navigation items. + */ + items: Collection.ItemCollection; + } + + /** + * Interface for an entity's form selector item. + */ + export interface FormItem + { + /** + * Gets the unique identifier of the form. + * + * @return The identifier, in Guid format. + */ + getId(): string; + + /** + * Gets the label for the form. + * + * @return The label. + */ + getLabel(): string; + + /** + * Navigates the user to this form. + */ + navigate(): void; + } + + /** + * Interface for the form selector API. + */ + export interface FormSelector + { + /** + * Gets current form. + * + * @return The current item. + * + * @remarks When only one form is available this method will return null. + */ + getCurrentItem(): FormItem; + + /** + * A reference to the collection of available forms. + */ + items: Collection.ItemCollection; + } + + /** + * A reference to the xRM application context. + */ + export var context: Context; + + /** + * A reference to the form's user interface API. + */ + export var ui: Ui; + + /** + * A reference to the form's data API. + */ + export var data: Data; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + export function getAttribute(): Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + export function getAttribute( index: number ): Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + export function getAttribute( delegateFunction: Collection.MatchingDelegate ): Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + export function getControl(): Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + export function getControl( index: number ): Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + export function getControl( delegateFunction: Collection.MatchingDelegate ): Control[]; + } + + /** + * An definition module for URL-based, CRM component parameters. + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export module Url + { + /** + * An enumeration for view types. + */ + export const enum ViewType + { + SystemView = 1039, + UserView = 4230 + } + + /** + * Interface for defining parameters on a request to open a form with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entityrecord" is required in + * the URL, for forms. Example: "pagetype=entityrecord" + */ + export interface FormOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * Additional parameters can be provided to the request. This can only be used to provide + * default field values for the form, or pass data to custom parameters that have been + * customized for the form. See example below for setting the selected form. + * + * @remarks Example: encodeURIComponent( "formid={8c9f3e6f-7839-e211-831e-00155db7d98f}" ); + */ + extraqs?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters on a request to open a view with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entitylist" is required in + * the URL, for views. Example: "pagetype=entitylist" + */ + export interface ViewOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * The unique identifier of a view, in Guid format, which is valid for the entity described by + * {@link etn}. + */ + viewid: string; + + /** + * The type of view identified by {@link viewid}. + * + * @remarks Accepted values are: 1039 System View + * 4230 User View. + */ + viewtype: ViewType; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters of a request to open a dialog with rundialog.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface DialogOpenParameters + { + /** + * The unique identifier of the dialog, in Guid format, which is valid for the entity described + * by: {@link EntityName} + */ + DialogId: string; + + /** + * The logical name of the entity. + */ + EntityName: string; + + /** + * The unique identifier for the targeted record. + */ + ObjectId: string; + } + + /** + * Interface for defining parameters of a request to open a report with viewer.apsx (as with + * window.open). Useful for parsing out the keys and values into a string of the format: + * "&key=value" + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface ReportOpenParameters + { + /** + * The action to perform, as either "run" or "filter". + * + * @remarks "run" Executes the report with default filters. + * "filter" Presents the user with the filter editor, and a "Run Report" button. + */ + action: string; + + /** + * The file name of the report. For out-of-box reports, this parameter enables context-sensitive + * help. + */ + helpID?: string; + + /** + * The unique identifier, held in the report's 'reportid' attribute, in Guid format. + */ + id: string; + } + } + + /** + * The Xrm.Utility API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Utility + { + /** + * Interface for defining parameters on a Xrm.Utility.openEntityForm() request. + */ + export interface FormOpenParameters + { + /** + * The identifier of the form to use, when several are available. + */ + formid: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Additional parameters can be provided to the request, by overloading + * this object with additional key and value pairs. This can only be used + * to provide default field values for the form, or pass data to custom + * parameters that have been customized for the form. + */ + [index: string]: string; + } + + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + export function alertDialog( message: string, onCloseCallback: () => void ): void; + + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + export function confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; + + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + export function isActivityType( entityType: string ): boolean; + + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) Options for controlling the operation. + */ + export function openEntityForm( name: string, id?: string, parameters?: FormOpenParameters ): void; + + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + export function openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } +} diff --git a/xrm/xrm-6.tests.ts b/xrm/xrm-6.tests.ts new file mode 100644 index 000000000..a791d861e --- /dev/null +++ b/xrm/xrm-6.tests.ts @@ -0,0 +1,69 @@ +/// +/// + +function _getContext() +{ + var errorMessage = "Context is not available."; + if ( typeof GetGlobalContext != "undefined" ) + { return GetGlobalContext(); } + else + { + if ( typeof Xrm != "undefined" ) + { + return Xrm.Page.context; + } + else { throw new Error( errorMessage ); } + } +} + +var crmContext = _getContext(); + +var grids = Xrm.Page.getControl(( control ) => +{ + return control.getControlType() === "subgrid"; +}); + +var selectedGridReferences: Xrm.Page.LookupValue[] = []; + +grids.forEach(( gridControl: Xrm.Page.GridControl ) => +{ + gridControl.refresh(); +}); + +var lookupAttribute = Xrm.Page.getControl( "customerid" ); + +lookupAttribute.addCustomFilter( ` + +`, "account" ); + +lookupAttribute.addPreSearch(() => { alert( "A search was performed." ); }); + +var lookupValues = lookupAttribute.getAttribute().getValue(); + +if ( lookupValues !== null ) + if ( !lookupValues[0].id || !lookupValues[0].entityType ) + throw new Error("Invalid value in Lookup control."); + +Xrm.Page.ui.controls.forEach(( control ) => { control.setVisible( true ); }); + +Xrm.Page.ui.tabs.forEach(( tab ) => +{ + tab.setVisible( true ); + + tab.sections.forEach(( section ) => + { + section.setVisible( true ); + }); +}); + +Xrm.Page.data.entity.addOnSave(( context ) => +{ + var eventArgs = context.getEventArgs(); + + if ( eventArgs.getSaveMode() === Xrm.Page.SaveMode.AutoSave || eventArgs.getSaveMode() === Xrm.Page.SaveMode.SaveAndClose ) + eventArgs.preventDefault(); +}); + +alert( `The current form type is: ${Xrm.Page.ui.getFormType() }` ); + +alert( `The current entity type is: ${Xrm.Page.data.entity.getEntityName() }` ); diff --git a/xrm/xrm-7.0.d.ts b/xrm/xrm-7.0.d.ts new file mode 100644 index 000000000..42814382d --- /dev/null +++ b/xrm/xrm-7.0.d.ts @@ -0,0 +1,2350 @@ +// Type definitions for Microsoft Dynamics xRM API v7.0 +// Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 +// Definitions by: David Berry , Matt Ngan +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Xrm +{ + /** + * Interface for the client context. + */ + export interface ClientContext + { + /** + * Returns a value to indicate which client the script is executing in. + * + * @return The client, as either "Web", "Outlook", or "Mobile" + */ + getClient(): string; + + /** + * Gets client's current state. + * + * @return The client state, as either "Online" or "Offline" + */ + getClientState(): string; + } + + /** + * Interface for the xRM application context. + */ + export interface Context + { + /** + * The client's context instance. + */ + client: ClientContext; + + /** + * Gets client's base URL for Dynamics CRM + * + * @return The client's base URL + * @remarks For Dynamics CRM On-Premises: http(s)://server/org + * For Dynamics CRM Online: https://org.crm.dynamics.com + * For Dynamics CRM for Outlook (Offline): http://localhost:2525 + */ + getClientUrl(): string; + + /** + * Gets current styling theme. + * + * @return The name of the current theme, as either "default", "Office12Blue", or "Office14Silver" + * + * @remarks This function does not work with Dynamics CRM for tablets. + */ + getCurrentTheme(): string; + + /** + * Gets whether automatic save is enabled. + * + * @return true if automatic saving is enabled, otherwise false. + */ + getIsAutoSaveEnabled(): boolean; + + /** + * Gets organization's LCID (language code). + * + * @return The organization language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getOrgLcid(): number; + + /** + * Gets organization's unique name. + * + * @return The organization's unique name. + * + * @remarks This value can be found on the Developer Resources page within Dynamics CRM + */ + getOrgUniqueName(): string; + + /** + * Gets query string parameters. + * + * @return The query string parameters, in a dictionary object representing name and value pairs. + */ + getQueryStringParameters(): { [index: string]: any }; + + /** + * Gets user's unique identifier. + * + * @return The user's identifier in Guid format. + * + * @remarks Example: "{B05EC7CE-5D51-DF11-97E0-00155DB232D0}" + */ + getUserId(): string; + + /** + * Gets user's LCID (language code). + * + * @return The user's language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getUserLcid(): number; + + /** + * Gets the name of the current user. + * + * @return The user's name. + */ + getUserName(): string; + + /** + * Gets all user security roles. + * + * @return An array of user role identifiers, in Guid format. + * + * @remarks Example: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"] + */ + getUserRoles(): string[]; + + /** + * Prefixes the current organization's unique name to a string; typically a URL path. + * + * @param {string} sPath Local pathname of the resource. + * + * @return A path string with the organization name. + * + * @remarks Format: "/"+ OrgName + sPath + */ + prependOrgName( sPath: string ): string; + } + + /** + * A definition module for asynchronous interface declarations. + */ + export module Async + { + /** + * Called when the operation is successful. + */ + export type SuccessCallbackDelegate = () => void; + + /** + * Called when the operation fails. + * + * @param {number} errorCode The error code. + * @param {string} message The message. + */ + export type ErrorCallbackDelegate = ( errorCode: number, message: string ) => void; + + /** + * Interface for Xrm.Page.data promises. + */ + export interface XrmPromise + { + /** + * A basic 'then' promise. + * + * @param {SuccessCallbackDelegate} successCallback The success callback. + * @param {ErrorCallbackDelegate} errorCallback The error callback. + */ + then( successCallback: SuccessCallbackDelegate, errorCallback: ErrorCallbackDelegate ): void; + } + } + + /** + * A definition module for collection interface declarations. + */ + export module Collection + { + /** + * Interface for a matching delegate. + * + * @tparam T Generic type parameter. + */ + export interface MatchingDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + * + * @return true if the item matches, false if it does not. + */ + ( item: T, index?: number ): boolean; + } + + /** + * Interface for iterative delegate. + * + * @tparam T Generic type parameter. + */ + export interface IterativeDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + */ + ( item: T, index?: number ): void; + } + + /** + * Interface for an item collection. + * + * @tparam T Generic type parameter. + */ + export interface ItemCollection + { + /** + * Applies an operation to all items in this collection. + * + * @param {IterativeDelegate{T}} delegate An iterative delegate function + */ + forEach( delegate: IterativeDelegate ): void; + + /** + * Gets. + * + * @param {MatchingDelegate{T}} delegate A matching delegate function + * + * @return A T[] whose members have been validated by delegate. + */ + get( delegate: MatchingDelegate ): T[]; + + /** + * Gets the item given by the index. + * + * @param {number} itemNumber The item number to get. + * + * @return The T in the itemNumber-th place. + */ + get( itemNumber: number ): T; + + /** + * Gets the item given by the key. + * + * @param {string} itemName The item name to get. + * + * @return The T matching the key itemName. + * + * @see {@link Xrm.Page.Control.getName()} for Control-naming schemes. + */ + get( itemName: string ): T; + + /** + * Gets the entire array of T. + * + * @return A T[]. + */ + get(): T[]; + + /** + * Gets the length of the collection. + * + * @return The length. + */ + getLength(): number; + } + } + + /** + * The Xrm.Page API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Page + { + /** + * Enumeration of entity form states/types. + */ + export const enum FormType + { + Undefined = 0, + Create = 1, + Update = 2, + ReadOnly = 3, + Disabled = 4, + BulkEdit = 6 + } + + /** + * Enumeration of entity form save modes. + */ + export const enum SaveMode + { + Save = 1, + SaveAndClose = 2, + SaveAndNew = 59, + AutoSave = 70, + SaveAsCompleted = 58, + Deactivate = 5, + Reactivate = 6, + Assign = 47, + Send = 7, + Qualify = 16, + Disqualify = 15 + } + + /** + * Enumeration of stage categories. + */ + export const enum StageCategory + { + Qualify = 0, + Develop = 1, + Propose = 2, + Close = 3, + Identify = 4, + Research = 5, + Resolve = 6 + } + + export interface Process + { + /** + * Returns the unique identifier of the process. + * + * @return The identifier for this process, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the process. + * + * @return The name. + */ + getName(): string; + + /** + * Returns an collection of stages in the process. + * + * @return The stages. + */ + getStages(): Collection.ItemCollection; + + /** + * Returns a boolean value to indicate if the process is rendered. + * + * @return true if the process is rendered, false if not. + */ + isRendered(): boolean; + } + + /** + * Interface for CRM Business Process Flow stages. + */ + export interface Stage + { + /** + * Returns an object with a getValue method which will return the integer value of the business process flow + * category. + * + * @return The stage category. + */ + getCategory(): { getValue(): StageCategory }; + + /** + * Returns the logical name of the entity associated with the stage. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns the unique identifier of the stage. + * + * @return The identifier of the Stage, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the stage. + * + * @return The name. + */ + getName(): string; + + /** + * Returns the status of the stage. + * + * @return The status. + * + * @remarks This method will return either "active" or "inactive". + */ + getStatus(): string; + + /** + * Returns a collection of steps in the stage. + * + * @return An array of Step. + */ + getSteps(): Step[]; + } + + export interface Step + { + /** + * Returns the logical name of the attribute associated to the step. + * + * @return The attribute. + * + * @remarks Some steps don’t contain an attribute value. + */ + getAttribute(): string; + + /** + * Returns the name of the step. + * + * @return The name. + */ + getName(): string; + + /** + * Returns whether the step is required in the business process flow. + * + * @return true if required, false if not. + * + * @remarks Returns true if the step is marked as required in the Business Process Flow editor; otherwise, false. + * There is no connection between this value and the values you can change in the Xrm.Page.data.entity + * attribute RequiredLevel methods. + */ + isRequired(): boolean; + } + + /** + * Interface for the event context. + */ + export interface EventContext + { + /** + * Gets the Xrm context. + * + * @return The Xrm context. + */ + getContext(): Context; + + /** + * Gets the handler's depth, which is the order in which the handler is executed. + * + * @return The depth, a 0-based index. + */ + getDepth(): number; + + /** + * Gets save-event arguments. + * + * @return The event arguments. + * + * @remarks Returns null for all but the "save" event. + */ + getEventArgs(): SaveEventArguments; + + /** + * Gets a reference to the object for which event occurred. + * + * @return The event source. + */ + getEventSource(): Xrm.Page.Attribute | Xrm.Page.Entity; + + /** + * Gets the shared variable with the specified key. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * + * @return The shared variable. + * + * @remarks Used to pass values between handlers of an event. + */ + getSharedVariable( key: string ): T; + + /** + * Sets a shared variable. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * @param {T} value The value. + * + * @remarks Used to pass values between handlers of an event. + */ + setSharedVariable( key: string, value: T ): void; + } + + /** + * Interface for a context-sensitive handler. + */ + export interface ContextSensitiveHandler + { + /** + * @param {EventContext} context The context. + */ + ( context?: EventContext ): void; + } + + /** + * Base interface for UI elements. + */ + export interface UiElement + { + /** + * Gets the label. + * + * @return The label. + */ + getLabel(): string; + + /** + * Gets the visibility state. + * + * @return true if the tab is visible, otherwise false. + */ + getVisible(): boolean; + + /** + * Sets the label. + * + * @param {string} label The label. + */ + setLabel( label: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for focusable UI elements. + */ + export interface UiFocusable + { + /** + * Sets focus on the element. + */ + setFocus(): void; + } + + /** + * Interface for a Lookup value. + */ + export interface LookupValue + { + /** + * The identifier. + */ + id: string; + + /** + * The name + */ + name?: string; + + /** + * Type of the entity. + */ + entityType: string; + } + + /** + * Interface for an OptionSet value. + */ + export interface OptionSetValue + { + /** + * The label text. + */ + text: string; + + /** + * The value, as a string. + * + * @remarks You must use parseInt to convert this value to a number before you can use it to + * set the value of an OptionSetAttribute. + */ + value: string; + } + + /** + * Interface for a privilege. + */ + export interface Privilege + { + /** + * true if the user can read. + */ + canRead: boolean; + + /** + * true if the user can update. + */ + canUpdate: boolean; + + /** + * true if the user can create. + */ + canCreate: boolean; + } + + /** + * Interface for an Entity attribute. + */ + export interface Attribute + { + /** + * Adds a handler to be called when the attribute's value is changed. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Fire all "on change" event handlers. + */ + fireOnChange(): void; + + /** + * Gets attribute type. + * + * @return The attribute's type name. + * + * @remarks Values returned are: boolean + * datetime + * decimal + * double + * integer + * lookup + * memo + * money + * optionset + * string + */ + getAttributeType(): string; + + /** + * Gets the attribute format. + * + * @return The format of the attribute. + * + * @see {@link getAttributeType()} + * + * @remarks Values returned are: date (datetime) + * datetime (datetime) + * duration (integer) + * email (string) + * language (optionset) + * none (integer) + * phone (string) + * text (string) + * textarea (string) + * tickersymbol (string) + * timezone (optionset) + * url (string) + */ + getFormat(): string; + + /** + * Gets a boolean value indicating whether this Attribute has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the logical name of the attribute. + * + * @return The logical name. + */ + getName(): string; + + /** + * Gets a reference to the record context of this attribute. + * + * @return The parent record context. + */ + getParent(): Entity; + + /** + * Gets the current level of requirement for the attribute. + * + * @return The required level, as either "none", "required", or "recommended" + */ + getRequiredLevel(): string; + + /** + * Gets current submit mode for the attribute. + * + * @return The submit mode, as either "always", "never", or "dirty" + * + * @remarks The default value is "dirty" + */ + getSubmitMode(): string; + + /** + * Gets the current user's privileges for the attribute. + * + * @return The user privileges. + */ + getUserPrivilege(): Privilege; + + /** + * Removes the handler from the "on change" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Sets required level. + * + * @param {"none"} requirementLevel Not required. + */ + setRequiredLevel( requirementLevel: "none" ): void; + + /** + * Sets required level. + * + * @param {"required"} requirementLevel Required. + */ + setRequiredLevel( requirementLevel: "required" ): void; + + /** + * Sets required level. + * + * @param {"recommended"} requirementLevel Recommended. + */ + setRequiredLevel( requirementLevel: "recommended" ): void; + + /** + * Sets the required level. + * + * @param {string} requirementLevel The requirement level, as either "none", "required", or "recommended" + */ + setRequiredLevel( requirementLevel: string ): void; + + /** + * Sets submit mode. + * + * @param {"always"} submitMode Always submit this attribute. + */ + setSubmitMode( submitMode: "always" ): void; + + /** + * Sets submit mode. + * + * @param {"never"} submitMode Never submit this attribute. + */ + setSubmitMode( submitMode: "never" ): void; + + /** + * Sets submit mode. + * + * @param {"dirty"} submitMode Submit this attribute when changed. + */ + setSubmitMode( submitMode: "dirty" ): void; + + /** + * Sets the submit mode. + * + * @param {string} submitMode The submit mode, as either "always", "never", or "dirty". + * + * @remarks The default value is "dirty" + */ + setSubmitMode( submitMode: string ): void; + + /** + * A collection of all the controls on the form that interface with this attribute. + */ + controls: Collection.ItemCollection; + } + + /** + * Interface for a Number attribute. + * + * @sa Attribute + */ + export interface NumberAttribute extends Attribute + { + /** + * Gets the maximum value allowed. + * + * @return The maximum value allowed. + */ + getMax(): number; + + /** + * Gets the minimum value allowed. + * + * @return The minimum value allowed. + */ + getMin(): number; + + /** + * Gets the attribute's configured precision. + * + * @return The total number of allowed decimal places. + */ + getPrecision(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface for a String attribute. + * + * @sa Attribute + */ + export interface StringAttribute extends Attribute + { + /** + * Gets maximum length allowed. + * + * @return The maximum length allowed. + * + * @remarks The email form's "Description" attribute does not have the this method. + */ + getMaxLength(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): string; + + /** + * Sets the value. + * + * @param {string} value The value. + * + * @remarks A String field with the {@link Attribute.getFormat|email} format enforces email + * address formatting. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: string ): void; + } + + /** + * Common interface for enumeration attributes (OptionSet and Boolean). + * + * @sa Attribute + */ + export interface EnumAttribute extends Attribute + { + /** + * Gets the initial value of the attribute. + * + * @return The initial value. + * @remarks Valid for optionset and boolean attribute types + */ + getInitialValue(): number | boolean; + } + + /** + * Interface for a Boolean attribute. + * + * @sa EnumAttribute + */ + export interface BooleanAttribute extends EnumAttribute + { + /** + * Gets the value. + * + * @return true if it succeeds, false if it fails. + */ + getValue(): boolean; + + /** + * Sets the value. + * + * @param {boolean} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: boolean ): void; + } + + /** + * Interface for a Date attribute. + * + * @sa Attribute + */ + export interface DateAttribute extends Attribute + { + /** + * Gets the value. + * + * @return The value. + */ + getValue(): Date; + + /** + * Sets the value. + * + * @param {Date} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: Date ): void; + } + + /** + * Interface an OptionSet attribute. + * + * @sa EnumAttribute + */ + export interface OptionSetAttribute extends EnumAttribute + { + /** + * Gets the option matching a value. + * + * @param {number} value The enumeration value of the option desired. + * + * @return The option. + */ + getOption( value: number ): OptionSetValue; + + /** + * Gets the option matching a label. + * + * @param {string} label The label of the option desired. + * + * @return The option. + */ + getOption( label: string ): OptionSetValue; + + /** + * Gets all of the options. + * + * @return An array of options. + */ + getOptions(): OptionSetValue[]; + + /** + * Gets selected option. + * + * @return The selected option. + */ + getSelectedOption(): OptionSetValue; + + /** + * Gets the label of the currently selected option. + * + * @return The current value's label. + */ + getText(): string; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks The getOptions() method returns option values as strings. You must use parseInt + * to convert them to numbers before you can use those values to set the value of an + * OptionSet attribute. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface a Lookup attribute. + * + * @sa Attribute + */ + export interface LookupAttribute extends Attribute + { + /** + * Gets a boolean value indicating whether the Lookup is a multi-value PartyList. + * + * @return true the attribute is a PartyList, otherwise false. + */ + getIsPartyList(): boolean; + + /** + * Gets the value. + * + * @return An array of LookupValue. + */ + getValue(): LookupValue[]; + + /** + * Sets the value. + * + * @param {LookupValue[]} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: LookupValue[] ): void; + } + + /** + * Interface for the form's record context, Xrm.Page.data.entity + */ + export interface Entity + { + /** + * Adds a handler to be called when the record is saved. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + addOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Gets an serialized-XML string representing data that will be passed to the server upon saving + * the record. + * + * @return The XML in string format. + * + * @remarks This function does not work with Microsoft Dynamics CRM for tablets. Example: + * "Contoso55555425 + * 555-1234". + */ + getDataXml(): string; + + /** + * Gets entity's logical name. + * + * @return The logical name. + */ + getEntityName(): string; + + /** + * Gets the record's unique identifier. + * + * @return The identifier, in Guid format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Gets a boolean value indicating whether the record has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the record's primary attribute value. + * + * @return The primary attribute value. + * + * @remarks The value for this attribute is used when links to the record are displayed. + */ + getPrimaryAttributeValue(): string; + + /** + * Removes the handler from the "on save" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Saves the record. + * + * @remarks When using quick create forms in the web application the saveandnew option is not + * applied. It will always work as if saveandclose were used. Quick create forms in + * Microsoft Dynamics CRM for tablets will apply the saveandnew behavior. + */ + save(): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandclose"} saveMode Saves the record, and closes the form. + */ + save( saveMode: "saveandclose" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandnew"} saveMode Saves the record, and opens a blank form. + */ + save( saveMode: "saveandnew" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {string} saveMode (Optional) the save mode to save, as either "saveandclose" or + * "saveandnew". + */ + save( saveMode: string ): void; + + /** + * The collection of attributes for the record. + */ + attributes: Collection.ItemCollection; + } + + /** + * Interface for save event arguments. + */ + export interface SaveEventArguments + { + /** + * Gets save mode, as an integer. + * + * @return The save mode. + * @remarks Values returned are: 1 Save + * 2 Save and Close + * 59 Save and New + * 70 AutoSave (Where enabled; can be used with an OnSave handler + * to conditionally disable auto-saving) + * 58 Save as Completed (Activities) + * 5 Deactivate + * 6 Reactivate + * 47 Assign (All user- or team-owned entities) + * 7 Send (Email) + * 16 Qualify (Lead) + * 15 Disqualify (Lead) + */ + getSaveMode(): SaveMode; + + /** + * Returns a boolean value to indicate if the record's save has been prevented. + * + * @return true if saving is prevented, otherwise false. + */ + isDefaultPrevented(): boolean; + + /** + * Prevents the save operation from being submitted to the server. + * @remarks All remaining "on save" handlers will continue execution. + */ + preventDefault(): void; + } + + /** + * Module for the Xrm.Page.data API. + */ + export module data + { + /** + * Interface for the Xrm.Page.data.process API. + */ + export interface ProcessManager + { + /** + * Returns a Process object representing the active process. + * + * @return current active process. + */ + getActiveProcess(): Process; + + /** + * Set a Process as the active process. + * + * @param {string} processId the Id of the process to make the active process. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveProcess( processId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Returns a Stage object representing the active stage. + * + * @return current active stage. + */ + getActiveStage(): Stage; + + /** + * Set a stage as the active stage. + * + * @param {string} stageId the Id of the stage to make the active stage. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveStage( stageId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Use this method to get a collection of stages currently in the active path with methods to interact with the + * stages displayed in the business process flow control. The active path represents stages currently rendered in + * the process control based on the branching rules and current data in the record. + * + * @return A collection of all completed stages, the currently active stage, and the predicted set of future stages + * based on satisfied conditions in the branching rule. This may be a subset of the stages returned with + * Xrm.Page.data.process.getActiveProcess because it will only include those stages which represent a valid + * transition from the current stage based on branching that has occurred in the process. + */ + getActivePath(): Collection.ItemCollection; + + /** + * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an + * entity. + * + * @param {Function} callbackFunction The callback function must accept a parameter + * that contains an object with dictionary + * properties where the name of the property is the + * Id of the business process flow and the value of + * the property is the name of the business process + * flow. + * + * The enabled processes are filtered according to + * the user’s privileges. The list of enabled + * processes is the same ones a user can see in the + * UI if they want to change the process manually. + */ + getEnabledProcesses( callbackFunction: ( enabledProcesses: ProcessDictionary ) => void ): void; + + /** + * Use this to add a function as an event handler for the OnStageChange event so that it will be called when the + * business process flow stage changes. + * + * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event handler + * pipeline. The execution context is automatically set to be the first + * parameter passed to the event handler. + */ + addOnStageChange( handler: ContextSensitiveHandler ): void; + + /** + * Use this to remove a function as an event handler for the OnStageChange event. + * + * @param {ContextSensitiveHandler} handler If an anonymous function is set using the addOnStageChange method it + * cannot be removed using this method. + */ + removeOnStageSelected( handler: ContextSensitiveHandler ): void; + + /** + * Progresses to the next stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + moveNext( callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Moves to the previous stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + movePrevious( callbackFunction?: ProcessCallbackDelegate ): void; + } + + /** + * Called when process change methods have completed. + * + * @param {string} status The result of the process change operation. + * @remarks Values returned are: success (The operation succeeded.) + * crossEntity (The previous stage is for a different entity.) + * beginning (The active stage is the first stage of the active path.) + * invalid (The operation failed because the selected stage isn’t the same + * as the active stage.) + * unreachable (The stage exists on a different path.) + */ + export type ProcessCallbackDelegate = ( status: string ) => void; + + /** + * Represents a key-value pair, where the key is the Process Flow's ID, and the value is the name thereof. + */ + export type ProcessDictionary = { [index: string]: string }; + + /** + * Asynchronously refreshes data on the form, without reloading the page. + * + * @param {boolean} save true to save the record, after the refresh. + * + * @return An Async.XrmPromise. + */ + export function refresh( save: boolean ): Async.XrmPromise; + + /** + * Asynchronously saves the record. + * + * @return An Async.XrmPromise. + */ + export function save(): Async.XrmPromise; + + /** + * The record context of the form. + */ + export var entity: Entity; + + /** + * The process API for Xrm.Page.data. + * + * @remarks This member may be undefined when Process Flows are not used by the current entity. + */ + export var process: ProcessManager; + } + + /** + * Interface for Xrm.Page.ui controls. + * + * @sa UiElement + */ + export interface Control extends UiElement + { + /** + * Clears the notification identified by uniqueId. + * + * @param {string} uniqueId (Optional) Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks If the uniqueId parameter is not used, the current notification shown will be removed. + */ + clearNotification( uniqueId?: string ): boolean; + + /** + * Gets the control's type. + * + * @return The control type. + * @remarks Values returned are: standard + * iframe + * lookup + * optionset + * subgrid + * webresource + * notes + * timercontrol + */ + getControlType(): string; + + /** + * Gets a boolean value, indicating whether the control is disabled. + * + * @return true if it is disabled, otherwise false. + */ + getDisabled(): boolean; + + /** + * Gets the name of the control on the form. + * + * @return The name of the control. + * + * @remarks The name assigned to a control is not determined until the form loads. Changes to + * the form may change the name assigned to a given control. + * When you use the control getName method the name of the first control will be the + * same as the name of the attribute. The second instance of a control for that + * attribute will be "1". The pattern +N + * will continue for each additional control added to the form for a specific + * attribute. When a form displays a business process flow control in the header, + * additional controls will be added for each attribute that is displayed in the + * business process flow. These controls have a unique name like the following: + * header_process_. + */ + getName(): string; + + /** + * Gets a reference to the Section parent of the control. + * + * @return The parent Section. + */ + getParent(): Section; + + /** + * Sets the state of the control to either enabled, or disabled. + * + * @param {boolean} disabled true to disable, false to enable. + */ + setDisabled( disabled: boolean ): void; + + /** + * Sets a control-local notification message. + * + * @param {string} message The message. + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks When this method is used on Microsoft Dynamics CRM for tablets a red "X" icon + * appears next to the control. Tapping on the icon will display the message. + */ + setNotification( message: string, uniqueId: string ): boolean; + } + + /** + * Interface for a standard control. + * + * @sa Control + */ + export interface StandardControl extends Control + { + /** + * Gets the control's bound attribute. + * + * @tparam T An Attribute type. + * + * @return The attribute. + */ + getAttribute(): T; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): Attribute; + } + + /** + * Interface for a Date control. + * + * @sa StandardControl + */ + export interface DateControl extends StandardControl + { + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): DateAttribute; + + /** + * Sets the visibility of the time component of the Date control. + * + * @param {boolean} showTimeValue true to show, false to hide the time value. + */ + setShowTime( showTimeValue: boolean ): void; + } + + /** + * Interface for a Lookup control. + * + * @sa StandardControl + */ + export interface LookupControl extends StandardControl + { + /** + * Adds a handler to the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + addPreSearch( handler: () => void ): void; + + /** + * Adds an additional custom filter to the lookup, with the "AND" filter operator. + * Can only be used within a "pre search" event handler + * + * @sa addPreSearch + * + * @param {string} filter Specifies the filter, as a serialized FetchXML + * "filter" node. + * @param {string} entityLogicalName (Optional) The logical name of the entity. + * + * @remarks If entityLogicalName is not specified, the filter will be applied to all entities + * valid for the Lookup control. + * Example filter: + * + * + */ + addCustomFilter( filter: string, entityLogicalName?: string ): void; + + /** + * Adds a custom view for the Lookup dialog. + * + * @param {string} viewId Unique identifier for the view, in Guid format. + * @param {string} entityName Name of the entity. + * @param {string} viewDisplayName Name of the view to display. + * @param {string} fetchXml The FetchXML query for the view's contents, serialized as a string. + * @param {string} layoutXml The Layout XML, serialized as a string. + * @param {boolean} isDefault true, to treat this view as default. + * + * @remarks Cannot be used on "Owner" Lookup controls. + * The viewId is never saved to CRM, but must be unique across available views. Generating + * a new value can be accomplished with a {@link http://www.guidgen.com/|Guid generator}. + * Example viewId value: "{00000000-0000-0000-0000-000000000001}" + * Layout XML Reference: {@link http://msdn.microsoft.com/en-us/library/gg334522.aspx} + */ + addCustomView( viewId: string, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean ): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): LookupAttribute; + + /** + * Gets the unique identifier of the default view. + * + * @return The default view, in Guid format. + * + * @remarks Example: "{00000000-0000-0000-0000-000000000000}" + */ + getDefaultView(): string; + + /** + * Removes the handler from the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + removePreSearch( handler: () => void ): void; + + /** + * Sets the Lookup's default view. + * + * @param {string} viewGuid Unique identifier for the view. + * + * @remarks Example viewGuid value: "{00000000-0000-0000-0000-000000000000}" + */ + setDefaultView( viewGuid: string ): void; + } + + /** + * Interface for an OptionSet control. + * + * @sa StandardControl + */ + export interface OptionSetControl extends StandardControl + { + /** + * Adds an option. + * + * @param {OptionSetValue} option The option. + * @param {number} index (Optional) zero-based index of the option. + * + * @remarks This method does not check that the values within the options you add are valid. + * If index is not provided, the new option will be added to the end of the list. + */ + addOption( option: OptionSetValue, index?: number ): void; + + /** + * Clears all options. + */ + clearOptions(): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): OptionSetAttribute; + + /** + * Removes the option matching the value. + * + * @param {number} value The value. + */ + removeOption( value: number ): void; + } + + /** + * Interface for a CRM grid control. + * + * @sa Control + */ + export interface GridControl extends Control + { + /** + * Refreshes the sub grid. + * + * @remarks Not available during the "on load" event of the form. + */ + refresh(): void; + } + + /** + * Interface for a framed control, which is either a Web Resource or an Iframe. + * + * @sa Control + * + * @remarks An Iframe control provides additional methods, so use {@link IframeControl} where + * appropriate. Silverlight controls should use {@link SilverlightControl}. + */ + export interface FramedControl extends Control + { + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLIFrameElement; + + /** + * Gets the URL value of the control. + * + * @return The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getSrc(): string; + + /** + * Sets the URL value of the control. + * + * @param {string} src The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setSrc( src: string ): void; + } + + /** + * Interface for an Iframe control. + * + * @sa FramedControl + */ + export interface IframeControl extends FramedControl + { + /** + * Gets initial URL defined for the Iframe. + * + * @return The initial URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getInitialUrl(): string; + } + + /** + * Interface for a Silverlight control. + * + * @sa Control + */ + export interface SilverlightControl extends Control + { + /** + * Gets the query string value passed to Silverlight. + * + * @return The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getData(): string; + + /** + * Sets the query string value passed to Silverlight. + * + * @param {string} data The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setData( data: string ): void; + + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLObjectElement; + } + + /** + * Interface for a form tab. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface Tab extends UiElement, UiFocusable + { + /** + * Gets display state of the tab. + * + * @return The display state, as either "expanded" or "collapsed" + */ + getDisplayState(): string; + + /** + * Gets the name of the tab. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.ui parent of the tab. + * + * @return The parent. + */ + getParent(): typeof ui; + + /** + * Sets display state of the tab. + * + * @param {"collapsed"} displayState Collapsed tab. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the tab. + * + * @param {"expanded"} displayState Expanded tab. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the tab. + * + * @param {string} displayState Display state of the tab, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + + /** + * A reference to the collection of form sections within this tab. + */ + sections: Collection.ItemCollection
; + } + + /** + * Interface for a form section. + * + * @sa UiElement + */ + export interface Section extends UiElement + { + /** + * Gets the name of the section. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.Tab parent of this item. + * + * @return The parent. + */ + getParent(): Tab; + + /** + * A reference to the collection of controls within this tab. + */ + controls: Collection.ItemCollection; + } + + /** + * Module for Xrm.Page.ui API. + */ + export module ui + { + /** + * Interface for Xrm.Page.ui.process API + */ + export interface ProcessManager + { + /** + * Sets display state of the process flow control. + * + * @param {"collapsed"} displayState Collapsed process flow control. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the process flow control. + * + * @param {"expanded"} displayState Expanded process flow control. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the process flow control. + * + * @param {string} displayState Display state of the process flow control, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Clears the form notification described by uniqueId. + * + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, otherwise false. + */ + export function clearFormNotification( uniqueId: string ): boolean; + + /** + * Closes the form. + */ + export function close(): void; + + /** + * Gets form type. + * + * @return The form type. + * + * @remarks Values returned are: 0 Undefined + * 1 Create + * 2 Update + * 3 Read Only + * 4 Disabled + * 6 Bulk Edit + * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) + */ + export function getFormType(): FormType; + + /** + * Gets view port height. + * + * @return The view port height, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function getViewPortHeight(): number; + + /** + * Gets view port width. + * + * @return The view port width, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function getViewPortWidth(): number; + + /** + * Re-evaluates the ribbon's configured EnableRules + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function refreshRibbon(): void; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"ERROR"} level An error message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "ERROR", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"WARNING"} level A warning message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "WARNING", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"INFO"} level An informational message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "INFO", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {string} level The level, as either "ERROR", "WARNING", or "INFO". + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, otherwise false. + */ + export function setFormNotification( message: string, level: string, uniqueId: string ): boolean; + + export var process: ProcessManager; + + /** + * A reference to the collection of controls on the form. + */ + export var controls: Collection.ItemCollection; + + /** + * The form selector API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + export var formSelector: FormSelector; + + /** + * The navigation API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + export var navigation: Navigation; + + /** + * A reference to the collection of tabs on the form. + */ + export var tabs: Collection.ItemCollection; + } + + /** + * Interface for a navigation item. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface NavigationItem extends UiElement, UiFocusable + { + /** + * Gets the name of the item. + * + * @return The identifier. + */ + getId(): string; + } + + /** + * Interface for Xrm.Page.ui.navigation. + */ + export interface Navigation + { + /** + * A reference to the collection of available navigation items. + */ + items: Collection.ItemCollection; + } + + /** + * Interface for an entity's form selector item. + */ + export interface FormItem + { + /** + * Gets the unique identifier of the form. + * + * @return The identifier, in Guid format. + */ + getId(): string; + + /** + * Gets the label for the form. + * + * @return The label. + */ + getLabel(): string; + + /** + * Navigates the user to this form. + */ + navigate(): void; + } + + /** + * Interface for the form selector API. + */ + export interface FormSelector + { + /** + * Gets current form. + * + * @return The current item. + * + * @remarks When only one form is available this method will return null. + */ + getCurrentItem(): FormItem; + + /** + * A reference to the collection of available forms. + */ + items: Collection.ItemCollection; + } + + /** + * A reference to the xRM application context. + */ + export var context: Context; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + export function getAttribute(): Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + export function getAttribute( index: number ): Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + export function getAttribute( delegateFunction: Collection.MatchingDelegate ): Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + export function getControl(): Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + export function getControl( index: number ): Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + export function getControl( delegateFunction: Collection.MatchingDelegate ): Control[]; + } + + /** + * An definition module for URL-based, CRM component parameters. + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export module Url + { + /** + * An enumeration for view types. + */ + export const enum ViewType + { + SystemView = 1039, + UserView = 4230 + } + + /** + * Interface for defining parameters on a request to open a form with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entityrecord" is required in + * the URL, for forms. Example: "pagetype=entityrecord" + */ + export interface FormOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * Additional parameters can be provided to the request. This can only be used to provide + * default field values for the form, or pass data to custom parameters that have been + * customized for the form. See example below for setting the selected form. + * + * @remarks Example: encodeURIComponent( "formid={8c9f3e6f-7839-e211-831e-00155db7d98f}" ); + */ + extraqs?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters on a request to open a view with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entitylist" is required in + * the URL, for views. Example: "pagetype=entitylist" + */ + export interface ViewOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * The unique identifier of a view, in Guid format, which is valid for the entity described by + * {@link etn}. + */ + viewid: string; + + /** + * The type of view identified by {@link viewid}. + * + * @remarks Accepted values are: 1039 System View + * 4230 User View. + */ + viewtype: ViewType; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters of a request to open a dialog with rundialog.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface DialogOpenParameters + { + /** + * The unique identifier of the dialog, in Guid format, which is valid for the entity described + * by: {@link EntityName} + */ + DialogId: string; + + /** + * The logical name of the entity. + */ + EntityName: string; + + /** + * The unique identifier for the targeted record. + */ + ObjectId: string; + } + + /** + * Interface for defining parameters of a request to open a report with viewer.apsx (as with + * window.open). Useful for parsing out the keys and values into a string of the format: + * "&key=value" + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface ReportOpenParameters + { + /** + * The action to perform, as either "run" or "filter". + * + * @remarks "run" Executes the report with default filters. + * "filter" Presents the user with the filter editor, and a "Run Report" button. + */ + action: string; + + /** + * The file name of the report. For out-of-box reports, this parameter enables context-sensitive + * help. + */ + helpID?: string; + + /** + * The unique identifier, held in the report's 'reportid' attribute, in Guid format. + */ + id: string; + } + } + + /** + * The Xrm.Utility API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Utility + { + export interface OpenParameters + { + /** + * Additional parameters can be provided to the request, by overloading + * this object with additional key and value pairs. This can only be used + * to provide default field values for the form, or pass data to custom + * parameters that have been customized for the form. + */ + [index: string]: string; + } + + /** + * Interface for defining parameters on a Xrm.Utility.openEntityForm() request. + */ + export interface FormOpenParameters extends OpenParameters + { + /** + * The identifier of the form to use, when several are available. + */ + formid: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + } + + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + export function alertDialog( message: string, onCloseCallback: () => void ): void; + + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + export function confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; + + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + export function isActivityType( entityType: string ): boolean; + + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. + */ + export function openEntityForm( name: string, id?: string, parameters?: FormOpenParameters ): void; + + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + export function openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } +} diff --git a/xrm/xrm-7.0.tests.ts b/xrm/xrm-7.0.tests.ts new file mode 100644 index 000000000..cb648e585 --- /dev/null +++ b/xrm/xrm-7.0.tests.ts @@ -0,0 +1,72 @@ +/// +/// + +function _getContext() +{ + var errorMessage = "Context is not available."; + if ( typeof GetGlobalContext != "undefined" ) + { return GetGlobalContext(); } + else + { + if ( typeof Xrm != "undefined" ) + { + return Xrm.Page.context; + } + else { throw new Error( errorMessage ); } + } +} + +var crmContext = _getContext(); + +var grids = Xrm.Page.getControl(( control ) => +{ + return control.getControlType() === "subgrid"; +}); + +var selectedGridReferences: Xrm.Page.LookupValue[] = []; + +grids.forEach(( gridControl: Xrm.Page.GridControl ) => +{ + gridControl.refresh(); +}); + +var lookupAttribute = Xrm.Page.getControl( "customerid" ); + +lookupAttribute.addCustomFilter( ` + +`, "account" ); + +lookupAttribute.addPreSearch(() => { alert( "A search was performed." ); }); + +var lookupValues = lookupAttribute.getAttribute().getValue(); + +if ( lookupValues !== null ) + if ( !lookupValues[0].id || !lookupValues[0].entityType ) + throw new Error("Invalid value in Lookup control."); + +if (Xrm.Page.data.process != null) + Xrm.Page.data.process.moveNext(( status ) => { alert( `Process moved forward with status: ${status}` ) }); + +Xrm.Page.ui.controls.forEach(( control ) => { control.setVisible( true ); }); + +Xrm.Page.ui.tabs.forEach(( tab ) => +{ + tab.setVisible( true ); + + tab.sections.forEach(( section ) => + { + section.setVisible( true ); + }); +}); + +Xrm.Page.data.entity.addOnSave(( context ) => +{ + var eventArgs = context.getEventArgs(); + + if ( eventArgs.getSaveMode() === Xrm.Page.SaveMode.AutoSave || eventArgs.getSaveMode() === Xrm.Page.SaveMode.SaveAndClose ) + eventArgs.preventDefault(); +}); + +alert( `The current form type is: ${Xrm.Page.ui.getFormType() }` ); + +alert( `The current entity type is: ${Xrm.Page.data.entity.getEntityName() }` ); diff --git a/xrm/xrm-tests.ts b/xrm/xrm-tests.ts new file mode 100644 index 000000000..610662c7d --- /dev/null +++ b/xrm/xrm-tests.ts @@ -0,0 +1,103 @@ +/// +/// +/// + +/// Demonstrate clientglobalcontext.d.ts + +function _getContext() +{ + var errorMessage = "Context is not available."; + if ( typeof GetGlobalContext != "undefined" ) + { return GetGlobalContext(); } + else + { + if ( typeof Xrm != "undefined" ) + { + return Xrm.Page.context; + } + else { throw new Error( errorMessage ); } + } +} + +var crmContext = _getContext(); + +/// Demonstrate iterator typing + +var grids = Xrm.Page.getControl(( control ) => +{ + return control.getControlType() === "subgrid"; +}); + +var selectedGridReferences: Xrm.Page.LookupValue[] = []; + +/// Demonstrate iterator typing with v7.1 additions + +grids.forEach(( gridControl: Xrm.Page.GridControl ) => +{ + gridControl.getGrid().getSelectedRows().forEach(( row ) => + { + selectedGridReferences.push( row.getData().getEntity().getEntityReference() ); + }) +}); + +/// Demonstrate generic overload vs typecast + +var lookupAttribute = Xrm.Page.getControl( "customerid" ); +var lookupAttribute2 = Xrm.Page.getControl( "customerid" ); + +/// Demonstrate ES6 String literal syntax + +lookupAttribute.addCustomFilter( ` + +`, "account" ); + +lookupAttribute.addPreSearch(() => { alert( "A search was performed." ); }); + +/// Demonstrate strong-typed attribute association with strong-typed control + +var lookupValues = lookupAttribute.getAttribute().getValue(); + +if ( lookupValues !== null ) + if ( !lookupValues[0].id || !lookupValues[0].entityType ) + throw new Error("Invalid value in Lookup control."); + +/// Demonstrate v7.0 BPF API + +if (Xrm.Page.data.process != null) + Xrm.Page.data.process.moveNext(( status ) => { alert( `Process moved forward with status: ${status}` ) }); + +/// Demonstrate v7.1 Quick Create form + +Xrm.Utility.openQuickCreate(( newRecord ) => { alert( `Newly created record Id: ${newRecord.id}` ); }, "account" ); + +/// Make all controls visible. + +Xrm.Page.ui.controls.forEach(( control ) => { control.setVisible( true ); }); + +/// Make all tabs and sections visible. + +Xrm.Page.ui.tabs.forEach(( tab ) => +{ + tab.setVisible( true ); + + tab.sections.forEach(( section ) => + { + section.setVisible( true ); + }); +}); + +/// Demonstrate OnSave event context. + +Xrm.Page.data.entity.addOnSave(( context ) => +{ + var eventArgs = context.getEventArgs(); + + if ( eventArgs.getSaveMode() === Xrm.Page.SaveMode.AutoSave || eventArgs.getSaveMode() === Xrm.Page.SaveMode.SaveAndClose ) + eventArgs.preventDefault(); +}); + +/// Demonstrate ES6 String literal with templates + +alert( `The current form type is: ${Xrm.Page.ui.getFormType() }` ); + +alert( `The current entity type is: ${Xrm.Page.data.entity.getEntityName() }` ); diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts new file mode 100644 index 000000000..8b82136a4 --- /dev/null +++ b/xrm/xrm.d.ts @@ -0,0 +1,2586 @@ +// Type definitions for Microsoft Dynamics xRM API v7.1 +// Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 +// Definitions by: David Berry , Matt Ngan +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Xrm +{ + /** + * Interface for the client context. + */ + export interface ClientContext + { + /** + * Returns a value to indicate which client the script is executing in. + * + * @return The client, as either "Web", "Outlook", or "Mobile" + */ + getClient(): string; + + /** + * Gets client's current state. + * + * @return The client state, as either "Online" or "Offline" + */ + getClientState(): string; + } + + /** + * Interface for the xRM application context. + */ + export interface Context + { + /** + * The client's context instance. + */ + client: ClientContext; + + /** + * Gets client's base URL for Dynamics CRM + * + * @return The client's base URL + * @remarks For Dynamics CRM On-Premises: http(s)://server/org + * For Dynamics CRM Online: https://org.crm.dynamics.com + * For Dynamics CRM for Outlook (Offline): http://localhost:2525 + */ + getClientUrl(): string; + + /** + * Gets current styling theme. + * + * @return The name of the current theme, as either "default", "Office12Blue", or "Office14Silver" + * + * @remarks This function does not work with Dynamics CRM for tablets. + */ + getCurrentTheme(): string; + + /** + * Gets whether automatic save is enabled. + * + * @return true if automatic saving is enabled, otherwise false. + */ + getIsAutoSaveEnabled(): boolean; + + /** + * Gets organization's LCID (language code). + * + * @return The organization language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getOrgLcid(): number; + + /** + * Gets organization's unique name. + * + * @return The organization's unique name. + * + * @remarks This value can be found on the Developer Resources page within Dynamics CRM + */ + getOrgUniqueName(): string; + + /** + * Gets query string parameters. + * + * @return The query string parameters, in a dictionary object representing name and value pairs. + */ + getQueryStringParameters(): { [index: string]: any }; + + /** + * Returns the difference between the local time and Coordinated Universal Time (UTC). + * + * @return The time zone offset, in minutes. + */ + getTimeZoneOffsetMinutes(): number; + + /** + * Gets user's unique identifier. + * + * @return The user's identifier in Guid format. + * + * @remarks Example: "{B05EC7CE-5D51-DF11-97E0-00155DB232D0}" + */ + getUserId(): string; + + /** + * Gets user's LCID (language code). + * + * @return The user's language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getUserLcid(): number; + + /** + * Gets the name of the current user. + * + * @return The user's name. + */ + getUserName(): string; + + /** + * Gets all user security roles. + * + * @return An array of user role identifiers, in Guid format. + * + * @remarks Example: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"] + */ + getUserRoles(): string[]; + + /** + * Prefixes the current organization's unique name to a string; typically a URL path. + * + * @param {string} sPath Local pathname of the resource. + * + * @return A path string with the organization name. + * + * @remarks Format: "/"+ OrgName + sPath + */ + prependOrgName( sPath: string ): string; + } + + /** + * A definition module for asynchronous interface declarations. + */ + export module Async + { + /** + * Called when the operation is successful. + */ + export type SuccessCallbackDelegate = () => void; + + /** + * Called when the operation fails. + * + * @param {number} errorCode The error code. + * @param {string} message The message. + */ + export type ErrorCallbackDelegate = ( errorCode: number, message: string ) => void; + + /** + * Interface for Xrm.Page.data promises. + */ + export interface XrmPromise + { + /** + * A basic 'then' promise. + * + * @param {SuccessCallbackDelegate} successCallback The success callback. + * @param {ErrorCallbackDelegate} errorCallback The error callback. + */ + then( successCallback: SuccessCallbackDelegate, errorCallback: ErrorCallbackDelegate ): void; + } + } + + /** + * A definition module for collection interface declarations. + */ + export module Collection + { + /** + * Interface for a matching delegate. + * + * @tparam T Generic type parameter. + */ + export interface MatchingDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + * + * @return true if the item matches, false if it does not. + */ + ( item: T, index?: number ): boolean; + } + + /** + * Interface for iterative delegate. + * + * @tparam T Generic type parameter. + */ + export interface IterativeDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + */ + ( item: T, index?: number ): void; + } + + /** + * Interface for an item collection. + * + * @tparam T Generic type parameter. + */ + export interface ItemCollection + { + /** + * Applies an operation to all items in this collection. + * + * @param {IterativeDelegate{T}} delegate An iterative delegate function + */ + forEach( delegate: IterativeDelegate ): void; + + /** + * Gets. + * + * @param {MatchingDelegate{T}} delegate A matching delegate function + * + * @return A T[] whose members have been validated by delegate. + */ + get( delegate: MatchingDelegate ): T[]; + + /** + * Gets the item given by the index. + * + * @param {number} itemNumber The item number to get. + * + * @return The T in the itemNumber-th place. + */ + get( itemNumber: number ): T; + + /** + * Gets the item given by the key. + * + * @param {string} itemName The item name to get. + * + * @return The T matching the key itemName. + * + * @see {@link Xrm.Page.Control.getName()} for Control-naming schemes. + */ + get( itemName: string ): T; + + /** + * Gets the entire array of T. + * + * @return A T[]. + */ + get(): T[]; + + /** + * Gets the length of the collection. + * + * @return The length. + */ + getLength(): number; + } + } + + /** + * The Xrm.Page API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Page + { + /** + * Enumeration of entity form states/types. + */ + export const enum FormType + { + Undefined = 0, + Create = 1, + Update = 2, + ReadOnly = 3, + Disabled = 4, + BulkEdit = 6 + } + + /** + * Enumeration of entity form save modes. + */ + export const enum SaveMode + { + Save = 1, + SaveAndClose = 2, + SaveAndNew = 59, + AutoSave = 70, + SaveAsCompleted = 58, + Deactivate = 5, + Reactivate = 6, + Assign = 47, + Send = 7, + Qualify = 16, + Disqualify = 15 + } + + /** + * Enumeration of stage categories. + */ + export const enum StageCategory + { + Qualify = 0, + Develop = 1, + Propose = 2, + Close = 3, + Identify = 4, + Research = 5, + Resolve = 6 + } + + /** + * Enumeration of grid control context resolutions. + */ + export const enum GridControlContext + { + Unknown = 0, + RibbonContextForm = 1, + RibbonContextListing = 2, + FormContextUnrelated = 3, + FormContextRelated = 4 + } + + /** + * Interface for a CRM Business Process Flow instance. + */ + export interface Process + { + /** + * Returns the unique identifier of the process. + * + * @return The identifier for this process, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the process. + * + * @return The name. + */ + getName(): string; + + /** + * Returns an collection of stages in the process. + * + * @return The stages. + */ + getStages(): Collection.ItemCollection; + + /** + * Returns a boolean value to indicate if the process is rendered. + * + * @return true if the process is rendered, false if not. + */ + isRendered(): boolean; + } + + /** + * Interface for CRM Business Process Flow stages. + */ + export interface Stage + { + /** + * Returns an object with a getValue method which will return the integer value of the business process flow + * category. + * + * @return The stage category. + */ + getCategory(): { getValue(): StageCategory }; + + /** + * Returns the logical name of the entity associated with the stage. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns the unique identifier of the stage. + * + * @return The identifier of the Stage, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the stage. + * + * @return The name. + */ + getName(): string; + + /** + * Returns the status of the stage. + * + * @return The status. + * + * @remarks This method will return either "active" or "inactive". + */ + getStatus(): string; + + /** + * Returns a collection of steps in the stage. + * + * @return An array of Step. + */ + getSteps(): Step[]; + } + + export interface Step + { + /** + * Returns the logical name of the attribute associated to the step. + * + * @return The attribute. + * + * @remarks Some steps don’t contain an attribute value. + */ + getAttribute(): string; + + /** + * Returns the name of the step. + * + * @return The name. + */ + getName(): string; + + /** + * Returns whether the step is required in the business process flow. + * + * @return true if required, false if not. + * + * @remarks Returns true if the step is marked as required in the Business Process Flow editor; otherwise, false. + * There is no connection between this value and the values you can change in the Xrm.Page.data.entity + * attribute RequiredLevel methods. + */ + isRequired(): boolean; + } + + /** + * Interface for the event context. + */ + export interface EventContext + { + /** + * Gets the Xrm context. + * + * @return The Xrm context. + */ + getContext(): Context; + + /** + * Gets the handler's depth, which is the order in which the handler is executed. + * + * @return The depth, a 0-based index. + */ + getDepth(): number; + + /** + * Gets save-event arguments. + * + * @return The event arguments. + * + * @remarks Returns null for all but the "save" event. + */ + getEventArgs(): SaveEventArguments; + + /** + * Gets a reference to the object for which event occurred. + * + * @return The event source. + */ + getEventSource(): Xrm.Page.Attribute | Xrm.Page.Entity; + + /** + * Gets the shared variable with the specified key. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * + * @return The shared variable. + * + * @remarks Used to pass values between handlers of an event. + */ + getSharedVariable( key: string ): T; + + /** + * Sets a shared variable. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * @param {T} value The value. + * + * @remarks Used to pass values between handlers of an event. + */ + setSharedVariable( key: string, value: T ): void; + } + + /** + * Interface for a context-sensitive handler. + */ + export interface ContextSensitiveHandler + { + /** + * @param {EventContext} context The context. + */ + ( context?: EventContext ): void; + } + + /** + * Base interface for UI elements. + */ + export interface UiElement + { + /** + * Gets the label. + * + * @return The label. + */ + getLabel(): string; + + /** + * Gets the visibility state. + * + * @return true if the tab is visible, otherwise false. + */ + getVisible(): boolean; + + /** + * Sets the label. + * + * @param {string} label The label. + */ + setLabel( label: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for focusable UI elements. + */ + export interface UiFocusable + { + /** + * Sets focus on the element. + */ + setFocus(): void; + } + + /** + * Interface for a Lookup value. + */ + export interface LookupValue + { + /** + * The identifier. + */ + id: string; + + /** + * The name + */ + name?: string; + + /** + * Type of the entity. + */ + entityType: string; + } + + /** + * Interface for an OptionSet value. + */ + export interface OptionSetValue + { + /** + * The label text. + */ + text: string; + + /** + * The value, as a string. + * + * @remarks You must use parseInt to convert this value to a number before you can use it to + * set the value of an OptionSetAttribute. + */ + value: string; + } + + /** + * Interface for a privilege. + */ + export interface Privilege + { + /** + * true if the user can read. + */ + canRead: boolean; + + /** + * true if the user can update. + */ + canUpdate: boolean; + + /** + * true if the user can create. + */ + canCreate: boolean; + } + + /** + * Interface for an Entity attribute. + */ + export interface Attribute + { + /** + * Adds a handler to be called when the attribute's value is changed. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Fire all "on change" event handlers. + */ + fireOnChange(): void; + + /** + * Gets attribute type. + * + * @return The attribute's type name. + * + * @remarks Values returned are: boolean + * datetime + * decimal + * double + * integer + * lookup + * memo + * money + * optionset + * string + */ + getAttributeType(): string; + + /** + * Gets the attribute format. + * + * @return The format of the attribute. + * + * @see {@link getAttributeType()} + * + * @remarks Values returned are: date (datetime) + * datetime (datetime) + * duration (integer) + * email (string) + * language (optionset) + * none (integer) + * phone (string) + * text (string) + * textarea (string) + * tickersymbol (string) + * timezone (optionset) + * url (string) + */ + getFormat(): string; + + /** + * Gets a boolean value indicating whether this Attribute has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the logical name of the attribute. + * + * @return The logical name. + */ + getName(): string; + + /** + * Gets a reference to the record context of this attribute. + * + * @return The parent record context. + */ + getParent(): Entity; + + /** + * Gets the current level of requirement for the attribute. + * + * @return The required level, as either "none", "required", or "recommended" + */ + getRequiredLevel(): string; + + /** + * Gets current submit mode for the attribute. + * + * @return The submit mode, as either "always", "never", or "dirty" + * + * @remarks The default value is "dirty" + */ + getSubmitMode(): string; + + /** + * Gets the current user's privileges for the attribute. + * + * @return The user privileges. + */ + getUserPrivilege(): Privilege; + + /** + * Removes the handler from the "on change" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Sets required level. + * + * @param {"none"} requirementLevel Not required. + */ + setRequiredLevel( requirementLevel: "none" ): void; + + /** + * Sets required level. + * + * @param {"required"} requirementLevel Required. + */ + setRequiredLevel( requirementLevel: "required" ): void; + + /** + * Sets required level. + * + * @param {"recommended"} requirementLevel Recommended. + */ + setRequiredLevel( requirementLevel: "recommended" ): void; + + /** + * Sets the required level. + * + * @param {string} requirementLevel The requirement level, as either "none", "required", or "recommended" + */ + setRequiredLevel( requirementLevel: string ): void; + + /** + * Sets submit mode. + * + * @param {"always"} submitMode Always submit this attribute. + */ + setSubmitMode( submitMode: "always" ): void; + + /** + * Sets submit mode. + * + * @param {"never"} submitMode Never submit this attribute. + */ + setSubmitMode( submitMode: "never" ): void; + + /** + * Sets submit mode. + * + * @param {"dirty"} submitMode Submit this attribute when changed. + */ + setSubmitMode( submitMode: "dirty" ): void; + + /** + * Sets the submit mode. + * + * @param {string} submitMode The submit mode, as either "always", "never", or "dirty". + * + * @remarks The default value is "dirty" + */ + setSubmitMode( submitMode: string ): void; + + /** + * A collection of all the controls on the form that interface with this attribute. + */ + controls: Collection.ItemCollection; + } + + /** + * Interface for a Number attribute. + * + * @sa Attribute + */ + export interface NumberAttribute extends Attribute + { + /** + * Gets the maximum value allowed. + * + * @return The maximum value allowed. + */ + getMax(): number; + + /** + * Gets the minimum value allowed. + * + * @return The minimum value allowed. + */ + getMin(): number; + + /** + * Gets the attribute's configured precision. + * + * @return The total number of allowed decimal places. + */ + getPrecision(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface for a String attribute. + * + * @sa Attribute + */ + export interface StringAttribute extends Attribute + { + /** + * Gets maximum length allowed. + * + * @return The maximum length allowed. + * + * @remarks The email form's "Description" attribute does not have the this method. + */ + getMaxLength(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): string; + + /** + * Sets the value. + * + * @param {string} value The value. + * + * @remarks A String field with the {@link Attribute.getFormat|email} format enforces email + * address formatting. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: string ): void; + } + + /** + * Common interface for enumeration attributes (OptionSet and Boolean). + * + * @sa Attribute + */ + export interface EnumAttribute extends Attribute + { + /** + * Gets the initial value of the attribute. + * + * @return The initial value. + * @remarks Valid for optionset and boolean attribute types + */ + getInitialValue(): number | boolean; + } + + /** + * Interface for a Boolean attribute. + * + * @sa EnumAttribute + */ + export interface BooleanAttribute extends EnumAttribute + { + /** + * Gets the value. + * + * @return true if it succeeds, false if it fails. + */ + getValue(): boolean; + + /** + * Sets the value. + * + * @param {boolean} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: boolean ): void; + } + + /** + * Interface for a Date attribute. + * + * @sa Attribute + */ + export interface DateAttribute extends Attribute + { + /** + * Gets the value. + * + * @return The value. + */ + getValue(): Date; + + /** + * Sets the value. + * + * @param {Date} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: Date ): void; + } + + /** + * Interface an OptionSet attribute. + * + * @sa EnumAttribute + */ + export interface OptionSetAttribute extends EnumAttribute + { + /** + * Gets the option matching a value. + * + * @param {number} value The enumeration value of the option desired. + * + * @return The option. + */ + getOption( value: number ): OptionSetValue; + + /** + * Gets the option matching a label. + * + * @param {string} label The label of the option desired. + * + * @return The option. + */ + getOption( label: string ): OptionSetValue; + + /** + * Gets all of the options. + * + * @return An array of options. + */ + getOptions(): OptionSetValue[]; + + /** + * Gets selected option. + * + * @return The selected option. + */ + getSelectedOption(): OptionSetValue; + + /** + * Gets the label of the currently selected option. + * + * @return The current value's label. + */ + getText(): string; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks The getOptions() method returns option values as strings. You must use parseInt + * to convert them to numbers before you can use those values to set the value of an + * OptionSet attribute. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface a Lookup attribute. + * + * @sa Attribute + */ + export interface LookupAttribute extends Attribute + { + /** + * Gets a boolean value indicating whether the Lookup is a multi-value PartyList. + * + * @return true the attribute is a PartyList, otherwise false. + */ + getIsPartyList(): boolean; + + /** + * Gets the value. + * + * @return An array of LookupValue. + */ + getValue(): LookupValue[]; + + /** + * Sets the value. + * + * @param {LookupValue[]} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: LookupValue[] ): void; + } + + /** + * Interface for the form's record context, Xrm.Page.data.entity + */ + export interface Entity + { + /** + * Adds a handler to be called when the record is saved. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + addOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Gets an serialized-XML string representing data that will be passed to the server upon saving + * the record. + * + * @return The XML in string format. + * + * @remarks This function does not work with Microsoft Dynamics CRM for tablets. Example: + * "Contoso55555425 + * 555-1234". + */ + getDataXml(): string; + + /** + * Gets entity's logical name. + * + * @return The logical name. + */ + getEntityName(): string; + + /** + * Gets the record's unique identifier. + * + * @return The identifier, in Guid format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Gets a boolean value indicating whether the record has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the record's primary attribute value. + * + * @return The primary attribute value. + * + * @remarks The value for this attribute is used when links to the record are displayed. + */ + getPrimaryAttributeValue(): string; + + /** + * Removes the handler from the "on save" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Saves the record. + * + * @remarks When using quick create forms in the web application the saveandnew option is not + * applied. It will always work as if saveandclose were used. Quick create forms in + * Microsoft Dynamics CRM for tablets will apply the saveandnew behavior. + */ + save(): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandclose"} saveMode Saves the record, and closes the form. + */ + save( saveMode: "saveandclose" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandnew"} saveMode Saves the record, and opens a blank form. + */ + save( saveMode: "saveandnew" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {string} saveMode (Optional) the save mode to save, as either "saveandclose" or + * "saveandnew". + */ + save( saveMode: string ): void; + + /** + * The collection of attributes for the record. + */ + attributes: Collection.ItemCollection; + } + + /** + * Interface for save event arguments. + */ + export interface SaveEventArguments + { + /** + * Gets save mode, as an integer. + * + * @return The save mode. + * @remarks Values returned are: 1 Save + * 2 Save and Close + * 59 Save and New + * 70 AutoSave (Where enabled; can be used with an OnSave handler + * to conditionally disable auto-saving) + * 58 Save as Completed (Activities) + * 5 Deactivate + * 6 Reactivate + * 47 Assign (All user- or team-owned entities) + * 7 Send (Email) + * 16 Qualify (Lead) + * 15 Disqualify (Lead) + */ + getSaveMode(): SaveMode; + + /** + * Returns a boolean value to indicate if the record's save has been prevented. + * + * @return true if saving is prevented, otherwise false. + */ + isDefaultPrevented(): boolean; + + /** + * Prevents the save operation from being submitted to the server. + * @remarks All remaining "on save" handlers will continue execution. + */ + preventDefault(): void; + } + + /** + * Module for the Xrm.Page.data API. + */ + export module data + { + /** + * Interface for the Xrm.Page.data.process API. + */ + export interface ProcessManager + { + /** + * Returns a Process object representing the active process. + * + * @return current active process. + */ + getActiveProcess(): Process; + + /** + * Set a Process as the active process. + * + * @param {string} processId the Id of the process to make the active process. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveProcess( processId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Returns a Stage object representing the active stage. + * + * @return current active stage. + */ + getActiveStage(): Stage; + + /** + * Set a stage as the active stage. + * + * @param {string} stageId the Id of the stage to make the active stage. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveStage( stageId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Use this method to get a collection of stages currently in the active path with methods to interact with the + * stages displayed in the business process flow control. The active path represents stages currently rendered in + * the process control based on the branching rules and current data in the record. + * + * @return A collection of all completed stages, the currently active stage, and the predicted set of future stages + * based on satisfied conditions in the branching rule. This may be a subset of the stages returned with + * Xrm.Page.data.process.getActiveProcess because it will only include those stages which represent a valid + * transition from the current stage based on branching that has occurred in the process. + */ + getActivePath(): Collection.ItemCollection; + + /** + * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an + * entity. + * + * @param {Function} callbackFunction The callback function must accept a parameter + * that contains an object with dictionary + * properties where the name of the property is the + * Id of the business process flow and the value of + * the property is the name of the business process + * flow. + * + * The enabled processes are filtered according to + * the user’s privileges. The list of enabled + * processes is the same ones a user can see in the + * UI if they want to change the process manually. + */ + getEnabledProcesses( callbackFunction: ( enabledProcesses: ProcessDictionary ) => void ): void; + + /** + * Use this to add a function as an event handler for the OnStageChange event so that it will be called when the + * business process flow stage changes. + * + * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event handler + * pipeline. The execution context is automatically set to be the first + * parameter passed to the event handler. + */ + addOnStageChange( handler: ContextSensitiveHandler ): void; + + /** + * Use this to remove a function as an event handler for the OnStageChange event. + * + * @param {ContextSensitiveHandler} handler If an anonymous function is set using the addOnStageChange method it + * cannot be removed using this method. + */ + removeOnStageSelected( handler: ContextSensitiveHandler ): void; + + /** + * Progresses to the next stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + moveNext( callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Moves to the previous stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + movePrevious( callbackFunction?: ProcessCallbackDelegate ): void; + } + + /** + * Called when process change methods have completed. + * + * @param {string} status The result of the process change operation. + * @remarks Values returned are: success (The operation succeeded.) + * crossEntity (The previous stage is for a different entity.) + * beginning (The active stage is the first stage of the active path.) + * invalid (The operation failed because the selected stage isn’t the same + * as the active stage.) + * unreachable (The stage exists on a different path.) + */ + export type ProcessCallbackDelegate = ( status: string ) => void; + + /** + * Represents a key-value pair, where the key is the Process Flow's ID, and the value is the name thereof. + */ + export type ProcessDictionary = { [index: string]: string }; + + /** + * Asynchronously refreshes data on the form, without reloading the page. + * + * @param {boolean} save true to save the record, after the refresh. + * + * @return An Async.XrmPromise. + */ + export function refresh( save: boolean ): Async.XrmPromise; + + /** + * Asynchronously saves the record. + * + * @return An Async.XrmPromise. + */ + export function save(): Async.XrmPromise; + + /** + * The record context of the form. + */ + export var entity: Entity; + + /** + * The process API for Xrm.Page.data. + * + * @remarks This member may be undefined when Process Flows are not used by the current entity. + */ + export var process: ProcessManager; + } + + /** + * Interface for Xrm.Page.ui controls. + * + * @sa UiElement + */ + export interface Control extends UiElement + { + /** + * Clears the notification identified by uniqueId. + * + * @param {string} uniqueId (Optional) Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks If the uniqueId parameter is not used, the current notification shown will be removed. + */ + clearNotification( uniqueId?: string ): boolean; + + /** + * Gets the control's type. + * + * @return The control type. + * @remarks Values returned are: standard + * iframe + * lookup + * optionset + * subgrid + * webresource + * notes + * timercontrol + * kbsearch (CRM Online Only, use parature.d.ts) + */ + getControlType(): string; + + /** + * Gets a boolean value, indicating whether the control is disabled. + * + * @return true if it is disabled, otherwise false. + */ + getDisabled(): boolean; + + /** + * Gets the name of the control on the form. + * + * @return The name of the control. + * + * @remarks The name assigned to a control is not determined until the form loads. Changes to + * the form may change the name assigned to a given control. + * When you use the control getName method the name of the first control will be the + * same as the name of the attribute. The second instance of a control for that + * attribute will be "1". The pattern +N + * will continue for each additional control added to the form for a specific + * attribute. When a form displays a business process flow control in the header, + * additional controls will be added for each attribute that is displayed in the + * business process flow. These controls have a unique name like the following: + * header_process_. + */ + getName(): string; + + /** + * Gets a reference to the Section parent of the control. + * + * @return The parent Section. + */ + getParent(): Section; + + /** + * Sets the state of the control to either enabled, or disabled. + * + * @param {boolean} disabled true to disable, false to enable. + */ + setDisabled( disabled: boolean ): void; + + /** + * Sets a control-local notification message. + * + * @param {string} message The message. + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks When this method is used on Microsoft Dynamics CRM for tablets a red "X" icon + * appears next to the control. Tapping on the icon will display the message. + */ + setNotification( message: string, uniqueId: string ): boolean; + } + + /** + * Interface for a standard control. + * + * @sa Control + */ + export interface StandardControl extends Control + { + /** + * Gets the control's bound attribute. + * + * @tparam T An Attribute type. + * + * @return The attribute. + */ + getAttribute(): T; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): Attribute; + } + + /** + * Interface for a Date control. + * + * @sa StandardControl + */ + export interface DateControl extends StandardControl + { + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): DateAttribute; + + /** + * Gets the status of the time-of-day component of the Date control. + * + * @return true if the time is shown, otherwise false. + */ + getShowTime(): boolean; + + /** + * Sets the visibility of the time component of the Date control. + * + * @param {boolean} showTimeValue true to show, false to hide the time value. + */ + setShowTime( showTimeValue: boolean ): void; + } + + /** + * Interface for a Lookup control. + * + * @sa StandardControl + */ + export interface LookupControl extends StandardControl + { + /** + * Adds a handler to the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + addPreSearch( handler: () => void ): void; + + /** + * Adds an additional custom filter to the lookup, with the "AND" filter operator. + * Can only be used within a "pre search" event handler + * + * @sa addPreSearch + * + * @param {string} filter Specifies the filter, as a serialized FetchXML + * "filter" node. + * @param {string} entityLogicalName (Optional) The logical name of the entity. + * + * @remarks If entityLogicalName is not specified, the filter will be applied to all entities + * valid for the Lookup control. + * Example filter: + * + * + */ + addCustomFilter( filter: string, entityLogicalName?: string ): void; + + /** + * Adds a custom view for the Lookup dialog. + * + * @param {string} viewId Unique identifier for the view, in Guid format. + * @param {string} entityName Name of the entity. + * @param {string} viewDisplayName Name of the view to display. + * @param {string} fetchXml The FetchXML query for the view's contents, serialized as a string. + * @param {string} layoutXml The Layout XML, serialized as a string. + * @param {boolean} isDefault true, to treat this view as default. + * + * @remarks Cannot be used on "Owner" Lookup controls. + * The viewId is never saved to CRM, but must be unique across available views. Generating + * a new value can be accomplished with a {@link http://www.guidgen.com/|Guid generator}. + * Example viewId value: "{00000000-0000-0000-0000-000000000001}" + * Layout XML Reference: {@link http://msdn.microsoft.com/en-us/library/gg334522.aspx} + */ + addCustomView( viewId: string, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean ): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): LookupAttribute; + + /** + * Gets the unique identifier of the default view. + * + * @return The default view, in Guid format. + * + * @remarks Example: "{00000000-0000-0000-0000-000000000000}" + */ + getDefaultView(): string; + + /** + * Removes the handler from the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + removePreSearch( handler: () => void ): void; + + /** + * Sets the Lookup's default view. + * + * @param {string} viewGuid Unique identifier for the view. + * + * @remarks Example viewGuid value: "{00000000-0000-0000-0000-000000000000}" + */ + setDefaultView( viewGuid: string ): void; + } + + /** + * Interface for an OptionSet control. + * + * @sa StandardControl + */ + export interface OptionSetControl extends StandardControl + { + /** + * Adds an option. + * + * @param {OptionSetValue} option The option. + * @param {number} index (Optional) zero-based index of the option. + * + * @remarks This method does not check that the values within the options you add are valid. + * If index is not provided, the new option will be added to the end of the list. + */ + addOption( option: OptionSetValue, index?: number ): void; + + /** + * Clears all options. + */ + clearOptions(): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): OptionSetAttribute; + + /** + * Removes the option matching the value. + * + * @param {number} value The value. + */ + removeOption( value: number ): void; + } + + /** + * Interface for a CRM grid control. + * + * @sa Control + */ + export interface GridControl extends Control + { + /** + * Use this method to add event handlers to the GridControl's OnLoad event. + * + * @param {Function} handler The event handler. + */ + addOnLoad( handler: () => void ): void; + + /** + * This method returns context information about the GridControl. + * + * @return The context type. + */ + getContextType(): GridControlContext; + + /** + * Use this method to get the logical name of the entity data displayed in the grid. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Use this method to get access to the Grid available in the GridControl. + * + * @return The grid. + */ + getGrid(): ui.Grid; + + /** + * Use this method to get access to the ViewSelector available for the GridControl when it is configured to display views. + * + * @return The view selector. + */ + getViewSelector(): ui.ViewSelector; + + /** + * Refreshes the sub grid. + * + * @remarks Not available during the "on load" event of the form. + */ + refresh(): void; + + /** + * Use this method to remove event handlers from the GridControl's OnLoad event. + * + * @param {Function} handler The handler. + */ + removeOnLoad( handler: () => void ): void; + } + + /** + * Interface for a framed control, which is either a Web Resource or an Iframe. + * + * @sa Control + * + * @remarks An Iframe control provides additional methods, so use {@link IframeControl} where + * appropriate. Silverlight controls should use {@link SilverlightControl}. + */ + export interface FramedControl extends Control + { + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLIFrameElement; + + /** + * Gets the URL value of the control. + * + * @return The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getSrc(): string; + + /** + * Sets the URL value of the control. + * + * @param {string} src The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setSrc( src: string ): void; + } + + /** + * Interface for an Iframe control. + * + * @sa FramedControl + */ + export interface IframeControl extends FramedControl + { + /** + * Gets initial URL defined for the Iframe. + * + * @return The initial URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getInitialUrl(): string; + } + + /** + * Interface for a Silverlight control. + * + * @sa Control + */ + export interface SilverlightControl extends Control + { + /** + * Gets the query string value passed to Silverlight. + * + * @return The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getData(): string; + + /** + * Sets the query string value passed to Silverlight. + * + * @param {string} data The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setData( data: string ): void; + + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLObjectElement; + } + + /** + * Interface for a form tab. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface Tab extends UiElement, UiFocusable + { + /** + * Gets display state of the tab. + * + * @return The display state, as either "expanded" or "collapsed" + */ + getDisplayState(): string; + + /** + * Gets the name of the tab. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.ui parent of the tab. + * + * @return The parent. + */ + getParent(): typeof ui; + + /** + * Sets display state of the tab. + * + * @param {"collapsed"} displayState Collapsed tab. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the tab. + * + * @param {"expanded"} displayState Expanded tab. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the tab. + * + * @param {string} displayState Display state of the tab, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + + /** + * A reference to the collection of form sections within this tab. + */ + sections: Collection.ItemCollection
; + } + + /** + * Interface for a form section. + * + * @sa UiElement + */ + export interface Section extends UiElement + { + /** + * Gets the name of the section. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.Tab parent of this item. + * + * @return The parent. + */ + getParent(): Tab; + + /** + * A reference to the collection of controls within this tab. + */ + controls: Collection.ItemCollection; + } + + /** + * Module for Xrm.Page.ui API. + */ + export module ui + { + /** + * Interface for Xrm.Page.ui.process API + */ + export interface ProcessManager + { + /** + * Sets display state of the process flow control. + * + * @param {"collapsed"} displayState Collapsed process flow control. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the process flow control. + * + * @param {"expanded"} displayState Expanded process flow control. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the process flow control. + * + * @param {string} displayState Display state of the process flow control, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for a grid. Use Grid methods to access information about data in the grid. Grid is returned by the + * GridControl.getGrid method. + */ + export interface Grid + { + /** + * Returns a collection of every GridRow in the Grid. + * + * @return The rows. + */ + getRows(): Collection.ItemCollection; + + /** + * Returns a collection of every selected GridRow in the Grid. + * + * @return The selected rows. + */ + getSelectedRows(): Collection.ItemCollection; + + /** + * Returns the total number of records in the Grid. + * + * @return The total record count. + */ + getTotalRecordCount(): number; + } + + /** + * Interface for a grid row. Use the GridRow.getData method to access the GridRowData. A collection of GridRow is + * returned by Grid.getRows and Grid.getSelectedRows methods. + */ + export interface GridRow + { + /** + * Returns the GridRowData for the GridRow. + * + * @return The data. + */ + getData(): GridRowData; + } + + /** + * Interface for grid row data. Use the GridRowData.getEntity method to access the GridEntity. GridRowData is + * returned by the GridRow.getData method. + */ + export interface GridRowData + { + /** + * Returns the GridEntity for the GridRowData. + * + * @return The entity. + */ + getEntity(): GridEntity; + } + + /** + * Interface for a grid entity. Use the GridEntity methods to access data about the specific records in the rows. + * GridEntity is returned by the GridRowData.getEntity method. + */ + export interface GridEntity + { + /** + * Returns the logical name for the record in the row. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns a LookupValue that references this record. + * + * @return The entity reference. + */ + getEntityReference(): LookupValue; + + /** + * Returns the id for the record in the row. + * + * @return The identifier of the GridEntity, in GUID format. + * + * @remarks Example return: "{00000000-0000-0000-0000-000000000000}" + */ + getId(): string; + + /** + * Returns the primary attribute value for the record in the row. (Commonly the name.) + * + * @return The primary attribute value. + */ + getPrimaryAttributeValue(): string; + } + + /** + * Interface for the view selector. Use the ViewSelector methods to get or set information about the view selector + * of the grid control. + */ + export interface ViewSelector + { + /** + * Use this method to get a reference to the current view. + * + * @return The current view. + */ + getCurrentView(): ViewSelectorItem; + + /** + * Use this method to determine whether the view selector is visible. + * + * @return true if visible, false if not. + */ + isVisible(): boolean; + + /** + * Use this method to set the current view. + * + * @param {ViewSelectorItem} viewSelectorItem The view selector item. + */ + setCurrentView( viewSelectorItem: ViewSelectorItem ): void; + } + + /** + * Interface for a view selector item. This object contains data that identifies a view. Use this as a parameter to + * the ViewSelector.setCurrentView method. + */ + export interface ViewSelectorItem + { + /** + * Returns a LookupValue that references this view. + * + * @return The entity reference. + */ + getEntityReference(): LookupValue; + } + + /** + * Clears the form notification described by uniqueId. + * + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, otherwise false. + */ + export function clearFormNotification( uniqueId: string ): boolean; + + /** + * Closes the form. + */ + export function close(): void; + + /** + * Gets form type. + * + * @return The form type. + * + * @remarks Values returned are: 0 Undefined + * 1 Create + * 2 Update + * 3 Read Only + * 4 Disabled + * 6 Bulk Edit + * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) + */ + export function getFormType(): FormType; + + /** + * Gets view port height. + * + * @return The view port height, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function getViewPortHeight(): number; + + /** + * Gets view port width. + * + * @return The view port width, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function getViewPortWidth(): number; + + /** + * Re-evaluates the ribbon's configured EnableRules + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function refreshRibbon(): void; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"ERROR"} level An error message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "ERROR", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"WARNING"} level A warning message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "WARNING", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"INFO"} level An informational message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "INFO", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {string} level The level, as either "ERROR", "WARNING", or "INFO". + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, otherwise false. + */ + export function setFormNotification( message: string, level: string, uniqueId: string ): boolean; + + export var process: ProcessManager; + + /** + * A reference to the collection of controls on the form. + */ + export var controls: Collection.ItemCollection; + + /** + * The form selector API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + export var formSelector: FormSelector; + + /** + * The navigation API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + export var navigation: Navigation; + + /** + * A reference to the collection of tabs on the form. + */ + export var tabs: Collection.ItemCollection; + } + + /** + * Interface for a navigation item. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface NavigationItem extends UiElement, UiFocusable + { + /** + * Gets the name of the item. + * + * @return The identifier. + */ + getId(): string; + } + + /** + * Interface for Xrm.Page.ui.navigation. + */ + export interface Navigation + { + /** + * A reference to the collection of available navigation items. + */ + items: Collection.ItemCollection; + } + + /** + * Interface for an entity's form selector item. + */ + export interface FormItem + { + /** + * Gets the unique identifier of the form. + * + * @return The identifier, in Guid format. + */ + getId(): string; + + /** + * Gets the label for the form. + * + * @return The label. + */ + getLabel(): string; + + /** + * Navigates the user to this form. + */ + navigate(): void; + } + + /** + * Interface for the form selector API. + */ + export interface FormSelector + { + /** + * Gets current form. + * + * @return The current item. + * + * @remarks When only one form is available this method will return null. + */ + getCurrentItem(): FormItem; + + /** + * A reference to the collection of available forms. + */ + items: Collection.ItemCollection; + } + + /** + * A reference to the xRM application context. + */ + export var context: Context; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + export function getAttribute(): Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + export function getAttribute( index: number ): Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + export function getAttribute( delegateFunction: Collection.MatchingDelegate ): Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + export function getControl(): Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + export function getControl( index: number ): Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + export function getControl( delegateFunction: Collection.MatchingDelegate ): Control[]; + } + + /** + * An definition module for URL-based, CRM component parameters. + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export module Url + { + /** + * An enumeration for view types. + */ + export const enum ViewType + { + SystemView = 1039, + UserView = 4230 + } + + /** + * Interface for defining parameters on a request to open a form with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entityrecord" is required in + * the URL, for forms. Example: "pagetype=entityrecord" + */ + export interface FormOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * Additional parameters can be provided to the request. This can only be used to provide + * default field values for the form, or pass data to custom parameters that have been + * customized for the form. See example below for setting the selected form. + * + * @remarks Example: encodeURIComponent( "formid={8c9f3e6f-7839-e211-831e-00155db7d98f}" ); + */ + extraqs?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters on a request to open a view with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entitylist" is required in + * the URL, for views. Example: "pagetype=entitylist" + */ + export interface ViewOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * The unique identifier of a view, in Guid format, which is valid for the entity described by + * {@link etn}. + */ + viewid: string; + + /** + * The type of view identified by {@link viewid}. + * + * @remarks Accepted values are: 1039 System View + * 4230 User View. + */ + viewtype: ViewType; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters of a request to open a dialog with rundialog.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface DialogOpenParameters + { + /** + * The unique identifier of the dialog, in Guid format, which is valid for the entity described + * by: {@link EntityName} + */ + DialogId: string; + + /** + * The logical name of the entity. + */ + EntityName: string; + + /** + * The unique identifier for the targeted record. + */ + ObjectId: string; + } + + /** + * Interface for defining parameters of a request to open a report with viewer.apsx (as with + * window.open). Useful for parsing out the keys and values into a string of the format: + * "&key=value" + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface ReportOpenParameters + { + /** + * The action to perform, as either "run" or "filter". + * + * @remarks "run" Executes the report with default filters. + * "filter" Presents the user with the filter editor, and a "Run Report" button. + */ + action: string; + + /** + * The file name of the report. For out-of-box reports, this parameter enables context-sensitive + * help. + */ + helpID?: string; + + /** + * The unique identifier, held in the report's 'reportid' attribute, in Guid format. + */ + id: string; + } + } + + /** + * The Xrm.Utility API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Utility + { + export interface OpenParameters + { + /** + * Additional parameters can be provided to the request, by overloading + * this object with additional key and value pairs. This can only be used + * to provide default field values for the form, or pass data to custom + * parameters that have been customized for the form. + */ + [index: string]: string; + } + + /** + * Interface for defining parameters on a Xrm.Utility.openEntityForm() request. + */ + export interface FormOpenParameters extends OpenParameters + { + /** + * The identifier of the form to use, when several are available. + */ + formid: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + } + + /** + * Interface for window options. + */ + export interface WindowOptions + { + /** + * Direct the form to open in a new window. + */ + openInNewWindow: boolean; + } + + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + export function alertDialog( message: string, onCloseCallback: () => void ): void; + + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + export function confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; + + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + export function isActivityType( entityType: string ): boolean; + + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. + * @param {WindowOptions} windowOptions (Optional) Options for controlling the window. + */ + export function openEntityForm( name: string, id?: string, parameters?: FormOpenParameters, windowOptions?: WindowOptions ): void; + + /** + * Opens quick create. + * + * @param {Function} callback The function that will be called when a record is created. This + * function is passed a LookupValue object as a parameter. + * @param {string} entityLogicalName The logical name of the entity to create. + * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values + * based on mapped attribute values. + * @param {OpenParameters} parameters (Optional) A dictionary object that passes extra query string + * parameters to the form. Invalid query string parameters will cause an + * error. + */ + export function openQuickCreate( callback: ( recordReference: Page.LookupValue ) => void, + entityLogicalName: string, + createFromEntity?: Page.LookupValue, + parameters?: OpenParameters ): void; + + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + export function openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } +} diff --git a/xss-filters/xss-filters-tests.ts b/xss-filters/xss-filters-tests.ts new file mode 100644 index 000000000..49a566efc --- /dev/null +++ b/xss-filters/xss-filters-tests.ts @@ -0,0 +1,37 @@ +/// + +import xssFilters = require('xss-filters'); + +var s = ''; + +xssFilters.inHTMLComment(s); +xssFilters.inHTMLData(s); +xssFilters.inDoubleQuotedAttr(s); +xssFilters.inSingleQuotedAttr(s); +xssFilters.inUnQuotedAttr(s); +xssFilters.uriInHTMLComment(s); +xssFilters.uriInHTMLData(s); +xssFilters.uriInDoubleQuotedAttr(s); +xssFilters.uriInSingleQuotedAttr(s); +xssFilters.uriInUnQuotedAttr(s); +xssFilters.uriPathInHTMLComment(s); +xssFilters.uriPathInHTMLData(s); +xssFilters.uriPathInDoubleQuotedAttr(s); +xssFilters.uriPathInSingleQuotedAttr(s); +xssFilters.uriPathInUnQuotedAttr(s); +xssFilters.uriQueryInHTMLComment(s); +xssFilters.uriQueryInHTMLData(s); +xssFilters.uriQueryInDoubleQuotedAttr(s); +xssFilters.uriQueryInSingleQuotedAttr(s); +xssFilters.uriQueryInUnQuotedAttr(s); +xssFilters.uriComponentInHTMLComment(s); +xssFilters.uriComponentInHTMLData(s); +xssFilters.uriComponentInDoubleQuotedAttr(s); +xssFilters.uriComponentInSingleQuotedAttr(s); +xssFilters.uriComponentInUnQuotedAttr(s); +xssFilters.uriFragmentInHTMLComment(s); +xssFilters.uriFragmentInHTMLData(s); +xssFilters.uriFragmentInDoubleQuotedAttr(s); +xssFilters.uriFragmentInSingleQuotedAttr(s); +xssFilters.uriFragmentInUnQuotedAttr(s); + diff --git a/xss-filters/xss-filters.d.ts b/xss-filters/xss-filters.d.ts new file mode 100644 index 000000000..3ac33d4f3 --- /dev/null +++ b/xss-filters/xss-filters.d.ts @@ -0,0 +1,43 @@ +// Type definitions for Yahoo XSS Filters +// Project: https://github.com/yahoo/xss-filters +// Definitions by: Dave Taylor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface XSSFilters { + inHTMLComment(s:string):string; + inHTMLData(s:string):string; + inDoubleQuotedAttr(s:string):string; + inSingleQuotedAttr(s:string):string; + inUnQuotedAttr(s:string):string; + uriInHTMLComment(s:string):string; + uriInHTMLData(s:string):string; + uriInDoubleQuotedAttr(s:string):string; + uriInSingleQuotedAttr(s:string):string; + uriInUnQuotedAttr(s:string):string; + uriPathInHTMLComment(s:string):string; + uriPathInHTMLData(s:string):string; + uriPathInDoubleQuotedAttr(s:string):string; + uriPathInSingleQuotedAttr(s:string):string; + uriPathInUnQuotedAttr(s:string):string; + uriQueryInHTMLComment(s:string):string; + uriQueryInHTMLData(s:string):string; + uriQueryInDoubleQuotedAttr(s:string):string; + uriQueryInSingleQuotedAttr(s:string):string; + uriQueryInUnQuotedAttr(s:string):string; + uriComponentInHTMLComment(s:string):string; + uriComponentInHTMLData(s:string):string; + uriComponentInDoubleQuotedAttr(s:string):string; + uriComponentInSingleQuotedAttr(s:string):string; + uriComponentInUnQuotedAttr(s:string):string; + uriFragmentInHTMLComment(s:string):string; + uriFragmentInHTMLData(s:string):string; + uriFragmentInDoubleQuotedAttr(s:string):string; + uriFragmentInSingleQuotedAttr(s:string):string; + uriFragmentInUnQuotedAttr(s:string):string; +} + +declare var xssFilters:XSSFilters; + +declare module 'xss-filters' { + export = xssFilters; +}