diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 60ef278e8..a8032eaab 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -63,7 +63,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](bgiframe/typescript.bgiframe.d.ts) [bgiframe](https://github.com/sumegizoltan/BgiFrame) by [Zoltan Sumegi](https://github.com/sumegizoltan) * [:link:](big.js/big.js.d.ts) [big.js](https://github.com/MikeMcl/big.js) by [Steve Ognibene](https://github.com/nycdotnet) * [:link:](bigint/bigint.d.ts) [BigInt](https://github.com/Evgenus/BigInt) by [Eugene Chernyshov](https://github.com/Evgenus) -* [:link:](big-integer/big-integer.d.ts) [BigInteger.js](https://github.com/peterolson/BigInteger.js) by [Ingo Bürk](https://github.com/Airblader) +* [:link:](big-integer/big-integer.d.ts) [BigInteger.js](https://github.com/peterolson/BigInteger.js) by [Ingo Bürk](https://github.com/Airblader), [Roel van Uden](https://github.com/Deathspike) * [:link:](bigscreen/bigscreen.d.ts) [BigScreen](http://brad.is/coding/BigScreen) by [Douglas Eichelberger](https://github.com/dduugg) * [:link:](bluebird/bluebird.d.ts) [bluebird](https://github.com/petkaantonov/bluebird) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](body-parser/body-parser.d.ts) [body-parser](http://expressjs.com) by [Santi Albo](https://github.com/santialbo), [VILIC VANE](https://vilic.info), [Jonathan Häberle](https://github.com/dreampulse) @@ -149,6 +149,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](diff/diff.d.ts) [diff](https://github.com/kpdecker/jsdiff) by [vvakame](https://github.com/vvakame) * [:link:](docCookies/docCookies.d.ts) [docCookies](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie) by [Jon Egerton](https://github.com/jonegerton) * [:link:](dock-spawn/dock-spawn.d.ts) [Dock Spawn](http://dockspawn.com) by [Drew Noakes](https://drewnoakes.com) +* [:link:](documentdb/documentdb.d.ts) [DocumentDB](https://github.com/Azure/azure-documentdb-node) by [Noel Abrahams](https://github.com/NoelAbrahams) * [:link:](dojo/dojo.d.ts) [Dojo](http://dojotoolkit.org) by [Michael Van Sickle](https://github.com/vansimke) * [:link:](domo/domo.d.ts) [Domo](http://domo-js.com) by [Steve Fenton](https://github.com/Steve-Fenton) * [:link:](domready/domready.d.ts) [domready](https://github.com/ded/domready) by [Christian Holm Nielsen](https://github.com/dotnetnerd) @@ -174,8 +175,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:](esprima/esprima.d.ts) [Esprima](http://esprima.org) by [teppeis](https://github.com/teppeis) +* [: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:](event-loop-lag/event-loop-lag.d.ts) [event-loop-lag](https://github.com/pebble/event-loop-lag) by [rogierschouten](https://github.com/rogierschouten) * [:link:](exit/exit.d.ts) [exit](https://github.com/cowboy/node-exit) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](expect.js/expect.js.d.ts) [expect.js](https://github.com/LearnBoost/expect.js) by [Teppei Sato](https://github.com/teppeis) * [:link:](expectations/expectations.d.ts) [expectations.js](https://github.com/spmason/expectations) by [vvakame](https://github.com/vvakame) @@ -232,8 +233,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](google.analytics/ga.d.ts) [Google Analytics (Classic and Universal)](https://developers.google.com/analytics/devguides/collection/gajs) by [Ronnie Haakon Hegelund](http://ronniehegelund.blogspot.dk), [Pat Kujawa](http://patkujawa.com) * [:link:](gapi/gapi.d.ts) [Google API Client](https://code.google.com/p/google-api-javascript-client) by [Frank M](https://github.com/sgtfrankieboy) * [:link:](google.feeds/google.feed.api.d.ts) [Google Feed Apis](https://developers.google.com/feed) by [RodneyJT](https://github.com/RodneyJT) -* [:link:](googlemaps/google.maps.d.ts) [Google Geolocation](https://developers.google.com/maps) by [Folia A/S](http://www.folia.dk) * [:link:](google.geolocation/google.geolocation.d.ts) [Google Geolocation](https://code.google.com/p/geo-location-javascript) by [Vincent Bortone](https://github.com/vbortone) +* [:link:](googlemaps/google.maps.d.ts) [Google Geolocation](https://developers.google.com/maps) by [Folia A/S](http://www.folia.dk) * [:link:](gapi.pagespeedonline/gapi.pagespeedonline.d.ts) [Google Page Speed Online Api](https://developers.google.com/speed/pagespeed) by [Frank M](https://github.com/sgtfrankieboy) * [:link:](recaptcha/recaptcha.d.ts) [Google Recaptcha](https://www.google.com/recaptcha) by [Brent Jenkins](https://github.com/brentj73) * [:link:](gapi.translate/gapi.translate.d.ts) [Google Translate API](https://developers.google.com/translate) by [Frank M](https://github.com/sgtfrankieboy) @@ -300,6 +301,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jasmine-fixture/jasmine-fixture.d.ts) [Jasmine-fixture](https://github.com/searls/jasmine-fixture) by [Craig Brett](https://github.com/craigbrett17) * [:link:](jasmine-jquery/jasmine-jquery.d.ts) [Jasmine-JQuery](https://github.com/velesin/jasmine-jquery) by [Gregor Stamac](https://github.com/gstamac) * [:link:](jasmine-matchers/jasmine-matchers.d.ts) [jasmine-matchers](https://github.com/uxebu/jasmine-matchers) by [Bart van der Schoor](https://github.com/Bartvds) +* [:link:](java-applet/java-applet.d.ts) [Java Applet](https://www.java.com) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](jdataview/jdataview.d.ts) [jDataView](https://github.com/jDataView/jDataView) by [Ingvar Stepanyan](https://github.com/RReverser) * [:link:](jest/jest.d.ts) [Jest](http://facebook.github.io/jest) by [Asana](https://asana.com) * [:link:](jjv/jjv.d.ts) [JJV](https://github.com/acornejo/jjv) by [Wim Looman](https://github.com/Nemo157) @@ -418,6 +420,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](kolite/kolite.d.ts) [KoLite](https://github.com/CodeSeven/kolite) by [Boris Yankov](https://github.com/borisyankov) * [:link:](kuromoji/kuromoji.d.ts) [kuromoji.js](https://github.com/takuyaa/kuromoji.js) by [MIZUSHIMA Junki](https://github.com/mzsm) * [:link:](ladda/ladda.d.ts) [Ladda](https://github.com/hakimel/Ladda) by [Danil Flores](https://github.com/dflor003), [Michael Lee](https://github.com/leemicw) +* [:link:](later/later.d.ts) [LaterJS](http://bunkat.github.io/later) by [Jason D Dryhurst-Smith](http://jasonds.co.uk) * [:link:](lazy.js/lazy.js.d.ts) [Lazy.js](https://github.com/dtao/lazy.js) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](leaflet/leaflet.d.ts) [Leaflet.js](https://github.com/Leaflet/Leaflet) by [Vladimir Zotov](https://github.com/rgripper) * [:link:](jquery.leanModal/jquery.leanModal.d.ts) [leanModal.js](http://leanmodal.finelysliced.com.au) by [FinelySliced](https://github.com/FinelySliced) @@ -468,6 +471,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](mixpanel/mixpanel.d.ts) [Mixpanel](https://mixpanel.com) by [Knut Eirik Leira Hjelle](https://github.com/hjellek) * [:link:](mixto/mixto.d.ts) [mixto](https://github.com/atom/mixto) by [vvakame](https://github.com/vvakame) * [:link:](mkdirp/mkdirp.d.ts) [mkdirp](http://github.com/substack/node-mkdirp) by [Bart van der Schoor](https://github.com/Bartvds) +* [:link:](mkpath/mkpath.d.ts) [mkpath](https://www.npmjs.com/package/mkpath) by [Jared Klopper](https://github.com/optical) * [:link:](mocha/mocha.d.ts) [mocha](http://mochajs.org) by [Kazi Manzur Rashid](https://github.com/kazimanzurrashid), [otiai10](https://github.com/otiai10), [jt000](https://github.com/jt000) * [:link:](mocha-phantomjs/mocha-phantomjs.d.ts) [mocha-phantomjs](http://metaskills.net/mocha-phantomjs) by [Erik Schierboom](https://github.com/ErikSchierboom) * [:link:](mockery/mockery.d.ts) [mockery](https://github.com/mfncooper/mockery) by [jt000](https://github.com/jt000) @@ -511,6 +515,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](ip/ip.d.ts) [node-ip](https://github.com/indutny/node-ip) by [Peter Harris](https://github.com/codeanimal) * [:link:](multiparty/multiparty.d.ts) [node-multiparty](https://github.com/andrewrk/node-multiparty) by [Ken Fukuyama](https://github.com/kenfdev) * [:link:](mysql/mysql.d.ts) [node-mysql](https://github.com/felixge/node-mysql) by [William Johnston](https://github.com/wjohnsto) +* [:link:](node-persist/node-persist.d.ts) [node-persist](https://github.com/simonlast/node-persist) by [Spencer Williams](http://spencerwi.com) * [:link:](promptly/promptly.d.ts) [node-promptly](https://github.com/IndigoUnited/node-promptly) by [Dan Spencer](https://github.com/danrspencer) * [:link:](radius/radius.d.ts) [node-radius](https://github.com/retailnext/node-radius) by [Peter Harris](https://github.com/codeanimal) * [:link:](node-uuid/node-uuid.d.ts) [node-uuid.js](https://github.com/broofa/node-uuid) by [Jeff May](https://github.com/jeffmay) @@ -524,8 +529,9 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](nodemailer/nodemailer.d.ts) [Nodemailer](https://github.com/andris9/Nodemailer) by [Vincent Bortone](https://github.com/vbortone) * [: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:](notify/notify.d.ts) [Notify.js](https://github.com/jpillora/notifyjs) by [Xiaohan Zhang](https://github.com/hellochar) +* [: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:](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) @@ -586,6 +592,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](raphael/raphael.d.ts) [Raphael](http://raphaeljs.com) by [CheCoxshall](https://github.com/CheCoxshall) * [:link:](ravenjs/ravenjs.d.ts) [Raven.js](https://github.com/getsentry/raven-js) by [Santi Albo](https://github.com/santialbo) * [:link:](react/react.d.ts) [React](http://facebook.github.io/react) by [Asana](https://asana.com) +* [:link:](react-router/react-router.d.ts) [React Router](https://github.com/rackt/react-router) by [Yuichi Murata](https://github.com/mrk21) * [:link:](readdir-stream/readdir-stream.d.ts) [readdir-stream](https://github.com/logicalparadox/readdir-stream) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](redis/redis.d.ts) [redis](https://github.com/mranney/node_redis) by [Carlos Ballesteros Velasco](https://github.com/soywiz), [Peter Harris](https://github.com/CodeAnimal) * [:link:](ref/ref.d.ts) [ref](https://github.com/TooTallNate/ref) by [Paul Loyd](https://github.com/loyd) @@ -619,12 +626,15 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](rx/rx.virtualtime.d.ts) [RxJS-VirtualTime](http://rx.codeplex.com) by [gsino](http://www.codeplex.com/site/users/view/gsino), [Igor Oleinikov](https://github.com/Igorbek) * [:link:](sammyjs/sammyjs.d.ts) [Sammy.js](http://sammyjs.org) by [Boris Yankov](https://github.com/borisyankov), [Oisin Grehan](https://github.com/oising) * [:link:](sanitize-filename/sanitize-filename.d.ts) [sanitize-filename](https://github.com/parshap/node-sanitize-filename) by [Wim Looman](https://github.com/Nemo157) +* [:link:](sanitize-html/sanitize-html.d.ts) [sanitize-html](https://github.com/punkave/sanitize-html) by [Rogier Schouten](https://github.com/rogierschouten) +* [:link:](sax/sax.d.ts) [sax js](https://github.com/isaacs/sax-js) by [Asana](https://asana.com) * [:link:](screenfull/screenfull.d.ts) [screenfull.js](https://github.com/sindresorhus/screenfull.js) by [Ilia Choly](http://github.com/icholy) * [:link:](select2/select2.d.ts) [Select2](http://ivaynberg.github.com/select2) by [Boris Yankov](https://github.com/borisyankov) * [:link:](selectize/selectize.d.ts) [Selectize](https://github.com/brianreavis/selectize.js) by [Adi Dahiya](https://github.com/adidahiya) * [:link:](selenium-webdriver/selenium-webdriver.d.ts) [Selenium WebDriverJS](https://code.google.com/p/selenium) by [Bill Armstrong](https://github.com/BillArmstrong) * [: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:](sharedworker/SharedWorker.d.ts) [SharedWorker](http://www.w3.org/TR/workers) by [Toshiya Nakakura](https://github.com/nakakura) * [:link:](shelljs/shelljs.d.ts) [ShellJS](http://shelljs.org) by [Niklas Mollenhauer](https://github.com/nikeee) * [:link:](should/should.d.ts) [should.js](https://github.com/visionmedia/should.js) by [Alex Varju](https://github.com/varju), [Maxime LUCE](https://github.com/SomaticIT) @@ -658,7 +668,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [: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:](stampit/stampit.d.ts) [stampit](https://github.com/ericelliott/stampit) by [Vasyl Boroviak](https://github.com/koresar) -* [:link:](stats/stats.d.ts) [Stats.js r11](http://github.com/mrdoob/stats.js) by [Gregory Dalton](https://github.com/gregolai) +* [:link:](stats/stats.d.ts) [Stats.js r12](http://github.com/mrdoob/stats.js) by [Gregory Dalton](https://github.com/gregolai) * [:link:](status-bar/status-bar.d.ts) [status-bar](https://github.com/atom/status-bar) by [vvakame](https://github.com/vvakame) * [:link:](storejs/storejs.d.ts) [store.js](https://github.com/marcuswestin/store.js) by [Vincent Bortone](https://github.com/vbortone) * [:link:](stream-to-array/stream-to-array.d.ts) [stream-to-array](https://github.com/stream-utils/stream-to-array) by [Bart van der Schoor](https://github.com/Bartvds) @@ -679,7 +689,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [: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) -* [:link:](tcomb/tcomb.d.ts) [tcomb](https://github.com/npm/tcomb) by [Jed Mao](https://github.com/jedmao) +* [:link:](tcomb/tcomb.d.ts) [tcomb](http://gcanti.github.io/tcomb/guide/index.html) by [Jed Mao](https://github.com/jedmao) * [:link:](tedious/tedious.d.ts) [tedious](https://pekim.github.io/tedious) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](tedious-connection-pool/tedious-connection-pool.d.ts) [tedious-connection-pool](https://github.com/pekim/tedious-connection-pool) by [Cyprien Autexier](https://github.com/sandorfr) * [:link:](teechart/teechart.d.ts) [TeeChart](http://www.steema.com) by [Steema Software](https://steema.com) diff --git a/documentdb/documentdb-tests.ts b/documentdb/documentdb-tests.ts new file mode 100644 index 000000000..13927cd93 --- /dev/null +++ b/documentdb/documentdb-tests.ts @@ -0,0 +1,66 @@ +/// + +import docDB = require('documentdb'); +var docDBClient = new docDB.DocumentClient('host', { masterKey: 'masterKey' }); + +docDBClient.createDatabase({ id: 'foo' }, undefined, (error, result) => { + + if (error) { + throw new Error(error.body); + } + else { + console.log('Created database: ' + result.id); + } +}); + +docDBClient.createCollection('database', { id: 'foo' }, undefined, (error, result) => { + + if (error) { + throw new Error(error.body); + } + else { + console.log('Created collection: ' + result.id); + } +}); + +var procedure: docDB.Procedure = { + id: 'procedure-one', + body: function () { + console.log('foo'); + } +}; + +docDBClient.createStoredProcedure('collection', procedure, undefined, (error, result) => { + + if (error) { + throw new Error(error.body); + } + else { + console.log('Created procedure: ' + result.id); + } +}); + +var document: docDB.NewDocument<{ val: string }> = { + id: '10' +}; + +docDBClient.createDocument('collection', document, undefined, (error, result) => { + + if (error) { + throw new Error(error.body); + } + else { + console.log('Created document: ' + result.id); + } +}); + +docDBClient.executeStoredProcedure('procedure', [10, 'foo'], (error, result) => { + + if (error) { + throw new Error(error.body); + } + else { + console.log('Procedure result: ' + result); + } +}); + diff --git a/documentdb/documentdb.d.ts b/documentdb/documentdb.d.ts new file mode 100644 index 000000000..581543508 --- /dev/null +++ b/documentdb/documentdb.d.ts @@ -0,0 +1,350 @@ +// Type definitions for DocumentDB +// Project: https://github.com/Azure/azure-documentdb-node +// Definitions by: Noel Abrahams +// Definitions: https://github.com/borisyankov/DefinitelyTyped/documentdb + +declare module 'documentdb' { + + /** The feed options and query methods.*/ + interface FeedOptions { + + /** Max number of items to be returned in the enumeration operation. */ + maxItemCount?: number; + + /** Opaque token for continuing the enumeration. */ + continuation?: string; + + /** Token for use with Session consistency. */ + sessionToken?: string; + } + + /** Options that can be specified for a request issued to the DocumentDB servers. */ + interface RequestOptions { + + /** Indicates what is the pre trigger to be invoked before the operation. */ + preTriggerInclude?: string; + + /** Indicates what is the post trigger to be invoked after the operation. */ + postTriggerInclude?: string; + + /** Conditions Associated with the request. */ + accessCondition?: { + + /** Conditional HTTP method header type.*/ + type: string; + + /** Conditional HTTP method header value.*/ + condition: string + }; + + /** Specifies indexing directives (index, do not index ..etc).*/ + indexingDirective?: string; + + /** Consistency level required by the client. */ + consistencyLevel?: string; + + /** Token for use with Session consistency.*/ + sessionToken?: string; + + /** Expiry time (in seconds) for resource token associated with permission (applicable only for requests on permissions).*/ + resourceTokenExpirySeconds?: number; + + /** Disables the automatic id generation. If id is missing in the body and this option is true, an error will be returned. */ + disableAutomaticIdGeneration?: boolean; + } + + /** Represents the error object returned from a failed query. */ + interface QueryError { + + /** The response code corresponding to the error. */ + code: number; + + /** A string representing the error information. */ + body: string; //{ code: string; message: string; }; + } + + /** + * The callback to execute after the request execution. + * @param error - Will contain error information if an error occurs, undefined otherwise. + * @param resource - An object that represents the requested resource (Db, collection, document ... etc) if no error happens. + * @param responseHeaders - An object that contain the response headers. + */ + interface RequestCallback { + (error: QueryError, resource: TResult, responseHeaders: any): void; + } + + /** Represents the result returned from a query. */ + interface QueryIterator { + + toArray(callback: (error: QueryError, result: TResultRow[]) => void): void; + } + + /** Reprents an object with a unique identifier. */ + interface UniqueId { + + /** The user-defined unique identifier for a document or other DocumentDB object (database, collection, procedure...) */ + id: string; + } + + /** Represents the common meta data for all DocumentDB objects. */ + interface AbstractMeta extends UniqueId { + + /** The self link.*/ + _self: string; + + /** The time the object was created.*/ + _ts: string; + + _rid?: string; + _etag?: string; + + _attachments?: string; + } + + /** Represents a custom document for storing in DocumentDB */ + interface NewDocument extends UniqueId { + + /** A custom property for containing the actual JSON object representing the document. + * Define a custom property in order to disambiguate the JSON document from the metadata added by Azure. + * This property is optional and the name is application-specific. + */ + //doc: TContent; + } + + /** Represents a document retrieved from storage. + * This differs from a new document by the properties in AbstractMeta, which are added by the system. + */ + interface RetrievedDocument extends NewDocument, AbstractMeta { + + } + + /** Represents the meta data for a database. */ + interface DatabaseMeta extends AbstractMeta { + } + + /** Represents the meta data for a collection. */ + interface CollectionMeta extends AbstractMeta { + } + + /** Represents the meta data for a stored procedure. */ + interface ProcedureMeta extends AbstractMeta { + body: string; + } + + /** An object that is used for authenticating requests and must contains one of the options. */ + export interface AuthOptions { + + /** The authorization master key to use to create the client. */ + masterKey?: string; + + /** An object that contains resources tokens. Keys for the object are resource Ids and values are the resource tokens.*/ + resourceTokens?: any; + + /** An array of {@link Permission} objects. */ + permissionFeed?: any[]; + } + + /** Represents a DocumentDB stored procecedure. */ + export interface Procedure extends UniqueId { + + /** The function representing the stored procedure. */ + body(...params: any[]): void; + } + + /** Represents DocumentDB collection. */ + export interface Collection extends UniqueId { + + indexingPolicy?: IndexingPolicy; + } + + /** The Indexing Path + *

Indexing paths hints to optimize indexing.
+ * Indexing paths allow tradeoff between indexing storage and query performance + *

+ */ + interface IndexingPath { + + /** The indexing type(range or hash) {@link IndexType}.*/ + IndexType: string; + + /** Path to be indexed.*/ + Path: string; + + /** Precision for this particular Index type for numeric data. */ + NumericPrecision: number; + + /** Precision for this particular Index type for string data. */ + StringPrecision: number; + } + + /** The Indexing Policy represents the indexing policy configuration for a collection. */ + interface IndexingPolicy { + + /** Specifies whether automatic indexing is enabled for a collection. +

In automatic indexing, documents can be explicitly excluded from indexing using {@link RequestOptions}. + In manual indexing, documents can be explicitly included.

*/ + automatic: boolean; + + /** The indexing mode (consistent or lazy) {@link IndexingMode}. */ + indexingMode: string; + + /** An array of {@link IndexingPath} represents The paths to be incuded for indexing. */ + IncludedPath: IndexingPath[]; + + /** An array of strings representing the paths to be excluded from indexing. */ + ExcludedPaths: string[]; + } + + + + /** Provides a client-side logical representation of the Azure DocumentDB database account. This client is used to configure and execute requests against the service. + */ + export class DocumentClient { + + /** + * Constructs a DocumentClient. + * @param urlConnection - The service endpoint to use to create the client. + * @param auth - An object that is used for authenticating requests and must contains one of the options. + * @param [connectionPolicy] - An instance of {@link ConnectionPolicy} class. This parameter is optional and the default connectionPolicy will be used if omitted. + * @param [consistencyLevel] - An optional parameter that represents the consistency level. It can take any value from {@link ConsistencyLevel}. + */ + constructor(urlConnection: string, auth: AuthOptions, connectionPolicy?: any, consistencyLevel?: string); + + /** Send a request for creating a database. + *

+ * A database manages users, permissions and a set of collections.
+ * Each Azure DocumentDB Database Account is able to support multiple independent named databases, with the database being the logical container for data.
+ * Each Database consists of one or more collections, each of which in turn contain one or more documents. Since databases are an an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.
+ *

+ * @param body - A json object that represents The database to be created. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createDatabase(body: UniqueId, options: RequestOptions, callback: RequestCallback): void; + + /** + * Creates a collection. + *

+ * A collection is a named logical container for documents.
+ * A database may contain zero or more named collections and each collection consists of zero or more JSON documents.
+ * Being schema-free, the documents in a collection do not need to share the same structure or fields.
+ * Since collections are application resources, they can be authorized using either the master key or resource keys.
+ *

+ * @param databaseLink - The self-link of the database. + * @param body - Represents the body of the collection. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createCollection(databaseLink: string, body: Collection, options: RequestOptions, callback: RequestCallback): void; + + /** + * Create a StoredProcedure. + *

+ * DocumentDB allows stored procedures to be executed in the storage tier, directly against a document collection. The script
+ * gets executed under ACID transactions on the primary storage partition of the specified collection. For additional details,
+ * refer to the server-side JavaScript API documentation. + *

+ * @param collectionLink - The self-link of the collection. + * @param procedure - Represents the body of the stored procedure. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createStoredProcedure(collectionLink: string, procedure: Procedure, options: RequestOptions, callback: RequestCallback): void; + + /** + * Create a document. + *

+ * There is no set schema for JSON documents. They may contain any number of custom properties as well as an optional list of attachments.
+ * A Document is an application resource and can be authorized using the master key or resource keys + *

+ * @param collectionLink - The self-link of the collection. + * @param document - Represents the body of the document. Can contain any number of user defined properties. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createDocument(collectionSelfLink: string, document: NewDocument, options: RequestOptions, callback: RequestCallback>): void; + + /** + * Execute the StoredProcedure represented by the object. + * @param procedureLink - The self-link of the stored procedure. + * @param [params] - Represents the parameters of the stored procedure. + * @param callback - The callback for the request. + */ + public executeStoredProcedure(procedureLink: string, params: any[], callback: RequestCallback): void; + + /** Lists all databases that satisfy a query. + * @param query - A SQL query string. + * @param [options] - The feed options. + * @returns - An instance of QueryIterator to handle reading feed. + */ + public queryDatabases(query: string): QueryIterator; + + /** + * Query the collections for the database. + * @param databaseLink - The self-link of the database. + * @param query - A SQL query string. + * @param [options] - Represents the feed options. + * @returns - An instance of queryIterator to handle reading feed. + */ + public queryCollections(databaseLink: string, query: string): QueryIterator; + + /** + * Query the storedProcedures for the collection. + * @param collectionLink - The self-link of the collection. + * @param query - A SQL query string. + * @param [options] - Represents the feed options. + * @returns - An instance of queryIterator to handle reading feed. + */ + public queryStoredProcedures(collectionLink: string, query: string): QueryIterator; + + /** + * Query the documents for the collection. + * @param collectionLink - The self-link of the collection. + * @param query - A SQL query string. + * @param [options] - Represents the feed options. + * @returns - An instance of queryIterator to handle reading feed. + */ + public queryDocuments(collectionLink: string, query: string, options?: FeedOptions): QueryIterator>; + + /** + * Delete the document object. + * @param documentLink - The self-link of the document. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public deleteDocument(documentLink: string, options: RequestOptions, callback: RequestCallback): void; + + /** + * Delete the database object. + * @param databaseLink - The self-link of the database. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public deleteDatabase(databaseLink: string, options: RequestOptions, callback: RequestCallback): void; + + /** + * Delete the collection object. + * @param collectionLink - The self-link of the collection. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public deleteCollection(collectionLink: string, options: RequestOptions, callback: RequestCallback): void; + + /** + * Delete the StoredProcedure object. + * @param procedureLink - The self-link of the stored procedure. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public deleteStoredProcedure(procedureLink: string, options: RequestOptions, callback: RequestCallback): void; + + /** + * Replace the StoredProcedure object. + * @param procedureLink - The self-link of the stored procedure. + * @param procedure - Represent the new procedure body. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public replaceStoredProcedure(procedureLink: string, procedure: Procedure, options: RequestOptions, callback: RequestCallback): void; + } +} \ No newline at end of file diff --git a/java-applet/java-applet-tests.ts b/java-applet/java-applet-tests.ts index 670527999..cf652a443 100644 --- a/java-applet/java-applet-tests.ts +++ b/java-applet/java-applet-tests.ts @@ -1,22 +1,29 @@ /// /** - * @summary Test for the applet status. + * @summary Test for the typage. + */ +function testTypage() { + var applet: HTMLAppletElement = document.getElementById('applet'); + var javaApplet: JavaApplet = applet; +} + +/** + * @summary Test for the java applet status. */ function testStatus() { - var java: Java = { - status: AppletStatus.Loading - }; + var applet: JavaApplet = document.getElementById('applet'); + var status: number = applet.status; } /** * @summary Test for the handlers. */ function testHandlers() { + var applet: JavaApplet = document.getElementById('applet'); + var handler: Function = () => {}; - var java: Java = { - onError: handler, - onLoad: handler, - onStop: handler - }; -} + applet.onError = handler; + applet.onLoad = handler; + applet.onStop = handler; +} \ No newline at end of file diff --git a/java-applet/java-applet.d.ts b/java-applet/java-applet.d.ts index 0102b3b75..982e71a1c 100644 --- a/java-applet/java-applet.d.ts +++ b/java-applet/java-applet.d.ts @@ -4,10 +4,11 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /** - * @summary Applet Status. - * {@link http://docs.oracle.com/javase/8/docs/technotes/guides/deploy/applet_dev_guide.html#JSDPG719|Applet Status And Event Handlers} + * @summary Java applet Status. More details: {@link http://docs.oracle.com/javase/8/docs/technotes/guides/deploy/applet_dev_guide.html#JSDPG719|Applet Status And Event Handlers} + * @enum {number} + * @readonly */ -declare enum AppletStatus { +declare enum JavaAppletStatus { /** * @summary Applet is loading. */ @@ -25,28 +26,32 @@ declare enum AppletStatus { } /** - * @summary Interface for Java object. + * @summary Interface for Java applet object. * @author Cyril Schumacher * @version 1.0 */ -interface Java { +interface JavaApplet extends HTMLAppletElement { /** - * Handler if the applet status is ERROR. An error has occurred while loading the applet. + * @summary Handler if the applet status is {@link JavaAppletStatus#Error}. An error has occurred while loading the applet. + * @type {Function} */ onError?: Function; /** - * Handler if the applet status is READY. Applet has finished loading and is ready to receive JavaScript calls. + * @summary Handler if the applet status is {@link JavaAppletStatus#Ready}. Applet has finished loading and is ready to receive JavaScript calls. + * @type {Function} */ onLoad?: Function; /** - * Handler if the applet has stopped. + * @summary Handler if the applet has stopped. + * @type {Function} */ onStop?: Function; /** - * @summary Applet Status. + * @summary Java applet Status. + * @type {JavaAppletStatus} */ - status?: AppletStatus; + status?: JavaAppletStatus; } diff --git a/jbinary/jbinary-tests.ts b/jbinary/jbinary-tests.ts new file mode 100644 index 000000000..c1e286fce --- /dev/null +++ b/jbinary/jbinary-tests.ts @@ -0,0 +1,16 @@ +/// + +var originalData = [0x05, 0x03, 0x7F, 0x1E]; +var b1 = new jBinary(originalData); +console.log(b1.readAll()); +console.log(b1.read('int8')); + +b1.seek(4); +console.log(b1.read('int8')); + +console.log(b1.tell()); + +b1.write('int8', 0x9A, 2); +b1.writeAll(originalData); + +console.log(b1.slice(0, 2)); diff --git a/jbinary/jbinary.d.ts b/jbinary/jbinary.d.ts new file mode 100644 index 000000000..f9a2f2aaa --- /dev/null +++ b/jbinary/jbinary.d.ts @@ -0,0 +1,32 @@ +// Type definitions for jBinary +// Project: https://github.com/jDataView/jBinary +// Definitions by: Tim Bureck +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Additional notes: +// Method stubs and types are taken from the official jBinary documentation, which can be found here: +// https://github.com/jDataView/jBinary/wiki/jBinary-Constructor +// https://github.com/jDataView/jBinary/wiki/jBinary-Methods + +/// + +declare class jBinary +{ + + constructor(data:Array); + constructor(data:jDataView, typeSet:Object); + constructor(bufferSize:number, typeSet:Object); + + read(type:string, offset?:number):any; + readAll():any; + + write(type:string, data:any, offset?:number):number; + writeAll(data:any):number; + + tell():number; + seek(position:number, callback?: (prop:jBinary, data:any) => any):number; + skip(count:number, callback?: (prop:jBinary, data:any) => any):number; + + slice(start:number, end:number, forceCopy?:boolean):jBinary; + as(typeSet:Object, modifyOriginal?:boolean):jBinary; +} \ No newline at end of file diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 6f9ff2076..9e7015659 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -616,7 +616,7 @@ interface KnockoutComponentTemplate { } interface KnockoutComponentInfo { - element: any; + element: Node; } /* end register overloads */ interface KnockoutComponentDefinition { diff --git a/later/later-test.ts b/later/later-test.ts new file mode 100644 index 000000000..2d336d1b3 --- /dev/null +++ b/later/later-test.ts @@ -0,0 +1,631 @@ +/// + + +module LaterTest_DefineSchedule { + + // define a new schedule + var textSched = later.parse.text('at 10:15am every weekday'); + var cronSched = later.parse.cron('0 0/5 14,18 * * ?'); + var recurSched = later.parse.recur().last().dayOfMonth(); + var manualSched = { schedules: [ { M: [ 3 ], D: [ 21 ] } ] }; + + // this schedule will fire on the closest weekday to the 15th + // every month at 2:00 am except in March + var complexSched = later.parse.recur() + .on(15).dayOfMonth().onWeekday().on(2).hour() + .and() + .on(14).dayOfMonth().on(6).dayOfWeek().on(2).hour() + .and() + .on(16).dayOfMonth().on(2).dayOfWeek().on(2).hour() + .except() + .on(3).month(); +} + +module LaterTest_ConfigureTimezone { + + // set later to use UTC (the default) + later.date.UTC(); + + // set later to use local time + later.date.localTime(); +} + +module LaterTest_TimePeriods { + export function second() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.second.name; + // 'second' + + later.second.range; + // 1 + + later.second.val(d); + // 5 + + later.second.isValid(d, 10); + // false + + later.second.extent(); + // [0, 59] + + later.second.start(d); + // 'Fri, 22 Mar 2013 10:02:05 GMT' + + later.second.end(d); + // 'Fri, 22 Mar 2013 10:02:05 GMT' + + later.second.next(d, 27); + // 'Fri, 22 Mar 2013 10:02:27 GMT' + + later.second.prev(d, 27); + // 'Fri, 22 Mar 2013 10:01:27 GMT' + } + + export function minute() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.minute.name; + // 'minute' + + later.minute.range; + // 60 + + later.minute.val(d); + // 2 + + later.minute.isValid(d, 2); + // true + + later.minute.extent(); + // [0, 59] + + later.minute.start(d); + // 'Fri, 22 Mar 2013 10:02:00 GMT' + + later.minute.end(d); + // 'Fri, 22 Mar 2013 10:02:59 GMT' + + later.minute.next(d, 27); + // 'Fri, 22 Mar 2013 10:27:00 GMT' + + later.minute.prev(d, 27); + // 'Fri, 22 Mar 2013 09:27:59 GMT' + } + + export function hour() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.hour.name; + // 'hour' + + later.hour.range; + // 3600 + + later.hour.val(d); + // 10 + + later.hour.isValid(d, 2); + // false + + later.hour.extent(); + // [0, 23] + + later.hour.start(d); + // 'Fri, 22 Mar 2013 10:00:00 GMT' + + later.hour.end(d); + // 'Fri, 22 Mar 2013 10:59:59 GMT' + + later.hour.next(d, 5); + // 'Sat, 23 Mar 2013 05:00:00 GMT' + + later.hour.prev(d, 21); + // 'Thu, 21 Mar 2013 21:59:59 GMT' + } + + export function time() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.time.name; + // 'time' + + later.time.range; + // 1 + + later.time.val(d); + // 36125 + + later.time.isValid(d, 36125); + // true + + later.time.extent(); + // [0, 86399] + + later.time.start(d); + // 'Fri, 22 Mar 2013 00:00:00 GMT' + + later.time.end(d); + // 'Fri, 22 Mar 2013 23:59:59 GMT' + + later.time.next(d, 60); + // 'Sat, 23 Mar 2013 00:01:00 GMT' + + later.time.prev(d, 60); + // 'Fri, 22 Mar 2013 00:01:00 GMT' + } + + export function day() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.day.name; + // 'day' + + later.day.range; + // 86400 + + later.day.val(d); + // 22 + + later.day.isValid(d, 3); + // false + + later.day.extent(d); + // [1, 31] + + later.day.start(d); + // 'Fri, 22 Mar 2013 00:00:00 GMT' + + later.day.end(d); + // 'Fri, 22 Mar 2013 23:59:59 GMT' + + later.day.next(d, 11); + // 'Thu, 11 Apr 2013 00:00:00 GMT' + + later.day.prev(d, 2); + // 'Sat, 02 Mar 2013 23:59:59 GMT' + } + + export function day_of_week() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.dayOfWeek.name; + // 'day of week' + + later.dayOfWeek.range; + // 86400 + + later.dayOfWeek.val(d); + // 6 + + later.dayOfWeek.isValid(d, 3); + // false + + later.dayOfWeek.extent(); + // [1, 7] + + later.dayOfWeek.start(d); + // 'Fri, 22 Mar 2013 00:00:00 GMT' + + later.dayOfWeek.end(d); + // 'Fri, 22 Mar 2013 23:59:59 GMT' + + later.dayOfWeek.next(d, 1); + // 'Sun, 24 Mar 2013 00:00:00 GMT' + + later.dayOfWeek.prev(d, 5); + // 'Thu, 21 Mar 2013 23:59:59 GMT' + } + + export function day_of_week_count() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.dayOfWeekCount.name; + // 'day of week count' + + later.dayOfWeekCount.range; + // 604800 + + later.dayOfWeekCount.val(d); + // 4 + + later.dayOfWeekCount.isValid(d, 4); + // true + + later.dayOfWeekCount.extent(d); + // [1, 5] + + later.dayOfWeekCount.start(d); + // 'Fri, 22 Mar 2013 00:00:00 GMT' + + later.dayOfWeekCount.end(d); + // 'Thu, 28 Mar 2013 23:59:59 GMT' + + // zero is special cased and means the last instance of + // a day of the week in the month, instead of meaning the + // first day of the week with the highest instance count + // which would have been Mar 29 with value 5. + later.dayOfWeekCount.next(d, 0); + // 'Mon, 25 Mar 2013 00:00:00 GMT' + + later.dayOfWeekCount.prev(d, 2); + // 'Thu, 14 Mar 2013 23:59:59 GMT' + } + + export function day_of_year() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.dayOfYear.name; + // 'day of year' + + later.dayOfYear.range; + // 86400 + + later.dayOfYear.val(d); + // 81 + + later.dayOfYear.isValid(d, 4); + // false + + later.dayOfYear.extent(d); + // [1, 365] + + later.dayOfYear.start(d); + // 'Fri, 22 Mar 2013 00:00:00 GMT' + + later.dayOfYear.end(d); + // 'Fri, 22 Mar 2013 23:59:59 GMT' + + later.dayOfYear.next(d, 256); + // 'Fri, 13 Sep 2013 00:00:00 GMT' + + later.dayOfYear.prev(d, 44); + // 'Wed, 13 Feb 2013 23:59:59 GMT' + } + + export function week_of_month() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.weekOfMonth.name; + // 'week of month' + + later.weekOfMonth.range; + // 604800 + + later.weekOfMonth.val(d); + // 4 + + later.weekOfMonth.isValid(d, 4); + // true + + later.weekOfMonth.extent(d); + // [1, 6] + + later.weekOfMonth.start(d); + // 'Sun, 17 Mar 2013 00:00:00 GMT' + + later.weekOfMonth.end(d); + // 'Sat, 23 Mar 2013 23:59:59 GMT' + + later.weekOfMonth.next(d, 1); + // 'Mon, 01 Apr 2013 00:00:00 GMT' + + later.weekOfMonth.prev(d, 2); + // 'Sat, 09 Mar 2013 23:59:59 GMT' + } + + export function week_of_year() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.weekOfYear.name; + // 'week of year' + + later.weekOfYear.range; + // 604800 + + later.weekOfYear.val(d); + // 12 + + later.weekOfYear.isValid(d, 21); + // false + + later.weekOfYear.extent(d); + // [1, 52] + + later.weekOfYear.start(d); + // 'Mon, 18 Mar 2013 00:00:00 GMT' + + later.weekOfYear.end(d); + // 'Sun, 24 Mar 2013 23:59:59 GMT' + + later.weekOfYear.next(d, 47); + // 'Mon, 18 Nov 2013 00:00:00 GMT' + + later.weekOfYear.prev(d, 52); + // 'Sun, 30 Dec 2012 23:59:59 GMT' + } + + export function month() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.month.name; + // 'month' + + later.month.range; + // 2629740 + + later.month.val(d); + // 3 + + later.month.isValid(d, 3); + // true + + later.month.extent(); + // [1, 12] + + later.month.start(d); + // 'Fri, 01 Mar 2013 00:00:00 GMT' + + later.month.end(d); + // 'Sun, 31 Mar 2013 23:59:59 GMT' + + later.month.next(d, 11); + // 'Fri, 01 Nov 2013 00:00:00 GMT' + + later.month.prev(d, 2); + // 'Thu, 28 Feb 2013 23:59:59 GMT' + } + + export function year() { + var d = new Date('2013-03-22T10:02:05Z'); + + later.year.name; + // 'year' + + later.year.range; + // 31556900 + + later.year.val(d); + // 2013 + + later.year.isValid(d, 2013); + // true + + later.year.extent(); + // [1970, 2099] + + later.year.start(d); + // 'Tue, 01 Jan 2013 00:00:00 GMT' + + later.year.end(d); + // 'Tue, 31 Dec 2013 23:59:59 GMT' + + later.year.next(d, 2014); + // 'Wed, 01 Jan 2014 00:00:00 GMT' + + later.year.prev(d, 2012); + // 'Mon, 31 Dec 2012 23:59:59 GMT' + } + + export interface IPartOfDayLater extends Later.IStatic { + partOfDay: Later.ITimePeriod; + } + + export function custom() { + + var customLater = later; + + customLater.partOfDay = { + + name: 'part of day', + + range: later.hour.range * 6, + + val: function(d: Date): number { + return later.hour.val(d) < 12 + ? 0 + : later.hour.val(d) < 18 + ? 1 + : 2; + }, + + isValid: function(d: Date, val: any) { + return customLater.partOfDay.val(d) === val; + }, + + extent: function(date?: Date) { + return [0, 2]; + }, + + start: function(date: Date) { + var hour = customLater.partOfDay.val(date) === 0 + ? 0 + : customLater.partOfDay.val(date) === 1 + ? 12 + : 18; + + return later.date.next( + later.year.val(date), + later.month.val(date), + later.day.val(date), + hour + ); + }, + + end: function(date: Date) { + var hour = customLater.partOfDay.val(date) === 0 + ? 11 + : customLater.partOfDay.val(date) === 1 + ? 5 + : 23; + + return later.date.prev( + later.year.val(date), + later.month.val(date), + later.day.val(date), + hour + ); + }, + + next: function(date: Date, val: any) { + var hour = val === 0 + ? 0 + : val === 1 + ? 12 + : 18; + + return later.date.next( + later.year.val(date), + later.month.val(date), + // increment the day if we already passed the desired time period + later.day.val(date) + (hour < later.hour.val(date) ? 1 : 0), + hour + ); + }, + + prev: function(date: Date, val: any) { + var hour = val === 0 + ? 11 + : val === 1 + ? 5 + : 23; + + return later.date.prev( + later.year.val(date), + later.month.val(date), + // decrement the day if we already passed the desired time period + later.day.val(date) + (hour > later.hour.val(date) ? -1 : 0), + hour + ); + } + }; + } +} + +module LaterTest_GenerateRecurences { + + export function on_method() { + // fires on the 2nd minute every hour + later.parse.recur().on(2).minute(); + + // fires every day at 8am and 8pm + later.parse.recur().on(8, 20).hour(); + + // fires every day at 8am + later.parse.recur().on('08:00:00').time(); + } + + export function first_method() { + // fires on the 0th minute of every hour + later.parse.recur().first().minute(); + } + + export function last_method() { + // fires on the last day of every month at 5am + later.parse.recur().on(5).hour().last().dayOfMonth(); + } + + export function onWeekend_method() { + // fires on the 5th minute of every hour during Sat and Sun + later.parse.recur().on(5).minute().onWeekend(); + } + + export function onWeekday_method() { + // fires on the 5th minute of every hour during Mon,Tues,Wed,Thur,Fri + later.parse.recur().on(5).minute().onWeekday(); + } + + export function every_method() { + // fires on the 0th, 10th, 20th, 30th, 40th, and 50th min of every hour + later.parse.recur().every(10).minute(); + + // fires on first second of Jan, Apr, July, Oct + later.parse.recur().every(3).month(); + } + + export function after_method() { + // fires on the 55th, 56th, 57th, 58th, and 59th minute + later.parse.recur().after(55).minute(); + + // fires at 12 noon and 6pm + later.parse.recur().every(6).hour().after('09:00').time(); + } + + export function before_method() { + // fires on the first second of January and February + later.parse.recur().before(3).month(); + + // fires at 6am every day + later.parse.recur().every(6).hour().before('09:00').time(); + + // fires between 9am and 6pm every day + later.parse.recur().after('09:00').time().before('18:00').time(); + later.parse.recur().after(9).hour().before(18).hour(); + } + + export function startingOn_method() { + // fires on the 10th, 25th, 40th, and 55th minute of every hour + later.parse.recur().every(15).minute().startingOn(10); + } + + export function between_method() { + // fires on the 10th, 25th, 40th minute of every hour + later.parse.recur().every(15).minute().between(10, 40); + } + + export function and_method() { + // fires every 2 hours on the first day of every month + // and 8:00am and 8:00pm on the last day of every month + var sched = later.parse.recur() + .every(2).hour().first().dayOfMonth() + .and() + .on(8, 20).hour().last().dayOfMonth() + } + + export function except_method() { + // fires every minute of every hour except on multiples of 2 and 3 + var sched = later.parse.recur() + .every().minute() + .except() + .every(2).minute().between(2, 59) + .and() + .every(3).minute().between(3, 59); + } + +} + +module LaterTest_CalculateOccurences { + + // Initialise next variable. + var next: Date[] = []; + + // calculate the next 10 occurrences of a recur schedule + var recurSched = later.parse.recur().last().dayOfMonth(); + + next = later.schedule(recurSched).next(10); + + // calculate the previous occurrence starting from March 21, 2013 + var cronSched = later.parse.cron('0 0/5 14,18 * * ?'); + + next = later.schedule(cronSched).prev(1, new Date(2013, 2, 21)); +} + +module LaterTest_ExecuteCodeUsingSchedule { + + // will fire every 5 minutes + var textSched = later.parse.text('every 5 min'); + + // execute logTime one time on the next occurrence of the text schedule + var timer = later.setTimeout(logTime, textSched); + + // execute logTime for each successive occurrence of the text schedule + var timer2 = later.setInterval(logTime, textSched); + + // function to execute + function logTime() { + console.log(new Date()); + } + + // clear the interval timer when you are done + timer2.clear(); +} \ No newline at end of file diff --git a/later/later.d.ts b/later/later.d.ts new file mode 100644 index 000000000..780de6398 --- /dev/null +++ b/later/later.d.ts @@ -0,0 +1,673 @@ +// Type definitions for LaterJS +// Project: http://bunkat.github.io/later/ +// Definitions by: Jason D Dryhurst-Smith +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Later { + + export interface IScheduleData { + + /** + * A list of recurrence information as a composite schedule. + */ + schedules: IRecurrence[]; + + /** + * A list of exceptions to the composite recurrence information. + */ + exceptions: IRecurrence[]; + + /** + * A code to identify any errors in the composite schedule and exceptions. + * The number tells you the position of the error within the schedule. + */ + error: number; + } + + export interface IRecurrence { + + /** Time in seconds from midnight. + */ + t?: number[]; + /** Seconds in minute. + */ + s?: number[]; + /** Minutes in hour. + */ + m?: number[]; + /** Hour in day. + */ + h?: number[]; + /** Day of the month. + */ + D?: number[]; + /** Day in week. + */ + dw?: number[]; + /** Nth day of the week in month. + */ + dc?: number[]; + /** Day in year. + */ + dy?: number[]; + /** Week in month. + */ + wm?: number[]; + /** ISO week in year. + */ + wy?: number[]; + /** Month in year. + */ + M?: number[]; + /** Year. + */ + Y?: number[]; + + /** After modifiers. + */ + t_a?: number[]; + /** After modifiers. + */ + s_a?: number[]; + /** After modifiers. + */ + m_a?: number[]; + /** After modifiers. + */ + h_a?: number[]; + /** After modifiers. + */ + D_a?: number[]; + /** After modifiers. + */ + dw_a?: number[]; + /** After modifiers. + */ + dc_a?: number[]; + /** After modifiers. + */ + dy_a?: number[]; + /** After modifiers. + */ + wm_a?: number[]; + /** After modifiers. + */ + wy_a?: number[]; + /** After modifiers. + */ + M_a?: number[]; + /** After modifiers. + */ + Y_a?: number[]; + + /** Before modifiers. + */ + t_b?: number[]; + /** Before modifiers. + */ + s_b?: number[]; + /** Before modifiers. + */ + m_b?: number[]; + /** Before modifiers. + */ + h_b?: number[]; + /** Before modifiers. + */ + D_b?: number[]; + /** Before modifiers. + */ + dw_b?: number[]; + /** Before modifiers. + */ + dc_b?: number[]; + /** Before modifiers. + */ + dy_b?: number[]; + /** Before modifiers. + */ + wm_b?: number[]; + /** Before modifiers. + */ + wy_b?: number[]; + /** Before modifiers. + */ + M_b?: number[]; + /** Before modifiers. + */ + Y_b?: number[]; + + /* + * Custom Time Periods and Modifiers + * For acces to custom time periods created as extension to the later static type + * and modifiers created on the later modifier static type. + */ + [ timeperiodAndModifierName: string ]: number[]; + } + + export interface IParseStatic { + + /** + * Create a recurrence builder for building schedule data. + */ + recur(): IRecurrenceBuilder; + + /** + * Create schedule data by parsing a cron string + * + * @param {string} [input] - A string value to parse. + */ + cron(input?: string): IScheduleData; + + /** + * Create schedule data by paring a human readable string. + * + * @param {string} [input] - A string value to parse. + */ + text(input?: string): IScheduleData; + } + + export interface ITimer { + + /** + * Clear the timer and end execution. + */ + clear(): void; + } + + export interface ISchedule { + + /** + * Finds the next valid instance or instances of the current schedule, + * optionally between a specified start and end date. Start date is + * Date.now() by default, end date is unspecified. Start date must be + * smaller than end date. + * + * @param {number} numberOfInst: The number of instances to return + * @param {Date} dateFrom: The earliest a valid instance can occur + * @param {Date} dateTo: The latest a valid instance can occur + */ + next(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[]; + + /** + * Finds the next valid range or ranges of the current schedule, + * optionally between a specified start and end date. Start date is + * Date.now() by default, end date is unspecified. Start date must be + * greater than end date. + * + * @param {number} numberOfInst: The number of ranges to return + * @param {Date} dateFrom: The earliest a valid range can occur + * @param {Date} dateTo: The latest a valid range can occur + */ + nextRange(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[]; + + /** + * Finds the previous valid instance or instances of the current schedule, + * optionally between a specified start and end date. Start date is + * Date.now() by default, end date is unspecified. Start date must be + * greater than end date. + * + * @param {number} numberOfInst: The number of instances to return + * @param {Date} dateFrom: The earliest a valid instance can occur + * @param {Date} dateTo: The latest a valid instance can occur + */ + prev(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[]; + + /** + * Finds the previous valid range or ranges of the current schedule, + * optionally between a specified start and end date. Start date is + * Date.now() by default, end date is unspecified. Start date must be + * greater than end date. + * + * @param {number} numberOfInst: The number of ranges to return + * @param {Date} dateFrom: The earliest a valid range can occur + * @param {Date} dateTo: The latest a valid range can occur + */ + prevRange(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[]; + } + + export interface IRecurrenceBuilder extends IScheduleData { + + /** a time period + */ + second(): IRecurrenceBuilder; + /** a time period + */ + minute(): IRecurrenceBuilder; + /** a time period + */ + hour(): IRecurrenceBuilder; + /** a time period + */ + time(): IRecurrenceBuilder; + /** a time period + */ + dayOfWeek(): IRecurrenceBuilder; + /** a time period + */ + dayOfWeekCount(): IRecurrenceBuilder; + /** a time period + */ + dayOfMonth(): IRecurrenceBuilder; + /** a time period + */ + dayOfYear(): IRecurrenceBuilder; + /** a time period + */ + weekOfMonth(): IRecurrenceBuilder; + /** a time period + */ + weekOfYear(): IRecurrenceBuilder; + /** a time period + */ + month(): IRecurrenceBuilder; + /** a time period + */ + year(): IRecurrenceBuilder; + + /** a time period + */ + fullDate(): IRecurrenceBuilder; + + /** + * Specifies one or more specific vals of a time period information provider. + * When used to specify a time, a string indicating the 24-hour time may be used. + * + * @param {number[]} values - A list of values. + */ + on(...values: number[]): IRecurrenceBuilder; + /** + * Specifies one or more specific vals of a time period information provider. + * When used to specify a time, a string indicating the 24-hour time may be used. + * + * @param {string} value - A string representing your value. + */ + on(value: string): IRecurrenceBuilder; + /** + * Specifies one or more specific vals of a time period information provider. + * When used to specify a time, a string indicating the 24-hour time may be used. + * + * @param {Date} date - A Date representing your value. + */ + on(date: Date): IRecurrenceBuilder; + + /** + * Preceed a time period. + * + * @param {number} [value] - A number representing your value. + */ + every(value?: number): IRecurrenceBuilder; + /** + * Preceed a time period. + * + * @param {string} [value] - A string representing your value. + */ + every(value?: string): IRecurrenceBuilder; + + /** + * Preceed a time period. + * + * @param {number} start - A number representing your start value. + * @param {number} end - A number representing your end value. + */ + between(start: number, end: number): IRecurrenceBuilder; + /** + * Preceed a time period. + * + * @param {string} start - A string representing your start value. + * @param {string} end - A string representing your end value. + */ + between(start: string, end: string): IRecurrenceBuilder; + + /** + * After a time period. + * + * @param {number} value - A number representing your value. + */ + after(value: number): IRecurrenceBuilder; + /** + * After a time period. + * + * @param {string} value - A string representing your value. + */ + after(value: string): IRecurrenceBuilder; + + /** + * After a time period. + * + * @param {number} value - A number representing your value. + */ + before(value: number): IRecurrenceBuilder; + /** + * After a time period. + * + * @param {string} value - A string representing your value. + */ + before(value: string): IRecurrenceBuilder; + + /** + * After a time period. + * + * @param {number} value - A number representing your value. + */ + startingOn(value: number): IRecurrenceBuilder; + /** + * After a time period. + * + * @param {string} value - A string representing your value. + */ + startingOn(value: string): IRecurrenceBuilder; + + /** + * Equivalent to .on(min) + */ + first(): IRecurrenceBuilder; + + /** + * Equivalent to .on(max) + */ + last(): IRecurrenceBuilder; + + /** + * Equivalent to .on(1,7).dayOfWeek() + */ + onWeekend(): IRecurrenceBuilder; + + /** + * Equivalent to .on(2,3,4,5,6).dayOfWeek() + */ + onWeekday(): IRecurrenceBuilder; + + /** + * Add a new schedule value to schedules, composite schedule. + */ + and(): IRecurrenceBuilder; + + /** + * Add exceptions. + */ + except(): IRecurrenceBuilder; + + /** + * Custom Timeperiod Recurrences. + * Using a key as defined by the custom period in any extension to Later.IStatic. + */ + customPeriod(key: string): IRecurrenceBuilder; + + /** + * Customise Recurrences. + * Using a key as defined by the custom modifier in any extension to Later.IModifierStatic. + */ + customModifier(key: string, values: number): IRecurrenceBuilder; + } + + export interface IDateProvider { + + /** + * Set later to use UTC time. + */ + UTC(): void; + + /** + * Set later to use local time. + */ + localTime(): void; + + /** + * Builds and returns a new Date using the specified values. Date + * returned is either using Local time or UTC based on isLocal. + * + * @param {number} [Y]: Four digit year + * @param {number} [M]: Month between 1 and 12, defaults to 1 + * @param {number} [D]: Date between 1 and 31, defaults to 1 + * @param {number} [h]: Hour between 0 and 23, defaults to 0 + * @param {number} [m]: Minute between 0 and 59, defaults to 0 + * @param {number} [s]: Second between 0 and 59, defaults to 0 + */ + next(Y?: number, M?: number, D?: number, h?: number, m?: number, s?: number): Date; + + /** + * Builds and returns a new Date using the specified values. Date + * returned is either using Local time or UTC based on isLocal. + * + * @param {number} [Y]: Four digit year + * @param {number} [M]: Month between 0 and 11, defaults to 11 + * @param {number} [D]: Date between 1 and 31, defaults to last day of month + * @param {number} [h]: Hour between 0 and 23, defaults to 23 + * @param {number} [m]: Minute between 0 and 59, defaults to 59 + * @param {number} [s]: Second between 0 and 59, defaults to 59 + */ + prev(Y?: number, M?: number, D?: number, h?: number, m?: number, s?: number): Date; + + /** + * Determines if a value will cause a particular constraint to rollover to the + * next largest time period. Used primarily when a constraint has a + * variable extent. + * + * @param {Date} d: Date + * @param {number} val: Value + * @param {IModifier} constraint: A modifier + * @param {ITimePeriod} period: A time period + */ + nextRollover(d: Date, val: number, constraint: IModifier, period: ITimePeriod): Date; + + /** + * Determines if a value will cause a particular constraint to rollover to the + * previous largest time period. Used primarily when a constraint has a + * variable extent. + * + * @param {Date} d: Date + * @param {number} val: Value + * @param {IModifier} constraint: A modifier + * @param {ITimePeriod} period: A time period + */ + prevRollover(d: Date, val: number, constraint: IModifier, period: ITimePeriod): Date; + } + + export interface ITimePeriod { + + /** + * The name of the time period information provider. + */ + name: string; + + /** + * The rough number of seconds that are covered when moving from one instance of this time period to the next instance. + */ + range: number; + + /** + * The value of this time period for the date specified. + * + * @param {Date} date - The given date. + */ + val(date: Date): number; + + /** + * True if the specified value is valid for the specified date, false otherwise. + * + * @param {Date} date - The given date. + * @param {any} value - The value to test for the date. + */ + isValid(date: Date, value: any): boolean; + + /** + * The minimum and maximum valid values for the time period for the specified date. + * If the minimum value is not 0, 0 can be specified in schedules to indicate the maximum value. + * This makes working with non - constant extents(like days in a month) easier. + * + * @param {Date} [date] - The given date. + */ + extent(date?: Date): number[]; + + /** + * The first second in which the value is the same as the value of the specified date. + * For example, the start of an hour would be the hour with 0 minutes and 0 seconds. + * + * @param {Date} date - The given date. + */ + start(date: Date): Date; + + /** + * The last second in which the value is the same as the value of the specified date. + * For example, the end of an hour would be the hour with 59 minutes and 59 seconds. + * + * @param {Date} date - The given date. + */ + end(date: Date): Date; + + /** + * Returns the next date where the value is the value specified. + * Sets the value to 1 if value specified is greater than the max allowed value. + * + * @param {Date} date - The given date. + * @param {any} value - The value to test for the date. + */ + next(date: Date, value: any): Date; + + /** + * Returns the previous date where the value is the value specified. + * Sets the value to the max allowed value if the value specified is greater than the max allowed value. + * + * @param {Date} date - The given date. + * @param {any} value - The value to test for the date. + */ + prev(date: Date, value: any): Date; + } + + export interface IModifier extends ITimePeriod { + /** + * Creates a new modified constraint. + * + * @param {ITimePeriod} constraint: The constraint to be modified + * @param {number} value: The starting value of the after constraint + */ + (constraint: ITimePeriod, value: number): ITimePeriod; + } + + export interface IModifierStatic { + + /** + * After Modifier + */ + after: IModifier; + + /** + * Before Modifier + */ + before: IModifier; + } + + export interface IStatic { + + /** + * Schedule + * Generates instances from schedule data. + */ + schedule(input: any): ISchedule; + + /** + * Parse + * For generating schedule data. + */ + parse: IParseStatic; + + /** Date Provider + */ + date: IDateProvider; + + /** + * Set timeout on window using given recurrence next. + * + * @param {function} callback - A callback called after first instance of recurrence pattern. + * @param {Later.IReccurence} - A recurrence instance. + */ + setTimeout(callback: () => void, time: IScheduleData): ITimer; + /** + * Set interval on window using given recurrence + * + * @param {function} callback - A callback called after each instance of recurrence pattern. + * @param {Later.IReccurence} - A recurrence instance. + */ + setInterval(callback: () => void, time: IScheduleData): ITimer; + + /** + * time period information provider. + */ + time: ITimePeriod; + /** + * Second time period information provider. + */ + second: ITimePeriod; + /** + * Minute time period information provider. + */ + minute: ITimePeriod; + /** + * Hour time period information provider. + */ + hour: ITimePeriod; + /** + * Day time period information provider. + */ + day: ITimePeriod; + /** + * Day of week time period information provider. + */ + dayOfWeek: ITimePeriod; + /** + * Day of week in month time period information provider. + */ + dayOfWeekCount: ITimePeriod; + /** + * Day in year time period information provider. + */ + dayOfYear: ITimePeriod; + /** + * Week of mobth time period information provider. + */ + weekOfMonth: ITimePeriod; + /** + * Week of yearfrom ISO 8601 time period information provider. + */ + weekOfYear: ITimePeriod; + /** + * Month time period information provider. + */ + month: ITimePeriod; + /** + * Year time period information provider. + */ + year: ITimePeriod; + + /** + * Later Modifiers: + * + * This type can be easily extended to include any custom IModifiers that you desire. + * These can then be used to create schedules of your own custom type. + * + * interface IGandalfsLaterModifier extends Later.IModifierStatic { + * duringTheThirdAge: IModifier + * } + * + * Be sure to use this interface when dealing with Later.modifier + */ + modifier: IModifierStatic + } +} + +/** + * Later Module: + * + * Easily define complex schedules then quickly calculate future or previous schedule occurrences. + * + * This type can be easily extended to include any custom ITimePeriods that you desire. + * These can then be used to create schedules of your own custom type. + * + * interface IGandalfsLater extends Later.IStatic { + * agesOfMiddleEarth: ITimePeriod + * } + * + * Be sure to use this interface when dealing with Later. + */ +declare var later: Later.IStatic; \ No newline at end of file diff --git a/lazy.js/lazy.js-tests.ts b/lazy.js/lazy.js-tests.ts index f719a90a9..cab0787c3 100644 --- a/lazy.js/lazy.js-tests.ts +++ b/lazy.js/lazy.js-tests.ts @@ -156,7 +156,7 @@ obj = fooSequence.toObject(); // ArrayLikeSequence -fooArraySeq = fooArraySeq.concat(); +fooArraySeq = fooArraySeq.concat(fooArr); fooArraySeq = fooArraySeq.first(); fooArraySeq = fooArraySeq.first(num); foo = fooArraySeq.get(num); diff --git a/lazy.js/lazy.js.d.ts b/lazy.js/lazy.js.d.ts index 7130a9d2d..d388ba6f7 100644 --- a/lazy.js/lazy.js.d.ts +++ b/lazy.js/lazy.js.d.ts @@ -176,7 +176,7 @@ declare module LazyJS { interface ArrayLikeSequence extends Sequence { // define()X; - concat(): ArrayLikeSequence; + concat(var_args: T[]): ArrayLikeSequence; first(count?: number): ArrayLikeSequence; get(index: number): T; length(): number; diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2017252ff..6f24b75dc 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1096,6 +1096,41 @@ result = _.unescape('Moe, Larry & Curly'); result = _.uniqueId('contact_'); result = _.uniqueId(); +/********* +* String +*********/ + +result = _.camelCase('Foo Bar'); +result = _.capitalize('fred'); +result = _.deburr('déjà vu'); +result = _.endsWith('abc', 'c'); +result = _.escape('fred, barney, & pebbles'); +result = _.escapeRegExp('[lodash](https://lodash.com/)'); +result = _.kebabCase('Foo Bar'); +result = _.pad('abc', 8); +result = _.pad('abc', 8, '_-'); +result = _.padLeft('abc', 6); +result = _.padLeft('abc', 6, '_-'); +result = _.padRight('abc', 6); +result = _.padRight('abc', 6, '_-'); +result = _.repeat('*', 3); +result = _.snakeCase('Foo Bar'); +result = _.startCase('--foo-bar'); +result = _.startsWith('abc', 'a'); +result = _.trim(' abc '); +result = _.trim('-_-abc-_-', '_-'); +result = _.trimLeft(' abc '); +result = _.trimLeft('-_-abc-_-', '_-'); +result = _.trimRight(' abc '); +result = _.trimRight('-_-abc-_-', '_-'); +result = _.trunc('hi-diddly-ho there, neighborino'); +result = _.trunc('hi-diddly-ho there, neighborino', 24); +result = _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' ' }); +result = _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/ }); +result = _.trunc('hi-diddly-ho there, neighborino', { 'omission': ' […]' }); +result = _.words('fred, barney, & pebbles'); +result = _.words('fred, barney, & pebbles', /[^, ]+/g); + /********** * Utilities * ***********/ diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c8f7ad42d..c43f27c5c 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6133,6 +6133,50 @@ declare module _ { values(object: any): any[]; } + /********** + * String * + **********/ + + interface LoDashStatic { + camelCase(str?: string): string; + capitalize(str?: string): string; + deburr(str?: string): string; + endsWith(str?: string, target?: string, position?: number): boolean; + escape(str?: string): string; + escapeRegExp(str?: string): string; + kebabCase(str?: string): string; + pad(str?: string, length?: number, chars?: string): string; + padLeft(str?: string, length?: number, chars?: string): string; + padRight(str?: string, length?: number, chars?: string): string; + repeat(str?: string, n?: number): string; + snakeCase(str?: string): string; + startCase(str?: string): string; + startsWith(str?: string, target?: string, position?: number): boolean; + trim(str?: string, chars?: string): string; + trimLeft(str?: string, chars?: string): string; + trimRight(str?: string, chars?: string): string; + trunc(str?: string, len?: number): string; + trunc(str?: string, options?: { length?: number; omission?: string; separator?: string }): string; + trunc(str?: string, options?: { length?: number; omission?: string; separator?: RegExp }): string; + words(str?: string, pattern?: string): string[]; + words(str?: string, pattern?: RegExp): string[]; + } + + //_.parseInt + interface LoDashStatic { + /** + * Converts the given value into an integer of the specified radix. If radix is undefined or 0 a + * radix of 10 is used unless the value is a hexadecimal, in which case a radix of 16 is used. + * + * Note: This method avoids differences in native ES3 and ES5 parseInt implementations. See + * http://es5.github.io/#E. + * @param value The value to parse. + * @param radix The radix used to interpret the value to parse. + * @return The new integer value. + **/ + parseInt(value: string, radix?: number): number; + } + /************* * Utilities * *************/ @@ -6174,22 +6218,6 @@ declare module _ { noConflict(): typeof _; } - //_.parseInt - interface LoDashStatic { - /** - * Converts the given value into an integer of the specified radix. If radix is undefined or 0 a - * radix of 10 is used unless the value is a hexadecimal, in which case a radix of 16 is used. - * - * Note: This method avoids differences in native ES3 and ES5 parseInt implementations. See - * http://es5.github.io/#E. - * @param value The value to parse. - * @param radix The radix used to interpret the value to parse. - * @return The new integer value. - **/ - parseInt(value: string): number; - } - - //_.property interface LoDashStatic { /** diff --git a/mkpath/mkpath-tests.ts b/mkpath/mkpath-tests.ts new file mode 100644 index 000000000..d0be59244 --- /dev/null +++ b/mkpath/mkpath-tests.ts @@ -0,0 +1,9 @@ +/// +import mkpath = require('mkpath'); + +mkpath('red/green/violet', function (err) { + if (err) throw err; + console.log('Directory structure red/green/violet created'); +}); + +mkpath.sync('/tmp/blue/orange', 700); diff --git a/mkpath/mkpath.d.ts b/mkpath/mkpath.d.ts new file mode 100644 index 000000000..3be1a0229 --- /dev/null +++ b/mkpath/mkpath.d.ts @@ -0,0 +1,15 @@ +// Type definitions for mkpath v0.1.0 +// Project: https://www.npmjs.com/package/mkpath +// Definitions by: Jared Klopper +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'mkpath' { + module mkpath { + function sync(path: string, mode?: number): void; + } + + function mkpath(path: string, callback?: (err: any) => void): void; + function mkpath(path: string, mode?: number, callback?: (err?: any) => void): void; + + export = mkpath; +} diff --git a/node-persist/node-persist-tests.ts b/node-persist/node-persist-tests.ts new file mode 100644 index 000000000..a4e2af1ed --- /dev/null +++ b/node-persist/node-persist-tests.ts @@ -0,0 +1,47 @@ +/// +// node-persist tests +// compile with --module=common + +import nodePersist = require("node-persist"); + +var opts = Node +nodePersist.init({ + dir: __dirname + "/test", + continuous: false +}); +nodePersist.setItem("someArray", [1,2,3], (err)=> { + nodePersist.getItem("someArray", (err: any, value: any)=> { + nodePersist.removeItem("someArray", (err) => err); + }); +}); +nodePersist.setItem("someString", "foo") + .then(() => nodePersist.getItem("someString")) + .then(() => nodePersist.removeItem("someString")) + .then(() => nodePersist.clear()) + .then(() => null); + +interface TestObject { + foo: string; + two: number; +} +nodePersist.clear((err) => { + var testObject: TestObject = {foo: "bar", two: 2}; + nodePersist.setItemSync("someObject", testObject); + testObject = nodePersist.getItemSync("someObject"); + nodePersist.removeItem("someObject"); + nodePersist.clearSync(); +}); + +var values: Array = nodePersist.values(); +var valuesWithKeyMatch: Array = nodePersist.valuesWithKeyMatch("some"); +var keys: Array = nodePersist.keys(); +var size: number = nodePersist.length(); +nodePersist.forEach((val) => {}); +try { + nodePersist.persist((err) => err); + nodePersist.persist().then(() => null); + nodePersist.persistSync; + nodePersist.persistKey("this", (err) => null); + nodePersist.persistKey("this").then(() => null); + nodePersist.persistKeySync("this"); +} catch(anyError){} diff --git a/node-persist/node-persist.d.ts b/node-persist/node-persist.d.ts new file mode 100644 index 000000000..23c86bd5c --- /dev/null +++ b/node-persist/node-persist.d.ts @@ -0,0 +1,44 @@ +// Type definitions for node-persist +// Project: https://github.com/simonlast/node-persist +// Definitions by: Spencer Williams +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "node-persist" { + type milliseconds = number; + module NodePersist { + export interface InitOptions { + dir?: string; + stringify?: (toSerialize: any)=>string; + parse?: (serialized: string)=>any; + encoding?: string; + logging?: boolean|Function; + continuous?: boolean; + interval?: milliseconds|boolean; + ttl?: milliseconds|boolean; + } + export function init(options?: InitOptions, callback?: Function): Q.Promise; + export function initSync(options?: InitOptions): void; + export function getItem(key: string, callback?: (err: any, value: any)=>any): Q.Promise; + export function getItemSync(key: string): any; + export function setItem(key: string, value: any, callback?: (err: any)=>any): Q.Promise; + export function setItemSync(key: string, value: any): void; + export function removeItem(key: string, callback?: (err: any)=>any): Q.Promise; + export function removeItemSync(key: string): void; + export function clear(callback?: (err: any)=>any): Q.Promise; + export function clearSync(): void; + export function values(): Array; + export function valuesWithKeyMatch(match: string): Array; + export function keys(): Array; + export function length(): number; + export function forEach(callback: (key: string, value: any)=>void): void; + + export function persist(callback?: (err: any)=>any): Q.Promise; + export function persistSync(): void; + export function persistKey(key: string, callback?: (err: any)=>any): Q.Promise; + export function persistKeySync(key: string): void; + } + export = NodePersist; +} diff --git a/node/node-0.11-tests.ts b/node/node-0.11-tests.ts index e9ef58dbb..5a0c294d4 100644 --- a/node/node-0.11-tests.ts +++ b/node/node-0.11-tests.ts @@ -10,6 +10,7 @@ import crypto = require("crypto"); import http = require("http"); import net = require("net"); import dgram = require("dgram"); +import querystring = require('querystring'); assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -122,4 +123,14 @@ var ai: dgram.AddressInfo = ds.address(); ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { }); +//////////////////////////////////////////////////// +///Querystring tests : https://gist.github.com/musubu/2202583 +//////////////////////////////////////////////////// +var original: string = 'http://example.com/product/abcde.html'; +var escaped: string = querystring.escape(original); +console.log(escaped); +// http%3A%2F%2Fexample.com%2Fproduct%2Fabcde.html +var unescaped: string = querystring.unescape(escaped); +console.log(unescaped); +// http://example.com/product/abcde.html diff --git a/node/node-0.11.d.ts b/node/node-0.11.d.ts index a564ac85f..302ba12a9 100644 --- a/node/node-0.11.d.ts +++ b/node/node-0.11.d.ts @@ -250,8 +250,8 @@ declare module "buffer" { declare module "querystring" { export function stringify(obj: any, sep?: string, eq?: string): string; export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; - export function escape(): any; - export function unescape(): any; + export function escape(str: string): string; + export function unescape(str: string): string; } declare module "events" { diff --git a/node/node-0.8.8.d.ts b/node/node-0.8.8.d.ts index f236faa89..274a580d8 100644 --- a/node/node-0.8.8.d.ts +++ b/node/node-0.8.8.d.ts @@ -203,8 +203,8 @@ interface Buffer { declare module "querystring" { export function stringify(obj: any, sep?: string, eq?: string): string; export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; - export function escape(): any; - export function unescape(): any; + export function escape(str: string): string; + export function unescape(str: string): string; } declare module "events" { diff --git a/node/node-tests.ts b/node/node-tests.ts index 7f59ab985..f2702ec4a 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -10,6 +10,7 @@ import crypto = require("crypto"); import http = require("http"); import net = require("net"); import dgram = require("dgram"); +import querystring = require('querystring'); assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -165,4 +166,14 @@ var ai: dgram.AddressInfo = ds.address(); ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { }); +//////////////////////////////////////////////////// +///Querystring tests : https://gist.github.com/musubu/2202583 +//////////////////////////////////////////////////// +var original: string = 'http://example.com/product/abcde.html'; +var escaped: string = querystring.escape(original); +console.log(escaped); +// http%3A%2F%2Fexample.com%2Fproduct%2Fabcde.html +var unescaped: string = querystring.unescape(escaped); +console.log(unescaped); +// http://example.com/product/abcde.html diff --git a/node/node.d.ts b/node/node.d.ts index 6c09ee04f..b1e849535 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -250,8 +250,8 @@ declare module "buffer" { declare module "querystring" { export function stringify(obj: any, sep?: string, eq?: string): string; export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; - export function escape(): any; - export function unescape(): any; + export function escape(str: string): string; + export function unescape(str: string): string; } declare module "events" { diff --git a/nopt/nopt-tests.ts b/nopt/nopt-tests.ts new file mode 100644 index 000000000..1e2fb60a5 --- /dev/null +++ b/nopt/nopt-tests.ts @@ -0,0 +1,20 @@ +/** +* Maintained by: jbondc +*/ + +/// +/// + +import nopt = require("nopt"); + +nopt({"--foo" : String}) + +nopt({ "--foo": String }, { "-f": "--foo"}) +nopt({ "--foo": String }, { "-f": ["--foo", "-d"] }) + +nopt({ "--foo": String }, { "-f": ["--foo", "-d"] }, ["test me --foo arg"]) +var cmd = nopt({ "--foo": String }, { "-f": ["--foo", "-d"] }, ["test me --foo arg"], 2) + +console.log(cmd.argv.cooked) +console.log(cmd.argv.original) +console.log(cmd.argv.remain) diff --git a/nopt/nopt.d.ts b/nopt/nopt.d.ts new file mode 100644 index 000000000..01e439821 --- /dev/null +++ b/nopt/nopt.d.ts @@ -0,0 +1,46 @@ +// Type definitions for nopt 3.0.1 +// Project: https://github.com/npm/nopt +// Definitions by: jbondc +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "nopt" { + + interface CommandData { + [key: string]: string + } + + interface TypeDefs { + [key: string]: TypeInfo + } + + interface TypeInfo { + type: Object + validate: (data: CommandData, k: string, val: string) => boolean + } + + module nopt { + export function clean(data: CommandData, types: FlagTypeMap, typeDefs?: TypeDefs): string + export var typeDefs: TypeDefs + } + + interface FlagTypeMap { + [k: string]: Object + } + + interface ShortFlags { + [k: string]: string[]|string + } + + function nopt(types: FlagTypeMap, shorthands?: ShortFlags, args?: string[], slice?: number): OptionsParsed + + interface OptionsParsed { + [k: string]: any + argv: { + remain: string[] + cooked: string[] + original: string[] + } + } + + export = nopt +} \ No newline at end of file diff --git a/raphael/raphael.d.ts b/raphael/raphael.d.ts index 82dba5d4c..bef33d99c 100644 --- a/raphael/raphael.d.ts +++ b/raphael/raphael.d.ts @@ -28,9 +28,9 @@ interface RaphaelElement { animateWith(el: RaphaelElement, anim: RaphaelAnimation, params: any, ms: number, easing?: string, callback?: Function): RaphaelElement; animateWith(el: RaphaelElement, anim: RaphaelAnimation, animation: RaphaelAnimation): RaphaelElement; attr(attrName: string, value: any): RaphaelElement; - attr(params: any): RaphaelElement; attr(attrName: string): any; attr(attrNames: string[]): any[]; + attr(params: any): RaphaelElement; click(handler: Function): RaphaelElement; clone(): RaphaelElement; data(key: string): any; diff --git a/react-router/react-router-test.ts b/react-router/react-router-test.ts new file mode 100644 index 000000000..c220b3c24 --- /dev/null +++ b/react-router/react-router-test.ts @@ -0,0 +1,326 @@ +/// +"use strict"; + +import React = require('react'); +import Router = require('react-router'); + +// Mixin +class NavigationTest { + v: T; + + makePath() { + var v1: string = this.v.makePath('to'); + var v2: string = this.v.makePath('to', {id: 1}); + var v3: string = this.v.makePath('to', {id: 1}, {type: 'json'}); + } + makeHref() { + var v1: string = this.v.makeHref('to'); + var v2: string = this.v.makeHref('to', {id: 1}); + var v3: string = this.v.makeHref('to', {id: 1}, {type: 'json'}); + } + transitionTo() { + var v1: void = this.v.transitionTo('to'); + var v2: void = this.v.transitionTo('to', {id: 1}); + var v3: void = this.v.transitionTo('to', {id: 1}, {type: 'json'}); + } + replaceWith() { + var v1: void = this.v.replaceWith('to'); + var v2: void = this.v.replaceWith('to', {id: 1}); + var v3: void = this.v.replaceWith('to', {id: 1}, {type: 'json'}); + } + goBack() { + var v1: void = this.v.goBack(); + } +} + +class StateTest { + v: T; + + getPath() { + var v1: string = this.v.getPath(); + } + + getRoutes() { + var v1: Router.Route[] = this.v.getRoutes(); + } + + getPathname() { + var v1: string = this.v.getPathname(); + } + + getParams() { + var v1: {} = this.v.getParams(); + } + + getQuery() { + var v1: {} = this.v.getQuery(); + } + + isActive() { + var v1: boolean = this.v.isActive('to'); + var v2: boolean = this.v.isActive('to', {id: 1}); + var v3: boolean = this.v.isActive('to', {id: 1}, {type: 'json'}); + } +} + +class RouteHandlerMixinTest { + v: T; + + getRouteDepth() { + var v1: number = this.v.getRouteDepth(); + } + + createChildRouteHandler() { + var v1: Router.RouteHandler = this.v.createChildRouteHandler({ref: 'hoge'}); + } +} + + +// Location +class LocationTest { + v: T; + + push() { + var v1: void = this.v.push('path/to/hoge'); + } + + replace() { + var v1: void = this.v.replace('path/to/hoge'); + } + + pop() { + var v1: void = this.v.pop(); + } + + getCurrentPath() { + var v1: void = this.v.getCurrentPath(); + } +} +new LocationTest(); +new LocationTest(); +new LocationTest(); + +class LocationListenerTest { + v: T; + + addChangeListener() { + var v1: void = this.v.addChangeListener(() => console.log(1)); + } + + removeChangeListener() { + var v1: void = this.v.removeChangeListener(() => console.log(1)); + } +} +new LocationListenerTest(); +new LocationListenerTest(); + + +// Behavior +class ScrollBehaviorTest { + v: T; + + updateScrollPosition() { + var v1: void = this.v.updateScrollPosition({x: 33, y: 102}, 'scrollTop'); + } +} +new ScrollBehaviorTest(); +new ScrollBehaviorTest(); + + +// Component +class DefaultRouteTest { + v: Router.DefaultRoute; + + props() { + var name: string = this.v.props.name; + var handler: React.ComponentClass = this.v.props.handler; + } + + createElement() { + var Handler: React.ComponentClass; + React.createElement(Router.DefaultRoute, null); + React.createElement(Router.DefaultRoute, {name: 'name', handler: Handler}); + } +} + +class LinkTest { + v: Router.Link; + + constructor() { + new NavigationTest(); + new StateTest(); + } + + props() { + var activeClassName: string = this.v.props.activeClassName; + var to: string = this.v.props.to; + var params: {} = this.v.props.params; + var query: {} = this.v.props.query; + var onClick: Function = this.v.props.onClick; + } + + getHref() { + var v1: string = this.v.getHref(); + } + + getClassName() { + var v1: string = this.v.getClassName(); + } + + createElement() { + React.createElement(Router.Link, null); + React.createElement(Router.Link, {to: 'home'}); + React.createElement(Router.Link, { + activeClassName: 'name', + to: 'home', + params: {}, + query: {}, + onClick: () => console.log(1) + }); + } +} + +class NotFoundRouteTest { + v: Router.NotFoundRoute; + + props() { + var name: string = this.v.props.name; + var handler: React.ComponentClass = this.v.props.handler; + } + + createElement() { + var Handler: React.ComponentClass; + React.createElement(Router.NotFoundRoute, null); + React.createElement(Router.NotFoundRoute, {handler: Handler}); + React.createElement(Router.NotFoundRoute, {handler: Handler, name: "home"}); + } +} + +class RedirectTest { + v: Router.Redirect; + + props() { + var path: string = this.v.props.path; + var from: string = this.v.props.from; + var to: string = this.v.props.to; + } + + createElement() { + React.createElement(Router.Redirect, null); + React.createElement(Router.Redirect, {}); + React.createElement(Router.Redirect, {path: 'a', from: 'a', to: 'b'}); + } +} + +class RouteTest { + v: Router.Route; + + props() { + var name: string = this.v.props.name; + var path: string = this.v.props.path; + var handler: React.ComponentClass = this.v.props.handler; + var ignoreScrollBehavior: boolean = this.v.props.ignoreScrollBehavior; + } + + createElement() { + var Handler: React.ComponentClass; + React.createElement(Router.Route, null); + React.createElement(Router.Route, {}); + React.createElement(Router.Route, {name: "home", path: "/", handler: Handler, ignoreScrollBehavior: true}); + } +} + +class RouteHandlerTest { + v: Router.RouteHandler; + + constructor() { + new RouteHandlerMixinTest(); + } + + createElement() { + React.createElement(Router.RouteHandler, null); + React.createElement(Router.RouteHandler, {}); + } +} + + +// History +class HistoryTest { + v: Router.History; + + length() { + var v1: number = this.v.length; + } + + back() { + var v1: void = this.v.back(); + } +} + + +// Router +class CreateTest { + v: Router.Router; + + constructor() { + this.v = Router.create({ + routes: React.createElement(Router.Route, null) + }); + this.v = Router.create({ + routes: React.createElement(Router.Route, null), + location: Router.HistoryLocation, + scrollBehavior: Router.ImitateBrowserBehavior + }); + } + + run() { + this.v.run((Handler) => console.log(Handler)); + this.v.run((Handler, state) => console.log(Handler, state)); + } +} + +class RunTest { + constructor() { + var v1: Router.Router = Router.run(React.createElement(Router.Route, null), (Handler) => { + React.render(React.createElement(Handler, null), document.body); + }); + var v2: Router.Router = Router.run(React.createElement(Router.Route, null), Router.HistoryLocation, (Handler, state) => { + React.render(React.createElement(Handler, null), document.body); + }); + } +} + + +// Transition +class TransitionTest { + constructor() { + var v1: Router.TransitionStaticLifecycle = { + willTransitionTo: (transition, params, query, callback) => { + transition.abort(); + transition.redirect('to'); + transition.redirect('to', {id: 1}); + transition.redirect('to', {id: 1}, {type: 'json'}); + transition.retry(); + }, + willTransitionFrom: (transition, component, callback) => {} + }; + var v2: Router.TransitionStaticLifecycle = { + willTransitionTo: (transition, params, query) => {}, + willTransitionFrom: (transition, component) => {} + }; + var v3: Router.TransitionStaticLifecycle = { + willTransitionTo: (transition, params) => {}, + willTransitionFrom: (transition) => {} + }; + var v4: Router.TransitionStaticLifecycle = { + willTransitionTo: (transition) => {}, + willTransitionFrom: () => {} + }; + var v5: Router.TransitionStaticLifecycle = { + willTransitionTo: () => {} + }; + var v6: Router.TransitionStaticLifecycle = { + willTransitionFrom: () => {} + }; + } +} diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts new file mode 100644 index 000000000..13c573b4b --- /dev/null +++ b/react-router/react-router.d.ts @@ -0,0 +1,278 @@ +// Type definitions for React Router 0.12.0 +// Project: https://github.com/rackt/react-router +// Definitions by: Yuichi Murata +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module ReactRouter { + // + // Mixin + // ---------------------------------------------------------------------- + interface Navigation { + makePath(to: string, params?: {}, query?: {}): string; + makeHref(to: string, params?: {}, query?: {}): string; + transitionTo(to: string, params?: {}, query?: {}): void; + replaceWith(to: string, params?: {}, query?: {}): void; + goBack(): void; + } + + interface RouteHandlerMixin { + getRouteDepth(): number; + createChildRouteHandler(props: {}): RouteHandler; + } + + interface State { + getPath(): string; + getRoutes(): Route[]; + getPathname(): string; + getParams(): {}; + getQuery(): {}; + isActive(to: string, params?: {}, query?: {}): boolean; + } + + var Navigation: Navigation; + var State: State; + var RouteHandlerMixin: RouteHandlerMixin; + + + // + // Component + // ---------------------------------------------------------------------- + // DefaultRoute + interface DefaultRouteProp { + name?: string; + handler: React.ComponentClass; + } + interface DefaultRoute extends React.ReactElement { + __react_router_default_route__: any; // dummy + } + interface DefaultRouteClass extends React.ComponentClass { + __react_router_default_route__: any; // dummy + } + + // Link + interface LinkProp { + activeClassName?: string; + to: string; + params?: {}; + query?: {}; + onClick?: Function; + } + interface Link extends React.ReactElement, Navigation, State { + __react_router_link__: any; // dummy + + getHref(): string; + getClassName(): string; + } + interface LinkClass extends React.ComponentClass { + __react_router_link__: any; // dummy + } + + // NotFoundRoute + interface NotFoundRouteProp { + name?: string; + handler: React.ComponentClass; + } + interface NotFoundRoute extends React.ReactElement { + __react_router_not_found_route__: any; // dummy + } + interface NotFoundRouteClass extends React.ComponentClass { + __react_router_not_found_route__: any; // dummy + } + + // Redirect + interface RedirectProp { + path?: string; + from?: string; + to?: string; + } + interface Redirect extends React.ReactElement { + __react_router_redirect__: any; // dummy + } + interface RedirectClass extends React.ComponentClass { + __react_router_redirect__: any; // dummy + } + + // Route + interface RouteProp { + name?: string; + path?: string; + handler?: React.ComponentClass; + ignoreScrollBehavior?: boolean; + } + interface Route extends React.ReactElement { + __react_router_route__: any; // dummy + } + interface RouteClass extends React.ComponentClass { + __react_router_route__: any; // dummy + } + + // RouteHandler + interface RouteHandlerProp {} + interface RouteHandler extends React.ReactElement, RouteHandlerMixin { + __react_router_route_handler__: any; // dummy + } + interface RouteHandlerClass extends React.ReactElement { + __react_router_route_handler__: any; // dummy + } + + var DefaultRoute: DefaultRouteClass; + var Link: LinkClass; + var NotFoundRoute: NotFoundRouteClass; + var Redirect: RedirectClass; + var Route: RouteClass; + var RouteHandler: RouteHandlerClass; + + + // + // Location + // ---------------------------------------------------------------------- + interface LocationBase { + push(path: string): void; + replace(path: string): void; + pop(): void; + getCurrentPath(): void; + } + + interface LocationListener { + addChangeListener(listener: Function): void; + removeChangeListener(listener: Function): void; + } + + interface HashLocation extends LocationBase, LocationListener {} + interface HistoryLocation extends LocationBase, LocationListener {} + interface RefreshLocation extends LocationBase {} + + var HashLocation: HashLocation; + var HistoryLocation: HistoryLocation; + var RefreshLocation: RefreshLocation; + + + // + // Behavior + // ---------------------------------------------------------------------- + interface ScrollBehaviorBase { + updateScrollPosition(position: {x: number; y: number;}, actionType: string): void; + } + interface ImitateBrowserBehavior extends ScrollBehaviorBase {} + interface ScrollToTopBehavior extends ScrollBehaviorBase {} + + var ImitateBrowserBehavior: ImitateBrowserBehavior; + var ScrollToTopBehavior: ScrollToTopBehavior; + + + // + // Router + // ---------------------------------------------------------------------- + interface Router extends React.ReactElement { + run(callback: RouterRunCallback): void; + } + + interface RouterState { + path: string; + action: string; + pathname: string; + params: {}; + query: {}; + routes : Route[]; + } + + interface RouterCreateOption { + routes: Route; + location?: LocationBase; + scrollBehavior?: ScrollBehaviorBase; + } + + type RouterRunCallback = (Handler: Router, state: RouterState) => void; + + function create(options: RouterCreateOption): Router; + function run(routes: Route, callback: RouterRunCallback): Router; + function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; + + + // + // History + // ---------------------------------------------------------------------- + interface History { + back(): void; + length: number; + } + var History: History; + + + // + // Transition + // ---------------------------------------------------------------------- + interface Transition { + abort(): void; + redirect(to: string, params?: {}, query?: {}): void; + retry(): void; + } + + interface TransitionStaticLifecycle { + willTransitionTo?( + transition: Transition, + params: {}, + query: {}, + callback: Function + ): void; + + willTransitionFrom?( + transition: Transition, + component: React.ReactElement, + callback: Function + ): void; + } +} + +declare module 'react-router' { + import Export = ReactRouter; + export = Export; +} + +declare module React { + interface TopLevelAPI { + // for DefaultRoute + createElement( + type: ReactRouter.DefaultRouteClass, + props: ReactRouter.DefaultRouteProp, + ...children: ReactNode[] + ): ReactRouter.DefaultRoute; + + // for Link + createElement( + type: ReactRouter.LinkClass, + props: ReactRouter.LinkProp, + ...children: ReactNode[] + ): ReactRouter.Link; + + // for NotFoundRoute + createElement( + type: ReactRouter.NotFoundRouteClass, + props: ReactRouter.NotFoundRouteProp, + ...children: ReactNode[] + ): ReactRouter.NotFoundRoute; + + // for Redirect + createElement( + type: ReactRouter.RedirectClass, + props: ReactRouter.RedirectProp, + ...children: ReactNode[] + ): ReactRouter.Redirect; + + // for Route + createElement( + type: ReactRouter.RouteClass, + props: ReactRouter.RouteProp, + ...children: ReactNode[] + ): ReactRouter.Route; + + // for RouteHandler + createElement( + type: ReactRouter.RouteHandlerClass, + props: ReactRouter.RouteHandlerProp, + ...children: ReactNode[] + ): ReactRouter.RouteHandler; + } +} diff --git a/react/future/README.md b/react/future/README.md new file mode 100644 index 000000000..07a203920 --- /dev/null +++ b/react/future/README.md @@ -0,0 +1,10 @@ +# React v0.13.0-beta Type Definitions + +This folder contains the following `.d.ts` files: +* `react-0.13.0.d.ts` declares the external module `"react"` +* `react-addons-0.13.0.d.ts` declares the external module `"react/addons"` +* `react-global-0.13.0.d.ts` declares the internal module `React` in the global namespace +* `react-addons-global-0.13.0.d.ts` extends the global `React` module with `addons` + +Interfaces are duplicated between these files; please take care to keep them in sync when making changes. See [#3615](https://github.com/borisyankov/DefinitelyTyped/pull/3615) for relevant discussion. + diff --git a/react/react-0.13.0-tests.ts b/react/future/react-0.13.0-tests.ts similarity index 67% rename from react/react-0.13.0-tests.ts rename to react/future/react-0.13.0-tests.ts index 18d4bcf4e..dd0052ee3 100644 --- a/react/react-0.13.0-tests.ts +++ b/react/future/react-0.13.0-tests.ts @@ -1,9 +1,9 @@ -/// - +/// // requiring react/addons instead of react so react.d.ts doesn't get picked up -import React = require('react/addons'); +// TODO: import "react" once 0.13.0 is released +import React = require("react/addons"); -interface Props { +interface Props extends React.Props { hello: string; world?: string; foo: number; @@ -42,36 +42,37 @@ var INPUT_REF: string = "input"; // Top-Level API // -------------------------------------------------------------------------- -var reactClassicClass: React.ClassicComponentClass = React.createClass({ - getDefaultProps: () => { - return { - hello: undefined, - world: "peace", - foo: undefined, - bar: undefined - }; - }, - getInitialState: () => { - return { - inputValue: this.context.someValue, - seconds: this.props.foo - }; - }, - reset: () => { - this.replaceState(this.getInitialState()); - }, - render: () => { - return React.DOM.div(null, - React.DOM.input({ - ref: INPUT_REF, - value: this.state.inputValue - })); - } -}); +var ClassicComponent: React.ClassicComponentClass = + React.createClass({ + getDefaultProps: () => { + return { + hello: undefined, + world: "peace", + foo: undefined, + bar: undefined + }; + }, + getInitialState: () => { + return { + inputValue: this.context.someValue, + seconds: this.props.foo + }; + }, + reset: () => { + this.replaceState(this.getInitialState()); + }, + render: () => { + return React.DOM.div(null, + React.DOM.input({ + ref: INPUT_REF, + value: this.state.inputValue + })); + } + }); -var reactClass: React.ComponentClass = reactClassicClass; +class ModernComponent extends React.Component + implements React.ChildContextProvider { -class ModernComponent extends React.Component implements React.ChildContextProvider { constructor(props: Props, context: Context) { super(props, context); this.state = { @@ -80,18 +81,17 @@ class ModernComponent extends React.Component implements }; } - // this should work but doesn't. Due to TypeScript bug? - //static propTypes = { - // foo: React.PropTypes.number - //} + static propTypes: React.ValidationMap = { + foo: React.PropTypes.number + } - //static contextTypes = { - // someValue: React.PropTypes.string - //} + static contextTypes: React.ValidationMap = { + someValue: React.PropTypes.string + } - //static childContextTypes = { - // someOtherValue: React.PropTypes.string - //} + static childContextTypes: React.ValidationMap = { + someOtherValue: React.PropTypes.string + } getChildContext() { return { @@ -120,66 +120,71 @@ class ModernComponent extends React.Component implements } } -ModernComponent.propTypes = { - foo: React.PropTypes.string, -} +// React.createFactory +var factory: React.Factory = + React.createFactory(ModernComponent); +var factoryElement: React.ReactElement = + factory(props); -ModernComponent.contextTypes = { - someValue: React.PropTypes.string -} +var classicFactory: React.ClassicFactory = + React.createFactory(ClassicComponent); +var classicFactoryElement: React.ReactClassicElement = + classicFactory(props); -ModernComponent.childContextTypes = { - someOtherValue: React.PropTypes.string -} +var domFactory: React.DOMFactory = + React.createFactory("foo"); +var domFactoryElement: React.ReactDOMElement = + domFactory(); -var reactElement: React.ReactElement; -reactElement = React.createElement(reactClass, props); -reactElement = React.createElement(ModernComponent, props); +// React.createElement +var element: React.ReactElement = + React.createElement(ModernComponent, props); +var classicElement: React.ReactClassicElement = + React.createElement(ClassicComponent, props); +var domElement: React.ReactHTMLElement = + React.createElement("div"); -var reactFactory: React.ComponentFactory; -reactFactory = React.createFactory(reactClass); -reactFactory = React.createFactory(ModernComponent); - -var component: React.Component = - React.render(reactElement, container); +// React.render +var component: React.Component = + React.render(element, container); +var classicComponent: React.ClassicComponent = + React.render(classicElement, container); +var domComponent: React.DOMComponent = + React.render(domElement, container); +// Other Top-Level API var unmounted: boolean = React.unmountComponentAtNode(container); -var str: string = React.renderToString(reactElement); -var markup: string = React.renderToStaticMarkup(reactElement); +var str: string = React.renderToString(element); +var markup: string = React.renderToStaticMarkup(element); var notValid: boolean = React.isValidElement(props); // false -var isValid = React.isValidElement(reactElement); // true +var isValid = React.isValidElement(element); // true React.initializeTouchEvents(true); var domNode: Element = React.findDOMNode(component); - -var reactClassicElement: React.ReactClassicElement; -reactClassicElement = React.createElement(reactClassicClass, props); -var classicComponent: React.ClassicComponent; -classicComponent = React.render(reactClassicElement, container); +domNode = React.findDOMNode(domNode); // // React Elements // -------------------------------------------------------------------------- -var type = reactElement.type; -var elementProps: Props = reactElement.props; -var key = reactElement.key; -var ref: string = reactElement.ref; -var factoryElement: React.ReactElement = reactFactory(elementProps); +var type = element.type; +var elementProps: Props = element.props; +var key = element.key; +var ref: string = element.ref; // // React Components // -------------------------------------------------------------------------- -var displayName: string = reactClass.displayName; -var defaultProps: Props = reactClass.getDefaultProps(); -var propTypes: React.ValidationMap = reactClass.propTypes; +var displayName: string = ClassicComponent.displayName; +var defaultProps: Props = ClassicComponent.getDefaultProps(); +var propTypes: React.ValidationMap = ClassicComponent.propTypes; // // Component API // -------------------------------------------------------------------------- // modern -var initialState: State = component.state; +var componentState: State = component.state; component.setState({ inputValue: "!!!" }); component.forceUpdate(); @@ -324,33 +329,28 @@ var onlyChild = React.Children.only([null, [[["Hallo"], true]], false]); interface TimerState { secondsElapsed: number; } -interface Timer extends React.Component<{}, TimerState, any> { -} -var Timer = React.createClass({ - displayName: "Timer", - getInitialState: () => { - return { secondsElapsed: 0 }; - }, - tick: () => { - var me = this; - me.setState({ - secondsElapsed: me.state.secondsElapsed + 1 - }); - }, - componentDidMount: () => { - this.interval = setInterval(this.tick, 1000); - }, - componentWillUnmount: () => { - clearInterval(this.interval); - }, - render: () => { - var me = this; +class Timer extends React.Component<{}, TimerState, {}> { + static state = { + secondsElapsed: 0 + } + private _interval: number; + tick() { + this.setState({ secondsElapsed: this.state.secondsElapsed + 1 }); + } + componentDidMount() { + var me = this; + this._interval = setInterval(() => me.tick(), 1000); + } + componentWillUnmount() { + clearInterval(this._interval); + } + render() { return React.DOM.div( null, "Seconds Elapsed: ", - me.state.secondsElapsed + this.state.secondsElapsed ); } -}); -var mountNode: Element; -React.render(React.createElement(Timer, null), mountNode); +} +React.render(React.createElement(Timer), container); + diff --git a/react/future/react-0.13.0.d.ts b/react/future/react-0.13.0.d.ts new file mode 100644 index 000000000..842623bc8 --- /dev/null +++ b/react/future/react-0.13.0.d.ts @@ -0,0 +1,747 @@ +// Type definitions for React v0.13.0 (external module) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "react" { + // + // React Elements + // ---------------------------------------------------------------------- + + interface ReactElementBase { + type: T; + props: P; + key: number | string; + ref: string; + } + + interface ReactElement

+ extends ReactElementBase, P> {} + + interface ReactClassicElement

+ extends ReactElementBase | string, P> {} + + interface ReactDOMElement

// subtype of ReactClassicElement + extends ReactElementBase {} + + type ReactHTMLElement = ReactDOMElement; + type ReactSVGElement = ReactDOMElement; + + // + // Factories + // ---------------------------------------------------------------------- + + interface Factory

{ + (props?: P, ...children: ReactNode[]): ReactElement

; + } + + interface ClassicFactory

{ + (props?: P, ...children: ReactNode[]): ReactClassicElement

; + } + + interface DOMFactory

{ + (props?: P, ...children: ReactNode[]): ReactDOMElement

; + } + + type HTMLFactory = DOMFactory; + type SVGFactory = DOMFactory; + + // + // React Nodes + // http://facebook.github.io/react/docs/glossary.html + // ---------------------------------------------------------------------- + + type ReactText = string | number; + type ReactChild = ReactElementBase | ReactText; + + // Should be Array but type aliases cannot be recursive + type ReactFragment = Array; + type ReactNode = ReactChild | ReactFragment | boolean; + + // + // Top Level API + // ---------------------------------------------------------------------- + + function createClass( + spec: ComponentSpec): ClassicComponentClass; + + function createFactory

( + type: string): DOMFactory

; + function createFactory

( + type: ClassicComponentClass | string): ClassicFactory

; + function createFactory

( + type: ComponentClass): Factory

; + + function createElement

( + type: string, + props?: P, + ...children: ReactNode[]): ReactDOMElement

; + function createElement

( + type: ClassicComponentClass | string, + props?: P, + ...children: ReactNode[]): ReactClassicElement

; + function createElement

( + type: ComponentClass, + props?: P, + ...children: ReactNode[]): ReactElement

; + + function render

( + element: ReactDOMElement

, + container: Element, + callback?: () => any): DOMComponent

; + function render( + element: ReactClassicElement

, + container: Element, + callback?: () => any): ClassicComponent; + function render( + element: ReactElement

, + container: Element, + callback?: () => any): Component; + + function unmountComponentAtNode(container: Element): boolean; + function renderToString(element: ReactElementBase): string; + function renderToStaticMarkup(element: ReactElementBase): string; + function isValidElement(object: {}): boolean; + function initializeTouchEvents(shouldUseTouch: boolean): void; + + function findDOMNode( + componentOrElement: Component | Element): TElement; + function findDOMNode( + componentOrElement: Component | Element): Element; + + var DOM: ReactDOM; + var PropTypes: ReactPropTypes; + var Children: ReactChildren; + + // + // Component API + // ---------------------------------------------------------------------- + + // Base component for plain JS classes + class Component implements ComponentLifecycle { + constructor(props: P, context: C); + setState(state: S, callback?: () => any): void; + forceUpdate(): void; + props: P; + state: S; + context: C; + refs: { + [key: string]: Component + }; + } + + interface ClassicComponent extends Component { + replaceState(nextState: S, callback?: () => any): void; + getDOMNode(): TElement; + getDOMNode(): Element; + isMounted(): boolean; + getInitialState?(): S; + setProps(nextProps: P, callback?: () => any): void; + replaceProps(nextProps: P, callback?: () => any): void; + } + + interface DOMComponent

extends ClassicComponent { + tagName: string; + } + + type HTMLComponent = DOMComponent; + type SVGComponent = DOMComponent; + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + interface ComponentClassBase { + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap<{}>; + } + + interface ComponentClass extends ComponentClassBase { + new(props?: P, context?: C): Component; + defaultProps?: P; + } + + interface ClassicComponentClass extends ComponentClassBase { + new(props?: P, context?: C): ClassicComponent; + getDefaultProps?(): P; + displayName?: string; + } + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + interface ComponentLifecycle { + componentWillMount?(): void; + componentDidMount?(): void; + componentWillReceiveProps?(nextProps: P, nextContext: C): void; + shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: C): boolean; + componentWillUpdate?(nextProps: P, nextState: S, nextContext: C): void; + componentDidUpdate?(prevProps: P, prevState: S, prevContext: C): void; + componentWillUnmount?(): void; + } + + interface Mixin extends ComponentLifecycle { + mixins?: Mixin; + statics?: { + [key: string]: any; + }; + + displayName?: string; + propTypes?: ValidationMap; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap + + getInitialState?(): S; + getDefaultProps?(): P; + } + + interface ComponentSpec extends Mixin { + render(): ReactElementBase; + } + + // + // Event System + // ---------------------------------------------------------------------- + + interface SyntheticEvent { + bubbles: boolean; + cancelable: boolean; + currentTarget: EventTarget; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + nativeEvent: Event; + preventDefault(): void; + stopPropagation(): void; + target: EventTarget; + timeStamp: Date; + type: string; + } + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + } + + interface KeyboardEvent extends SyntheticEvent { + altKey: boolean; + charCode: number; + ctrlKey: boolean; + getModifierState(key: string): boolean; + key: string; + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + repeat: boolean; + shiftKey: boolean; + which: number; + } + + interface FocusEvent extends SyntheticEvent { + relatedTarget: EventTarget; + } + + interface FormEvent extends SyntheticEvent { + } + + interface MouseEvent extends SyntheticEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + pageX: number; + pageY: number; + relatedTarget: EventTarget; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends SyntheticEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + view: AbstractView; + } + + interface WheelEvent extends SyntheticEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + interface EventHandler { + (event: E): void; + } + + interface ClipboardEventHandler extends EventHandler {} + interface KeyboardEventHandler extends EventHandler {} + interface FocusEventHandler extends EventHandler {} + interface FormEventHandler extends EventHandler {} + interface MouseEventHandler extends EventHandler {} + interface TouchEventHandler extends EventHandler {} + interface UIEventHandler extends EventHandler {} + interface WheelEventHandler extends EventHandler {} + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + interface Props { + children?: ReactNode; + key?: number | string; + ref?: string; + } + + interface DOMAttributes extends Props { + onCopy?: ClipboardEventHandler; + onCut?: ClipboardEventHandler; + onPaste?: ClipboardEventHandler; + onKeyDown?: KeyboardEventHandler; + onKeyPress?: KeyboardEventHandler; + onKeyUp?: KeyboardEventHandler; + onFocus?: FocusEventHandler; + onBlur?: FocusEventHandler; + onChange?: FormEventHandler; + onInput?: FormEventHandler; + onSubmit?: FormEventHandler; + onClick?: MouseEventHandler; + onDoubleClick?: MouseEventHandler; + onDrag?: MouseEventHandler; + onDragEnd?: MouseEventHandler; + onDragEnter?: MouseEventHandler; + onDragExit?: MouseEventHandler; + onDragLeave?: MouseEventHandler; + onDragOver?: MouseEventHandler; + onDragStart?: MouseEventHandler; + onDrop?: MouseEventHandler; + onMouseDown?: MouseEventHandler; + onMouseEnter?: MouseEventHandler; + onMouseLeave?: MouseEventHandler; + onMouseMove?: MouseEventHandler; + onMouseOut?: MouseEventHandler; + onMouseOver?: MouseEventHandler; + onMouseUp?: MouseEventHandler; + onTouchCancel?: TouchEventHandler; + onTouchEnd?: TouchEventHandler; + onTouchMove?: TouchEventHandler; + onTouchStart?: TouchEventHandler; + onScroll?: UIEventHandler; + onWheel?: WheelEventHandler; + + dangerouslySetInnerHTML?: { + __html: string; + }; + } + + interface CSSProperties { + columnCount?: number; + flex?: number | string; + flexGrow?: number; + flexShrink?: number; + fontWeight?: number; + lineClamp?: number; + lineHeight?: number; + opacity?: number; + order?: number; + orphans?: number; + widows?: number; + zIndex?: number; + zoom?: number; + + // SVG-related properties + fillOpacity?: number; + strokeOpacity?: number; + } + + interface HTMLAttributes extends DOMAttributes { + accept?: string; + acceptCharset?: string; + accessKey?: string; + action?: string; + allowFullScreen?: boolean; + allowTransparency?: boolean; + alt?: string; + async?: boolean; + autoComplete?: boolean; + autoFocus?: boolean; + autoPlay?: boolean; + cellPadding?: number | string; + cellSpacing?: number | string; + charSet?: string; + checked?: boolean; + classID?: string; + className?: string; + cols?: number; + colSpan?: number; + content?: string; + contentEditable?: boolean; + contextMenu?: string; + controls?: any; + coords?: string; + crossOrigin?: string; + data?: string; + dateTime?: string; + defer?: boolean; + dir?: string; + disabled?: boolean; + download?: any; + draggable?: boolean; + encType?: string; + form?: string; + formNoValidate?: boolean; + frameBorder?: number | string; + height?: number | string; + hidden?: boolean; + href?: string; + hrefLang?: string; + htmlFor?: string; + httpEquiv?: string; + icon?: string; + id?: string; + label?: string; + lang?: string; + list?: string; + loop?: boolean; + manifest?: string; + max?: number | string; + maxLength?: number; + media?: string; + mediaGroup?: string; + method?: string; + min?: number | string; + multiple?: boolean; + muted?: boolean; + name?: string; + noValidate?: boolean; + open?: boolean; + pattern?: string; + placeholder?: string; + poster?: string; + preload?: string; + radioGroup?: string; + readOnly?: boolean; + rel?: string; + required?: boolean; + role?: string; + rows?: number; + rowSpan?: number; + sandbox?: string; + scope?: string; + scrollLeft?: number; + scrolling?: string; + scrollTop?: number; + seamless?: boolean; + selected?: boolean; + shape?: string; + size?: number; + sizes?: string; + span?: number; + spellCheck?: boolean; + src?: string; + srcDoc?: string; + srcSet?: string; + start?: number; + step?: number | string; + style?: CSSProperties; + tabIndex?: number; + target?: string; + title?: string; + type?: string; + useMap?: string; + value?: string; + width?: number | string; + wmode?: string; + + // Non-standard Attributes + autoCapitalize?: boolean; + autoCorrect?: boolean; + property?: string; + itemProp?: string; + itemScope?: boolean; + itemType?: string; + } + + interface SVGAttributes extends DOMAttributes { + cx?: SVGLength | SVGAnimatedLength; + cy?: any; + d?: string; + dx?: SVGLength | SVGAnimatedLength; + dy?: SVGLength | SVGAnimatedLength; + fill?: any; // SVGPaint | string + fillOpacity?: number | string; + fontFamily?: string; + fontSize?: number | string; + fx?: SVGLength | SVGAnimatedLength; + fy?: SVGLength | SVGAnimatedLength; + gradientTransform?: SVGTransformList | SVGAnimatedTransformList; + gradientUnits?: string; + markerEnd?: string; + markerMid?: string; + markerStart?: string; + offset?: number | string; + opacity?: number | string; + patternContentUnits?: string; + patternUnits?: string; + points?: string; + preserveAspectRatio?: string; + r?: SVGLength | SVGAnimatedLength; + rx?: SVGLength | SVGAnimatedLength; + ry?: SVGLength | SVGAnimatedLength; + spreadMethod?: string; + stopColor?: any; // SVGColor | string + stopOpacity?: number | string; + stroke?: any; // SVGPaint + strokeDasharray?: string; + strokeLinecap?: string; + strokeOpacity?: number | string; + strokeWidth?: SVGLength | SVGAnimatedLength; + textAnchor?: string; + transform?: SVGTransformList | SVGAnimatedTransformList; + version?: string; + viewBox?: string; + x1?: SVGLength | SVGAnimatedLength; + x2?: SVGLength | SVGAnimatedLength; + x?: SVGLength | SVGAnimatedLength; + y1?: SVGLength | SVGAnimatedLength; + y2?: SVGLength | SVGAnimatedLength + y?: SVGLength | SVGAnimatedLength; + } + + // + // React.DOM + // ---------------------------------------------------------------------- + + interface ReactDOM { + // HTML + a: HTMLFactory; + abbr: HTMLFactory; + address: HTMLFactory; + area: HTMLFactory; + article: HTMLFactory; + aside: HTMLFactory; + audio: HTMLFactory; + b: HTMLFactory; + base: HTMLFactory; + bdi: HTMLFactory; + bdo: HTMLFactory; + big: HTMLFactory; + blockquote: HTMLFactory; + body: HTMLFactory; + br: HTMLFactory; + button: HTMLFactory; + canvas: HTMLFactory; + caption: HTMLFactory; + cite: HTMLFactory; + code: HTMLFactory; + col: HTMLFactory; + colgroup: HTMLFactory; + data: HTMLFactory; + datalist: HTMLFactory; + dd: HTMLFactory; + del: HTMLFactory; + details: HTMLFactory; + dfn: HTMLFactory; + dialog: HTMLFactory; + div: HTMLFactory; + dl: HTMLFactory; + dt: HTMLFactory; + em: HTMLFactory; + embed: HTMLFactory; + fieldset: HTMLFactory; + figcaption: HTMLFactory; + figure: HTMLFactory; + footer: HTMLFactory; + form: HTMLFactory; + h1: HTMLFactory; + h2: HTMLFactory; + h3: HTMLFactory; + h4: HTMLFactory; + h5: HTMLFactory; + h6: HTMLFactory; + head: HTMLFactory; + header: HTMLFactory; + hr: HTMLFactory; + html: HTMLFactory; + i: HTMLFactory; + iframe: HTMLFactory; + img: HTMLFactory; + input: HTMLFactory; + ins: HTMLFactory; + kbd: HTMLFactory; + keygen: HTMLFactory; + label: HTMLFactory; + legend: HTMLFactory; + li: HTMLFactory; + link: HTMLFactory; + main: HTMLFactory; + map: HTMLFactory; + mark: HTMLFactory; + menu: HTMLFactory; + menuitem: HTMLFactory; + meta: HTMLFactory; + meter: HTMLFactory; + nav: HTMLFactory; + noscript: HTMLFactory; + object: HTMLFactory; + ol: HTMLFactory; + optgroup: HTMLFactory; + option: HTMLFactory; + output: HTMLFactory; + p: HTMLFactory; + param: HTMLFactory; + picture: HTMLFactory; + pre: HTMLFactory; + progress: HTMLFactory; + q: HTMLFactory; + rp: HTMLFactory; + rt: HTMLFactory; + ruby: HTMLFactory; + s: HTMLFactory; + samp: HTMLFactory; + script: HTMLFactory; + section: HTMLFactory; + select: HTMLFactory; + small: HTMLFactory; + source: HTMLFactory; + span: HTMLFactory; + strong: HTMLFactory; + style: HTMLFactory; + sub: HTMLFactory; + summary: HTMLFactory; + sup: HTMLFactory; + table: HTMLFactory; + tbody: HTMLFactory; + td: HTMLFactory; + textarea: HTMLFactory; + tfoot: HTMLFactory; + th: HTMLFactory; + thead: HTMLFactory; + time: HTMLFactory; + title: HTMLFactory; + tr: HTMLFactory; + track: HTMLFactory; + u: HTMLFactory; + ul: HTMLFactory; + "var": HTMLFactory; + video: HTMLFactory; + wbr: HTMLFactory; + + // SVG + circle: SVGFactory; + defs: SVGFactory; + ellipse: SVGFactory; + g: SVGFactory; + line: SVGFactory; + linearGradient: SVGFactory; + mask: SVGFactory; + path: SVGFactory; + pattern: SVGFactory; + polygon: SVGFactory; + polyline: SVGFactory; + radialGradient: SVGFactory; + rect: SVGFactory; + stop: SVGFactory; + svg: SVGFactory; + text: SVGFactory; + tspan: SVGFactory; + } + + // + // React.PropTypes + // ---------------------------------------------------------------------- + + interface Validator { + (object: T, key: string, componentName: string): Error; + } + + interface Requireable extends Validator { + isRequired: Validator; + } + + interface ValidationMap { + [key: string]: Validator; + } + + interface ReactPropTypes { + any: Requireable; + array: Requireable; + bool: Requireable; + func: Requireable; + number: Requireable; + object: Requireable; + string: Requireable; + node: Requireable; + element: Requireable; + instanceOf(expectedClass: {}): Requireable; + oneOf(types: any[]): Requireable; + oneOfType(types: Validator[]): Requireable; + arrayOf(type: Validator): Requireable; + objectOf(type: Validator): Requireable; + shape(type: ValidationMap): Requireable; + } + + // + // React.Children + // ---------------------------------------------------------------------- + + interface ReactChildren { + map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; + forEach(children: ReactNode, fn: (child: ReactChild) => any): void; + count(children: ReactNode): number; + only(children: ReactNode): ReactChild; + } + + // + // Browser Interfaces + // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts + // ---------------------------------------------------------------------- + + interface AbstractView { + styleMedia: StyleMedia; + document: Document; + } + + interface Touch { + identifier: number; + target: EventTarget; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + pageX: number; + pageY: number; + } + + interface TouchList { + [index: number]: Touch; + length: number; + item(index: number): Touch; + identifiedTouch(identifier: number): Touch; + } +} + diff --git a/react/future/react-addons-0.13.0-tests.ts b/react/future/react-addons-0.13.0-tests.ts new file mode 100644 index 000000000..a1be24add --- /dev/null +++ b/react/future/react-addons-0.13.0-tests.ts @@ -0,0 +1,387 @@ +/// +import React = require("react/addons"); + +interface Props extends React.Props { + hello: string; + world?: string; + foo: number; + bar: boolean; +} + +interface State { + inputValue?: string; + seconds?: number; +} + +interface Context { + someValue?: string; +} + +interface ChildContext { + someOtherValue: string; +} + +interface MyComponent extends React.Component { + reset(): void; +} + +var props: Props = { + key: 42, + ref: "myComponent42", + hello: "world", + foo: 42, + bar: true +}; + +var container: Element; +var INPUT_REF: string = "input"; + +// +// Top-Level API +// -------------------------------------------------------------------------- + +var ClassicComponent: React.ClassicComponentClass = + React.createClass({ + getDefaultProps: () => { + return { + hello: undefined, + world: "peace", + foo: undefined, + bar: undefined + }; + }, + getInitialState: () => { + return { + inputValue: this.context.someValue, + seconds: this.props.foo + }; + }, + reset: () => { + this.replaceState(this.getInitialState()); + }, + render: () => { + return React.DOM.div(null, + React.DOM.input({ + ref: INPUT_REF, + value: this.state.inputValue + })); + } + }); + +class ModernComponent extends React.Component + implements React.ChildContextProvider { + + constructor(props: Props, context: Context) { + super(props, context); + this.state = { + inputValue: context.someValue, + seconds: props.foo + }; + } + + static propTypes: React.ValidationMap = { + foo: React.PropTypes.number + } + + static contextTypes: React.ValidationMap = { + someValue: React.PropTypes.string + } + + static childContextTypes: React.ValidationMap = { + someOtherValue: React.PropTypes.string + } + + getChildContext() { + return { + someOtherValue: 'foo' + } + } + + state = { + inputValue: this.context.someValue, + seconds: this.props.foo + } + + reset() { + this.setState({ + inputValue: this.context.someValue, + seconds: this.props.foo + }); + } + + render() { + return React.DOM.div(null, + React.DOM.input({ + ref: INPUT_REF, + value: this.state.inputValue + })); + } +} + +// React.createFactory +var factory: React.Factory = + React.createFactory(ModernComponent); +var factoryElement: React.ReactElement = + factory(props); + +var classicFactory: React.ClassicFactory = + React.createFactory(ClassicComponent); +var classicFactoryElement: React.ReactClassicElement = + classicFactory(props); + +var domFactory: React.DOMFactory = + React.createFactory("foo"); +var domFactoryElement: React.ReactDOMElement = + domFactory(); + +// React.createElement +var element: React.ReactElement = + React.createElement(ModernComponent, props); +var classicElement: React.ReactClassicElement = + React.createElement(ClassicComponent, props); +var domElement: React.ReactHTMLElement = + React.createElement("div"); + +// React.render +var component: React.Component = + React.render(element, container); +var classicComponent: React.ClassicComponent = + React.render(classicElement, container); +var domComponent: React.DOMComponent = + React.render(domElement, container); + +// Other Top-Level API +var unmounted: boolean = React.unmountComponentAtNode(container); +var str: string = React.renderToString(element); +var markup: string = React.renderToStaticMarkup(element); +var notValid: boolean = React.isValidElement(props); // false +var isValid = React.isValidElement(element); // true +React.initializeTouchEvents(true); +var domNode: Element = React.findDOMNode(component); +domNode = React.findDOMNode(domNode); + +// +// React Elements +// -------------------------------------------------------------------------- + +var type = element.type; +var elementProps: Props = element.props; +var key = element.key; +var ref: string = element.ref; + +// +// React Components +// -------------------------------------------------------------------------- + +var displayName: string = ClassicComponent.displayName; +var defaultProps: Props = ClassicComponent.getDefaultProps(); +var propTypes: React.ValidationMap = ClassicComponent.propTypes; + +// +// Component API +// -------------------------------------------------------------------------- + +// modern +var componentState: State = component.state; +component.setState({ inputValue: "!!!" }); +component.forceUpdate(); + +// classic +var htmlElement: Element = classicComponent.getDOMNode(); +var divElement: HTMLDivElement = classicComponent.getDOMNode(); +var isMounted: boolean = classicComponent.isMounted(); +classicComponent.setProps(elementProps); +classicComponent.replaceProps(props); +classicComponent.replaceState({ inputValue: "???", seconds: 60 }); + +var inputRef: React.HTMLComponent = + component.refs[INPUT_REF]; +var value: string = inputRef.getDOMNode().value; + +var myComponent = component; +myComponent.reset(); + +// +// Attributes +// -------------------------------------------------------------------------- + +var children = ["Hello world", [null], React.DOM.span(null)]; +var divStyle = { // CSSProperties + flex: "1 1 main-size", + backgroundImage: "url('hello.png')" +}; +var htmlAttr: React.HTMLAttributes = { + key: 36, + ref: "htmlComponent", + children: children, + className: "test-attr", + style: divStyle, + onClick: (event: React.MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + }, + dangerouslySetInnerHTML: { + __html: "STRONG" + } +}; +React.DOM.div(htmlAttr); +React.DOM.span(htmlAttr); +React.DOM.input(htmlAttr); + +// +// React.PropTypes +// -------------------------------------------------------------------------- + +var PropTypesSpecification: React.ComponentSpec = { + propTypes: { + optionalArray: React.PropTypes.array, + optionalBool: React.PropTypes.bool, + optionalFunc: React.PropTypes.func, + optionalNumber: React.PropTypes.number, + optionalObject: React.PropTypes.object, + optionalString: React.PropTypes.string, + optionalNode: React.PropTypes.node, + optionalElement: React.PropTypes.element, + optionalMessage: React.PropTypes.instanceOf(Date), + optionalEnum: React.PropTypes.oneOf(["News", "Photos"]), + optionalUnion: React.PropTypes.oneOfType([ + React.PropTypes.string, + React.PropTypes.number, + React.PropTypes.instanceOf(Date) + ]), + optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), + optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), + optionalObjectWithShape: React.PropTypes.shape({ + color: React.PropTypes.string, + fontSize: React.PropTypes.number + }), + requiredFunc: React.PropTypes.func.isRequired, + requiredAny: React.PropTypes.any.isRequired, + customProp: function(props: any, propName: string, componentName: string) { + if (!/matchme/.test(props[propName])) { + return new Error("Validation failed!"); + } + return null; + } + }, + render: (): React.ReactHTMLElement => { + return null; + } +}; + +// +// ContextTypes +// -------------------------------------------------------------------------- + +var ContextTypesSpecification: React.ComponentSpec = { + contextTypes: { + optionalArray: React.PropTypes.array, + optionalBool: React.PropTypes.bool, + optionalFunc: React.PropTypes.func, + optionalNumber: React.PropTypes.number, + optionalObject: React.PropTypes.object, + optionalString: React.PropTypes.string, + optionalNode: React.PropTypes.node, + optionalElement: React.PropTypes.element, + optionalMessage: React.PropTypes.instanceOf(Date), + optionalEnum: React.PropTypes.oneOf(["News", "Photos"]), + optionalUnion: React.PropTypes.oneOfType([ + React.PropTypes.string, + React.PropTypes.number, + React.PropTypes.instanceOf(Date) + ]), + optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), + optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), + optionalObjectWithShape: React.PropTypes.shape({ + color: React.PropTypes.string, + fontSize: React.PropTypes.number + }), + requiredFunc: React.PropTypes.func.isRequired, + requiredAny: React.PropTypes.any.isRequired, + customProp: function(props: any, propName: string, componentName: string) { + if (!/matchme/.test(props[propName])) { + return new Error("Validation failed!"); + } + return null; + } + }, + render: (): React.ReactHTMLElement => { + return null; + } +}; + +// +// React.Children +// -------------------------------------------------------------------------- + +var childMap: { [key: string]: number } = + React.Children.map(children, (child) => { return 42; }); +React.Children.forEach(children, (child) => {}); +var nChildren: number = React.Children.count(children); +var onlyChild = React.Children.only([null, [[["Hallo"], true]], false]); + +// +// Example from http://facebook.github.io/react/ +// -------------------------------------------------------------------------- + +interface TimerState { + secondsElapsed: number; +} +class Timer extends React.Component<{}, TimerState, {}> { + static state = { + secondsElapsed: 0 + } + private _interval: number; + tick() { + this.setState({ secondsElapsed: this.state.secondsElapsed + 1 }); + } + componentDidMount() { + var me = this; + this._interval = setInterval(() => me.tick(), 1000); + } + componentWillUnmount() { + clearInterval(this._interval); + } + render() { + return React.DOM.div( + null, + "Seconds Elapsed: ", + this.state.secondsElapsed + ); + } +} +React.render(React.createElement(Timer), container); + +// +// React.addons +// -------------------------------------------------------------------------- + +var cx = React.addons.classSet; +var className: string = cx({ a: true, b: false, c: true }); +className = cx("a", null, "b"); + +// +// React.addons (Transitions) +// -------------------------------------------------------------------------- + +React.createFactory(React.addons.TransitionGroup)({ component: "div" }); +React.createFactory(React.addons.CSSTransitionGroup)({ + component: React.createClass({ + render: (): React.ReactElement => null + }), + childFactory: (c) => c, + transitionName: "transition", + transitionAppear: false, + transitionEnter: true, + transitionLeave: true +}); + +// +// React.addons.TestUtils +// -------------------------------------------------------------------------- + +var node: Element; +React.addons.TestUtils.Simulate.click(node); +React.addons.TestUtils.Simulate.change(node); +React.addons.TestUtils.Simulate.keyDown(node, { key: "Enter" }); + diff --git a/react/react-0.13.0.d.ts b/react/future/react-addons-0.13.0.d.ts similarity index 79% rename from react/react-0.13.0.d.ts rename to react/future/react-addons-0.13.0.d.ts index 9ee102541..dd06aa1e9 100644 --- a/react/react-0.13.0.d.ts +++ b/react/future/react-addons-0.13.0.d.ts @@ -1,42 +1,179 @@ -// Type definitions for React 0.13.0 +// Type definitions for ReactWithAddons v0.13.0 (external module) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module React { +declare module "react/addons" { // - // React Elements + // React Elements // ---------------------------------------------------------------------- - - type ReactType = ComponentClass | string; - interface ReactElement

{ - type: ComponentClass | string; + interface ReactElementBase { + type: T; props: P; key: number | string; ref: string; } - interface ReactClassicElement

extends ReactElement

{ - } + interface ReactElement

+ extends ReactElementBase, P> {} - interface ReactHTMLElement extends ReactElement {} - interface ReactSVGElement extends ReactElement {} + interface ReactClassicElement

+ extends ReactElementBase | string, P> {} + + interface ReactDOMElement

// subtype of ReactClassicElement + extends ReactElementBase {} + + type ReactHTMLElement = ReactDOMElement; + type ReactSVGElement = ReactDOMElement; // - // React Nodes + // Factories + // ---------------------------------------------------------------------- + + interface Factory

{ + (props?: P, ...children: ReactNode[]): ReactElement

; + } + + interface ClassicFactory

{ + (props?: P, ...children: ReactNode[]): ReactClassicElement

; + } + + interface DOMFactory

{ + (props?: P, ...children: ReactNode[]): ReactDOMElement

; + } + + type HTMLFactory = DOMFactory; + type SVGFactory = DOMFactory; + + // + // React Nodes // http://facebook.github.io/react/docs/glossary.html // ---------------------------------------------------------------------- type ReactText = string | number; - type ReactChild = ReactElement | ReactText; + type ReactChild = ReactElementBase | ReactText; // Should be Array but type aliases cannot be recursive type ReactFragment = Array; type ReactNode = ReactChild | ReactFragment | boolean; // - // React Components + // Top Level API + // ---------------------------------------------------------------------- + + function createClass( + spec: ComponentSpec): ClassicComponentClass; + + function createFactory

( + type: string): DOMFactory

; + function createFactory

( + type: ClassicComponentClass | string): ClassicFactory

; + function createFactory

( + type: ComponentClass): Factory

; + + function createElement

( + type: string, + props?: P, + ...children: ReactNode[]): ReactDOMElement

; + function createElement

( + type: ClassicComponentClass | string, + props?: P, + ...children: ReactNode[]): ReactClassicElement

; + function createElement

( + type: ComponentClass, + props?: P, + ...children: ReactNode[]): ReactElement

; + + function render

( + element: ReactDOMElement

, + container: Element, + callback?: () => any): DOMComponent

; + function render( + element: ReactClassicElement

, + container: Element, + callback?: () => any): ClassicComponent; + function render( + element: ReactElement

, + container: Element, + callback?: () => any): Component; + + function unmountComponentAtNode(container: Element): boolean; + function renderToString(element: ReactElementBase): string; + function renderToStaticMarkup(element: ReactElementBase): string; + function isValidElement(object: {}): boolean; + function initializeTouchEvents(shouldUseTouch: boolean): void; + + function findDOMNode( + componentOrElement: Component | Element): TElement; + function findDOMNode( + componentOrElement: Component | Element): Element; + + var DOM: ReactDOM; + var PropTypes: ReactPropTypes; + var Children: ReactChildren; + + // + // Component API + // ---------------------------------------------------------------------- + + // Base component for plain JS classes + class Component implements ComponentLifecycle { + constructor(props: P, context: C); + setState(state: S, callback?: () => any): void; + forceUpdate(): void; + props: P; + state: S; + context: C; + refs: { + [key: string]: Component + }; + } + + interface ClassicComponent extends Component { + replaceState(nextState: S, callback?: () => any): void; + getDOMNode(): TElement; + getDOMNode(): Element; + isMounted(): boolean; + getInitialState?(): S; + setProps(nextProps: P, callback?: () => any): void; + replaceProps(nextProps: P, callback?: () => any): void; + } + + interface DOMComponent

extends ClassicComponent { + tagName: string; + } + + type HTMLComponent = DOMComponent; + type SVGComponent = DOMComponent; + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + interface ComponentClassBase { + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap<{}>; + } + + interface ComponentClass extends ComponentClassBase { + new(props?: P, context?: C): Component; + defaultProps?: P; + } + + interface ClassicComponentClass extends ComponentClassBase { + new(props?: P, context?: C): ClassicComponent; + getDefaultProps?(): P; + displayName?: string; + } + + // + // Component Specs and Lifecycle // ---------------------------------------------------------------------- interface ComponentLifecycle { @@ -48,102 +185,7 @@ declare module React { componentDidUpdate?(prevProps: P, prevState: S, prevContext: C): void; componentWillUnmount?(): void; } - - // "modern" ES6 classes - class Component implements ComponentLifecycle { - constructor(props: P, context: C); - // static members can't be type checked with generics. However, see ComponentClass - static defaultProps: any; - static propTypes: ValidationMap; - static contextTypes: ValidationMap; - static childContextTypes: ValidationMap; - static displayName: string; - setState(state: S, callback?: () => any): void; - forceUpdate(): void; - props: P; - state: S; - context: C; - refs: { - [key: string]: Component - }; - } - - interface ComponentClass { - new (props: P, context: C): Component; - // can cast to get type checking for generics if desired - defaultProps: P; - getDefaultProps?(): P; - propTypes: ValidationMap

; - contextTypes: ValidationMap; - childContextTypes: ValidationMap; - displayName: string; - } - - // "classic" createClass - class ClassicComponent extends Component { - replaceState(nextState: S, callback?: () => any): void; - getDOMNode(): TElement; - getDOMNode(): Element; - isMounted(): boolean; - getInitialState(): S; - setProps(nextProps: P, callback?: () => any): void; - replaceProps(nextProps: P, callback?: () => any): void; - } - - interface ClassicComponentClass extends ComponentClass { - new (props: P, context: C): ClassicComponent; - } - - interface ChildContextProvider { - getChildContext: () => C; - } - - // - // ReactElement Factories - // ---------------------------------------------------------------------- - interface ComponentFactory

{ - (props?: P, ...children: ReactNode[]): ReactElement

; - } - - interface HTMLFactory extends ComponentFactory {} - interface SVGFactory extends ComponentFactory {} - - // - // Top-Level API - // ---------------------------------------------------------------------- - - interface TopLevelAPI { - createClass(spec: ComponentSpec): ClassicComponentClass; - createElement

(type: ClassicComponentClass, props: P, ...children: ReactNode[]): ReactClassicElement

; - createElement

(type: ComponentClass | string, props: P, ...children: ReactNode[]): ReactElement

; - createFactory

(type: ComponentClass | string): ComponentFactory

; - render(element: ReactClassicElement

, container: Element, callback?: () => any): ClassicComponent; - render(element: ReactElement

, container: Element, callback?: () => any): Component; - unmountComponentAtNode(container: Element): boolean; - renderToString(element: ReactElement): string; - renderToStaticMarkup(element: ReactElement): string; - isValidElement(object: {}): boolean; - initializeTouchEvents(shouldUseTouch: boolean): void; - findDOMNode(component: Component): Element; - findDOMNode(component: Component): TElement; - } - - // - // Component API - // ---------------------------------------------------------------------- - - class DOMComponent

extends ClassicComponent { - tagName: string; - } - - interface HTMLComponent extends DOMComponent {} - interface SVGComponent extends DOMComponent {} - - // - // Component Specs and Lifecycle - // ---------------------------------------------------------------------- - interface Mixin extends ComponentLifecycle { mixins?: Mixin; statics?: { @@ -154,13 +196,13 @@ declare module React { propTypes?: ValidationMap; contextTypes?: ValidationMap; childContextTypes?: ValidationMap - + getInitialState?(): S; getDefaultProps?(): P; } interface ComponentSpec extends Mixin { - render(): ReactElement; + render(): ReactElementBase; } // @@ -266,15 +308,16 @@ declare module React { interface WheelEventHandler extends EventHandler {} // - // Attributes + // Props / DOM Attributes // ---------------------------------------------------------------------- - interface ReactAttributes { + interface Props { children?: ReactNode; key?: number | string; ref?: string; + } - // Event Attributes + interface DOMAttributes extends Props { onCopy?: ClipboardEventHandler; onCut?: ClipboardEventHandler; onPaste?: ClipboardEventHandler; @@ -335,7 +378,7 @@ declare module React { strokeOpacity?: number; } - interface HTMLAttributes extends ReactAttributes { + interface HTMLAttributes extends DOMAttributes { accept?: string; acceptCharset?: string; accessKey?: string; @@ -443,9 +486,9 @@ declare module React { itemType?: string; } - interface SVGAttributes extends ReactAttributes { + interface SVGAttributes extends DOMAttributes { cx?: SVGLength | SVGAnimatedLength; - cy?: any; + cy?: any; d?: string; dx?: SVGLength | SVGAnimatedLength; dy?: SVGLength | SVGAnimatedLength; @@ -490,7 +533,7 @@ declare module React { } // - // React.DOM + // React.DOM // ---------------------------------------------------------------------- interface ReactDOM { @@ -677,14 +720,36 @@ declare module React { // React.addons // ---------------------------------------------------------------------- - interface ClassSet { - [key: string]: boolean; - } + export var addons: { + CSSTransitionGroup: CSSTransitionGroup; + LinkedStateMixin: LinkedStateMixin; + PureRenderMixin: PureRenderMixin; + TransitionGroup: TransitionGroup; + + batchedUpdates(callback: (a: A, b: B) => any, a: A, b: B): void; + batchedUpdates(callback: (a: A) => any, a: A): void; + batchedUpdates(callback: () => any): void; + + // deprecated: use petehunt/react-classset or JedWatson/classnames + classSet(cx: { [key: string]: boolean }): string; + classSet(...classList: string[]): string; + + cloneWithProps

(element: ReactElement

, props: P): ReactElement

; + + update(value: any[], spec: UpdateArraySpec): any[]; + update(value: {}, spec: UpdateSpec): any; + + // Development tools + Perf: ReactPerf; + TestUtils: ReactTestUtils; + }; // // React.addons (Transitions) // ---------------------------------------------------------------------- + type ReactType = ComponentClass | string; + interface TransitionGroupProps { component?: ReactType; childFactory?: (child: ReactElement) => ReactElement; @@ -697,8 +762,10 @@ declare module React { transitionLeave?: boolean; } - interface CSSTransitionGroup extends ComponentClass {} - interface TransitionGroup extends ComponentClass {} + type CSSTransitionGroup = + ComponentClass; + type TransitionGroup = + ComponentClass; // // React.addons (Mixins) @@ -785,28 +852,44 @@ declare module React { mockComponent(mocked: MockedComponentClass, mockTagName?: string): ReactTestUtils; isElementOfType(element: ReactElement, type: ReactType): boolean; + isTextComponent(instance: Component): boolean; isDOMComponent(instance: Component): boolean; isCompositeComponent(instance: Component): boolean; - isCompositeComponentWithType(instance: Component, type: ComponentClass): boolean; - isTextComponent(instance: Component): boolean; + isCompositeComponentWithType( + instance: Component, + type: ComponentClass): boolean; - findAllInRenderedTree(tree: Component, fn: (i: Component) => boolean): Component; + findAllInRenderedTree( + tree: Component, + fn: (i: Component) => boolean): Component; - scryRenderedDOMComponentsWithClass(tree: Component, className: string): DOMComponent[]; - findRenderedDOMComponentWithClass(tree: Component, className: string): DOMComponent; + scryRenderedDOMComponentsWithClass( + tree: Component, + className: string): DOMComponent[]; + findRenderedDOMComponentWithClass( + tree: Component, + className: string): DOMComponent; - scryRenderedDOMComponentsWithTag(tree: Component, tagName: string): DOMComponent[]; - findRenderedDOMComponentWithTag(tree: Component, tagName: string): DOMComponent; + scryRenderedDOMComponentsWithTag( + tree: Component, + tagName: string): DOMComponent[]; + findRenderedDOMComponentWithTag( + tree: Component, + tagName: string): DOMComponent; scryRenderedComponentsWithType( - tree: Component, type: ComponentClass): Component[]; + tree: Component, + type: ComponentClass): Component[]; scryRenderedComponentsWithType>( - tree: Component, type: ComponentClass): C[]; + tree: Component, + type: ComponentClass): C[]; findRenderedComponentWithType( - tree: Component, type: ComponentClass): Component; + tree: Component, + type: ComponentClass): Component; findRenderedComponentWithType>( - tree: Component, type: ComponentClass): C; + tree: Component, + type: ComponentClass): C; } interface SyntheticEventData { @@ -884,44 +967,6 @@ declare module React { wheel: EventSimulator; } - // - // react Exports - // ---------------------------------------------------------------------- - - interface Exports extends TopLevelAPI { - DOM: ReactDOM; - PropTypes: ReactPropTypes; - Children: ReactChildren; - Component: ComponentClass; - } - - // - // react/addons Exports - // ---------------------------------------------------------------------- - - interface AddonsExports extends Exports { - addons: { - CSSTransitionGroup: CSSTransitionGroup; - LinkedStateMixin: LinkedStateMixin; - PureRenderMixin: PureRenderMixin; - TransitionGroup: TransitionGroup; - - batchedUpdates(callback: (a: A, b: B) => any, a: A, b: B): void; - batchedUpdates(callback: (a: A) => any, a: A): void; - batchedUpdates(callback: () => any): void; - - classSet(cx: ClassSet): string; - cloneWithProps

(element: ReactElement

, props: P): ReactElement

; - - update(value: any[], spec: UpdateArraySpec): any[]; - update(value: {}, spec: UpdateSpec): any; - - // Development tools - Perf: ReactPerf; - TestUtils: ReactTestUtils; - }; - } - // // Browser Interfaces // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts @@ -951,13 +996,3 @@ declare module React { } } -declare module "react" { - var exports: React.Exports; - export = exports; -} - -declare module "react/addons" { - var exports: React.AddonsExports; - export = exports; -} - diff --git a/react/future/react-addons-global-0.13.0.d.ts b/react/future/react-addons-global-0.13.0.d.ts new file mode 100644 index 000000000..733ba54a5 --- /dev/null +++ b/react/future/react-addons-global-0.13.0.d.ts @@ -0,0 +1,259 @@ +// Type definitions for ReactWithAddons v0.13.0 (internal module) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + +declare module React { + // + // React.addons + // ---------------------------------------------------------------------- + + export var addons: { + CSSTransitionGroup: CSSTransitionGroup; + LinkedStateMixin: LinkedStateMixin; + PureRenderMixin: PureRenderMixin; + TransitionGroup: TransitionGroup; + + batchedUpdates(callback: (a: A, b: B) => any, a: A, b: B): void; + batchedUpdates(callback: (a: A) => any, a: A): void; + batchedUpdates(callback: () => any): void; + + // deprecated: use petehunt/react-classset or JedWatson/classnames + classSet(cx: { [key: string]: boolean }): string; + classSet(...classList: string[]): string; + + cloneWithProps

(element: ReactElement

, props: P): ReactElement

; + + update(value: any[], spec: UpdateArraySpec): any[]; + update(value: {}, spec: UpdateSpec): any; + + // Development tools + Perf: ReactPerf; + TestUtils: ReactTestUtils; + }; + + // + // React.addons (Transitions) + // ---------------------------------------------------------------------- + + type ReactType = ComponentClass | string; + + interface TransitionGroupProps { + component?: ReactType; + childFactory?: (child: ReactElement) => ReactElement; + } + + interface CSSTransitionGroupProps extends TransitionGroupProps { + transitionName: string; + transitionAppear?: boolean; + transitionEnter?: boolean; + transitionLeave?: boolean; + } + + type CSSTransitionGroup = + ComponentClass; + type TransitionGroup = + ComponentClass; + + // + // React.addons (Mixins) + // ---------------------------------------------------------------------- + + interface ReactLink { + value: T; + requestChange(newValue: T): void; + } + + interface LinkedStateMixin extends Mixin { + linkState(key: string): ReactLink; + } + + interface PureRenderMixin extends Mixin { + } + + // + // Reat.addons.update + // ---------------------------------------------------------------------- + + interface UpdateSpec { + $set: any; + $merge: {}; + $apply(value: any): any; + // [key: string]: UpdateSpec; + } + + interface UpdateArraySpec extends UpdateSpec { + $push?: any[]; + $unshift?: any[]; + $splice?: any[][]; + } + + // + // React.addons.Perf + // ---------------------------------------------------------------------- + + interface ComponentPerfContext { + current: string; + owner: string; + } + + interface NumericPerfContext { + [key: string]: number; + } + + interface Measurements { + exclusive: NumericPerfContext; + inclusive: NumericPerfContext; + render: NumericPerfContext; + counts: NumericPerfContext; + writes: NumericPerfContext; + displayNames: { + [key: string]: ComponentPerfContext; + }; + totalTime: number; + } + + interface ReactPerf { + start(): void; + stop(): void; + printInclusive(measurements: Measurements[]): void; + printExclusive(measurements: Measurements[]): void; + printWasted(measurements: Measurements[]): void; + printDOM(measurements: Measurements[]): void; + getLastMeasurements(): Measurements[]; + } + + // + // React.addons.TestUtils + // ---------------------------------------------------------------------- + + interface MockedComponentClass { + new(): any; + } + + interface ReactTestUtils { + Simulate: Simulate; + + renderIntoDocument

(element: ReactElement

): Component; + renderIntoDocument>(element: ReactElement): C; + + mockComponent(mocked: MockedComponentClass, mockTagName?: string): ReactTestUtils; + + isElementOfType(element: ReactElement, type: ReactType): boolean; + isTextComponent(instance: Component): boolean; + isDOMComponent(instance: Component): boolean; + isCompositeComponent(instance: Component): boolean; + isCompositeComponentWithType( + instance: Component, + type: ComponentClass): boolean; + + findAllInRenderedTree( + tree: Component, + fn: (i: Component) => boolean): Component; + + scryRenderedDOMComponentsWithClass( + tree: Component, + className: string): DOMComponent[]; + findRenderedDOMComponentWithClass( + tree: Component, + className: string): DOMComponent; + + scryRenderedDOMComponentsWithTag( + tree: Component, + tagName: string): DOMComponent[]; + findRenderedDOMComponentWithTag( + tree: Component, + tagName: string): DOMComponent; + + scryRenderedComponentsWithType( + tree: Component, + type: ComponentClass): Component[]; + scryRenderedComponentsWithType>( + tree: Component, + type: ComponentClass): C[]; + + findRenderedComponentWithType( + tree: Component, + type: ComponentClass): Component; + findRenderedComponentWithType>( + tree: Component, + type: ComponentClass): C; + } + + interface SyntheticEventData { + altKey?: boolean; + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + changedTouches?: TouchList; + charCode?: boolean; + clipboardData?: DataTransfer; + ctrlKey?: boolean; + deltaMode?: number; + deltaX?: number; + deltaY?: number; + deltaZ?: number; + detail?: number; + getModifierState?(key: string): boolean; + key?: string; + keyCode?: number; + locale?: string; + location?: number; + metaKey?: boolean; + pageX?: number; + pageY?: number; + relatedTarget?: EventTarget; + repeat?: boolean; + screenX?: number; + screenY?: number; + shiftKey?: boolean; + targetTouches?: TouchList; + touches?: TouchList; + view?: AbstractView; + which?: number; + } + + interface EventSimulator { + (element: Element, eventData?: SyntheticEventData): void; + (descriptor: Component, eventData?: SyntheticEventData): void; + } + + interface Simulate { + blur: EventSimulator; + change: EventSimulator; + click: EventSimulator; + cut: EventSimulator; + doubleClick: EventSimulator; + drag: EventSimulator; + dragEnd: EventSimulator; + dragEnter: EventSimulator; + dragExit: EventSimulator; + dragLeave: EventSimulator; + dragOver: EventSimulator; + dragStart: EventSimulator; + drop: EventSimulator; + focus: EventSimulator; + input: EventSimulator; + keyDown: EventSimulator; + keyPress: EventSimulator; + keyUp: EventSimulator; + mouseDown: EventSimulator; + mouseEnter: EventSimulator; + mouseLeave: EventSimulator; + mouseMove: EventSimulator; + mouseOut: EventSimulator; + mouseOver: EventSimulator; + mouseUp: EventSimulator; + paste: EventSimulator; + scroll: EventSimulator; + submit: EventSimulator; + touchCancel: EventSimulator; + touchEnd: EventSimulator; + touchMove: EventSimulator; + touchStart: EventSimulator; + wheel: EventSimulator; + } +} + diff --git a/react/future/react-global-0.13.0.d.ts b/react/future/react-global-0.13.0.d.ts new file mode 100644 index 000000000..996d09d3a --- /dev/null +++ b/react/future/react-global-0.13.0.d.ts @@ -0,0 +1,747 @@ +// Type definitions for React v0.13.0 (internal module) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module React { + // + // React Elements + // ---------------------------------------------------------------------- + + interface ReactElementBase { + type: T; + props: P; + key: number | string; + ref: string; + } + + interface ReactElement

+ extends ReactElementBase, P> {} + + interface ReactClassicElement

+ extends ReactElementBase | string, P> {} + + interface ReactDOMElement

// subtype of ReactClassicElement + extends ReactElementBase {} + + type ReactHTMLElement = ReactDOMElement; + type ReactSVGElement = ReactDOMElement; + + // + // Factories + // ---------------------------------------------------------------------- + + interface Factory

{ + (props?: P, ...children: ReactNode[]): ReactElement

; + } + + interface ClassicFactory

{ + (props?: P, ...children: ReactNode[]): ReactClassicElement

; + } + + interface DOMFactory

{ + (props?: P, ...children: ReactNode[]): ReactDOMElement

; + } + + type HTMLFactory = DOMFactory; + type SVGFactory = DOMFactory; + + // + // React Nodes + // http://facebook.github.io/react/docs/glossary.html + // ---------------------------------------------------------------------- + + type ReactText = string | number; + type ReactChild = ReactElementBase | ReactText; + + // Should be Array but type aliases cannot be recursive + type ReactFragment = Array; + type ReactNode = ReactChild | ReactFragment | boolean; + + // + // Top Level API + // ---------------------------------------------------------------------- + + function createClass( + spec: ComponentSpec): ClassicComponentClass; + + function createFactory

( + type: string): DOMFactory

; + function createFactory

( + type: ClassicComponentClass | string): ClassicFactory

; + function createFactory

( + type: ComponentClass): Factory

; + + function createElement

( + type: string, + props?: P, + ...children: ReactNode[]): ReactDOMElement

; + function createElement

( + type: ClassicComponentClass | string, + props?: P, + ...children: ReactNode[]): ReactClassicElement

; + function createElement

( + type: ComponentClass, + props?: P, + ...children: ReactNode[]): ReactElement

; + + function render

( + element: ReactDOMElement

, + container: Element, + callback?: () => any): DOMComponent

; + function render( + element: ReactClassicElement

, + container: Element, + callback?: () => any): ClassicComponent; + function render( + element: ReactElement

, + container: Element, + callback?: () => any): Component; + + function unmountComponentAtNode(container: Element): boolean; + function renderToString(element: ReactElementBase): string; + function renderToStaticMarkup(element: ReactElementBase): string; + function isValidElement(object: {}): boolean; + function initializeTouchEvents(shouldUseTouch: boolean): void; + + function findDOMNode( + componentOrElement: Component | Element): TElement; + function findDOMNode( + componentOrElement: Component | Element): Element; + + var DOM: ReactDOM; + var PropTypes: ReactPropTypes; + var Children: ReactChildren; + + // + // Component API + // ---------------------------------------------------------------------- + + // Base component for plain JS classes + class Component implements ComponentLifecycle { + constructor(props: P, context: C); + setState(state: S, callback?: () => any): void; + forceUpdate(): void; + props: P; + state: S; + context: C; + refs: { + [key: string]: Component + }; + } + + interface ClassicComponent extends Component { + replaceState(nextState: S, callback?: () => any): void; + getDOMNode(): TElement; + getDOMNode(): Element; + isMounted(): boolean; + getInitialState?(): S; + setProps(nextProps: P, callback?: () => any): void; + replaceProps(nextProps: P, callback?: () => any): void; + } + + interface DOMComponent

extends ClassicComponent { + tagName: string; + } + + type HTMLComponent = DOMComponent; + type SVGComponent = DOMComponent; + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + interface ComponentClassBase { + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap<{}>; + } + + interface ComponentClass extends ComponentClassBase { + new(props?: P, context?: C): Component; + defaultProps?: P; + } + + interface ClassicComponentClass extends ComponentClassBase { + new(props?: P, context?: C): ClassicComponent; + getDefaultProps?(): P; + displayName?: string; + } + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + interface ComponentLifecycle { + componentWillMount?(): void; + componentDidMount?(): void; + componentWillReceiveProps?(nextProps: P, nextContext: C): void; + shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: C): boolean; + componentWillUpdate?(nextProps: P, nextState: S, nextContext: C): void; + componentDidUpdate?(prevProps: P, prevState: S, prevContext: C): void; + componentWillUnmount?(): void; + } + + interface Mixin extends ComponentLifecycle { + mixins?: Mixin; + statics?: { + [key: string]: any; + }; + + displayName?: string; + propTypes?: ValidationMap; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap + + getInitialState?(): S; + getDefaultProps?(): P; + } + + interface ComponentSpec extends Mixin { + render(): ReactElementBase; + } + + // + // Event System + // ---------------------------------------------------------------------- + + interface SyntheticEvent { + bubbles: boolean; + cancelable: boolean; + currentTarget: EventTarget; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + nativeEvent: Event; + preventDefault(): void; + stopPropagation(): void; + target: EventTarget; + timeStamp: Date; + type: string; + } + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + } + + interface KeyboardEvent extends SyntheticEvent { + altKey: boolean; + charCode: number; + ctrlKey: boolean; + getModifierState(key: string): boolean; + key: string; + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + repeat: boolean; + shiftKey: boolean; + which: number; + } + + interface FocusEvent extends SyntheticEvent { + relatedTarget: EventTarget; + } + + interface FormEvent extends SyntheticEvent { + } + + interface MouseEvent extends SyntheticEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + pageX: number; + pageY: number; + relatedTarget: EventTarget; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends SyntheticEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + view: AbstractView; + } + + interface WheelEvent extends SyntheticEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + interface EventHandler { + (event: E): void; + } + + interface ClipboardEventHandler extends EventHandler {} + interface KeyboardEventHandler extends EventHandler {} + interface FocusEventHandler extends EventHandler {} + interface FormEventHandler extends EventHandler {} + interface MouseEventHandler extends EventHandler {} + interface TouchEventHandler extends EventHandler {} + interface UIEventHandler extends EventHandler {} + interface WheelEventHandler extends EventHandler {} + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + interface Props { + children?: ReactNode; + key?: number | string; + ref?: string; + } + + interface DOMAttributes extends Props { + onCopy?: ClipboardEventHandler; + onCut?: ClipboardEventHandler; + onPaste?: ClipboardEventHandler; + onKeyDown?: KeyboardEventHandler; + onKeyPress?: KeyboardEventHandler; + onKeyUp?: KeyboardEventHandler; + onFocus?: FocusEventHandler; + onBlur?: FocusEventHandler; + onChange?: FormEventHandler; + onInput?: FormEventHandler; + onSubmit?: FormEventHandler; + onClick?: MouseEventHandler; + onDoubleClick?: MouseEventHandler; + onDrag?: MouseEventHandler; + onDragEnd?: MouseEventHandler; + onDragEnter?: MouseEventHandler; + onDragExit?: MouseEventHandler; + onDragLeave?: MouseEventHandler; + onDragOver?: MouseEventHandler; + onDragStart?: MouseEventHandler; + onDrop?: MouseEventHandler; + onMouseDown?: MouseEventHandler; + onMouseEnter?: MouseEventHandler; + onMouseLeave?: MouseEventHandler; + onMouseMove?: MouseEventHandler; + onMouseOut?: MouseEventHandler; + onMouseOver?: MouseEventHandler; + onMouseUp?: MouseEventHandler; + onTouchCancel?: TouchEventHandler; + onTouchEnd?: TouchEventHandler; + onTouchMove?: TouchEventHandler; + onTouchStart?: TouchEventHandler; + onScroll?: UIEventHandler; + onWheel?: WheelEventHandler; + + dangerouslySetInnerHTML?: { + __html: string; + }; + } + + interface CSSProperties { + columnCount?: number; + flex?: number | string; + flexGrow?: number; + flexShrink?: number; + fontWeight?: number; + lineClamp?: number; + lineHeight?: number; + opacity?: number; + order?: number; + orphans?: number; + widows?: number; + zIndex?: number; + zoom?: number; + + // SVG-related properties + fillOpacity?: number; + strokeOpacity?: number; + } + + interface HTMLAttributes extends DOMAttributes { + accept?: string; + acceptCharset?: string; + accessKey?: string; + action?: string; + allowFullScreen?: boolean; + allowTransparency?: boolean; + alt?: string; + async?: boolean; + autoComplete?: boolean; + autoFocus?: boolean; + autoPlay?: boolean; + cellPadding?: number | string; + cellSpacing?: number | string; + charSet?: string; + checked?: boolean; + classID?: string; + className?: string; + cols?: number; + colSpan?: number; + content?: string; + contentEditable?: boolean; + contextMenu?: string; + controls?: any; + coords?: string; + crossOrigin?: string; + data?: string; + dateTime?: string; + defer?: boolean; + dir?: string; + disabled?: boolean; + download?: any; + draggable?: boolean; + encType?: string; + form?: string; + formNoValidate?: boolean; + frameBorder?: number | string; + height?: number | string; + hidden?: boolean; + href?: string; + hrefLang?: string; + htmlFor?: string; + httpEquiv?: string; + icon?: string; + id?: string; + label?: string; + lang?: string; + list?: string; + loop?: boolean; + manifest?: string; + max?: number | string; + maxLength?: number; + media?: string; + mediaGroup?: string; + method?: string; + min?: number | string; + multiple?: boolean; + muted?: boolean; + name?: string; + noValidate?: boolean; + open?: boolean; + pattern?: string; + placeholder?: string; + poster?: string; + preload?: string; + radioGroup?: string; + readOnly?: boolean; + rel?: string; + required?: boolean; + role?: string; + rows?: number; + rowSpan?: number; + sandbox?: string; + scope?: string; + scrollLeft?: number; + scrolling?: string; + scrollTop?: number; + seamless?: boolean; + selected?: boolean; + shape?: string; + size?: number; + sizes?: string; + span?: number; + spellCheck?: boolean; + src?: string; + srcDoc?: string; + srcSet?: string; + start?: number; + step?: number | string; + style?: CSSProperties; + tabIndex?: number; + target?: string; + title?: string; + type?: string; + useMap?: string; + value?: string; + width?: number | string; + wmode?: string; + + // Non-standard Attributes + autoCapitalize?: boolean; + autoCorrect?: boolean; + property?: string; + itemProp?: string; + itemScope?: boolean; + itemType?: string; + } + + interface SVGAttributes extends DOMAttributes { + cx?: SVGLength | SVGAnimatedLength; + cy?: any; + d?: string; + dx?: SVGLength | SVGAnimatedLength; + dy?: SVGLength | SVGAnimatedLength; + fill?: any; // SVGPaint | string + fillOpacity?: number | string; + fontFamily?: string; + fontSize?: number | string; + fx?: SVGLength | SVGAnimatedLength; + fy?: SVGLength | SVGAnimatedLength; + gradientTransform?: SVGTransformList | SVGAnimatedTransformList; + gradientUnits?: string; + markerEnd?: string; + markerMid?: string; + markerStart?: string; + offset?: number | string; + opacity?: number | string; + patternContentUnits?: string; + patternUnits?: string; + points?: string; + preserveAspectRatio?: string; + r?: SVGLength | SVGAnimatedLength; + rx?: SVGLength | SVGAnimatedLength; + ry?: SVGLength | SVGAnimatedLength; + spreadMethod?: string; + stopColor?: any; // SVGColor | string + stopOpacity?: number | string; + stroke?: any; // SVGPaint + strokeDasharray?: string; + strokeLinecap?: string; + strokeOpacity?: number | string; + strokeWidth?: SVGLength | SVGAnimatedLength; + textAnchor?: string; + transform?: SVGTransformList | SVGAnimatedTransformList; + version?: string; + viewBox?: string; + x1?: SVGLength | SVGAnimatedLength; + x2?: SVGLength | SVGAnimatedLength; + x?: SVGLength | SVGAnimatedLength; + y1?: SVGLength | SVGAnimatedLength; + y2?: SVGLength | SVGAnimatedLength + y?: SVGLength | SVGAnimatedLength; + } + + // + // React.DOM + // ---------------------------------------------------------------------- + + interface ReactDOM { + // HTML + a: HTMLFactory; + abbr: HTMLFactory; + address: HTMLFactory; + area: HTMLFactory; + article: HTMLFactory; + aside: HTMLFactory; + audio: HTMLFactory; + b: HTMLFactory; + base: HTMLFactory; + bdi: HTMLFactory; + bdo: HTMLFactory; + big: HTMLFactory; + blockquote: HTMLFactory; + body: HTMLFactory; + br: HTMLFactory; + button: HTMLFactory; + canvas: HTMLFactory; + caption: HTMLFactory; + cite: HTMLFactory; + code: HTMLFactory; + col: HTMLFactory; + colgroup: HTMLFactory; + data: HTMLFactory; + datalist: HTMLFactory; + dd: HTMLFactory; + del: HTMLFactory; + details: HTMLFactory; + dfn: HTMLFactory; + dialog: HTMLFactory; + div: HTMLFactory; + dl: HTMLFactory; + dt: HTMLFactory; + em: HTMLFactory; + embed: HTMLFactory; + fieldset: HTMLFactory; + figcaption: HTMLFactory; + figure: HTMLFactory; + footer: HTMLFactory; + form: HTMLFactory; + h1: HTMLFactory; + h2: HTMLFactory; + h3: HTMLFactory; + h4: HTMLFactory; + h5: HTMLFactory; + h6: HTMLFactory; + head: HTMLFactory; + header: HTMLFactory; + hr: HTMLFactory; + html: HTMLFactory; + i: HTMLFactory; + iframe: HTMLFactory; + img: HTMLFactory; + input: HTMLFactory; + ins: HTMLFactory; + kbd: HTMLFactory; + keygen: HTMLFactory; + label: HTMLFactory; + legend: HTMLFactory; + li: HTMLFactory; + link: HTMLFactory; + main: HTMLFactory; + map: HTMLFactory; + mark: HTMLFactory; + menu: HTMLFactory; + menuitem: HTMLFactory; + meta: HTMLFactory; + meter: HTMLFactory; + nav: HTMLFactory; + noscript: HTMLFactory; + object: HTMLFactory; + ol: HTMLFactory; + optgroup: HTMLFactory; + option: HTMLFactory; + output: HTMLFactory; + p: HTMLFactory; + param: HTMLFactory; + picture: HTMLFactory; + pre: HTMLFactory; + progress: HTMLFactory; + q: HTMLFactory; + rp: HTMLFactory; + rt: HTMLFactory; + ruby: HTMLFactory; + s: HTMLFactory; + samp: HTMLFactory; + script: HTMLFactory; + section: HTMLFactory; + select: HTMLFactory; + small: HTMLFactory; + source: HTMLFactory; + span: HTMLFactory; + strong: HTMLFactory; + style: HTMLFactory; + sub: HTMLFactory; + summary: HTMLFactory; + sup: HTMLFactory; + table: HTMLFactory; + tbody: HTMLFactory; + td: HTMLFactory; + textarea: HTMLFactory; + tfoot: HTMLFactory; + th: HTMLFactory; + thead: HTMLFactory; + time: HTMLFactory; + title: HTMLFactory; + tr: HTMLFactory; + track: HTMLFactory; + u: HTMLFactory; + ul: HTMLFactory; + "var": HTMLFactory; + video: HTMLFactory; + wbr: HTMLFactory; + + // SVG + circle: SVGFactory; + defs: SVGFactory; + ellipse: SVGFactory; + g: SVGFactory; + line: SVGFactory; + linearGradient: SVGFactory; + mask: SVGFactory; + path: SVGFactory; + pattern: SVGFactory; + polygon: SVGFactory; + polyline: SVGFactory; + radialGradient: SVGFactory; + rect: SVGFactory; + stop: SVGFactory; + svg: SVGFactory; + text: SVGFactory; + tspan: SVGFactory; + } + + // + // React.PropTypes + // ---------------------------------------------------------------------- + + interface Validator { + (object: T, key: string, componentName: string): Error; + } + + interface Requireable extends Validator { + isRequired: Validator; + } + + interface ValidationMap { + [key: string]: Validator; + } + + interface ReactPropTypes { + any: Requireable; + array: Requireable; + bool: Requireable; + func: Requireable; + number: Requireable; + object: Requireable; + string: Requireable; + node: Requireable; + element: Requireable; + instanceOf(expectedClass: {}): Requireable; + oneOf(types: any[]): Requireable; + oneOfType(types: Validator[]): Requireable; + arrayOf(type: Validator): Requireable; + objectOf(type: Validator): Requireable; + shape(type: ValidationMap): Requireable; + } + + // + // React.Children + // ---------------------------------------------------------------------- + + interface ReactChildren { + map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; + forEach(children: ReactNode, fn: (child: ReactChild) => any): void; + count(children: ReactNode): number; + only(children: ReactNode): ReactChild; + } + + // + // Browser Interfaces + // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts + // ---------------------------------------------------------------------- + + interface AbstractView { + styleMedia: StyleMedia; + document: Document; + } + + interface Touch { + identifier: number; + target: EventTarget; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + pageX: number; + pageY: number; + } + + interface TouchList { + [index: number]: Touch; + length: number; + item(index: number): Touch; + identifiedTouch(identifier: number): Touch; + } +} + diff --git a/react/react-addons-0.13.0-tests.ts b/react/react-addons-0.13.0-tests.ts deleted file mode 100644 index 6081a9824..000000000 --- a/react/react-addons-0.13.0-tests.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// -import React = require("react/addons"); - -var isImportant: boolean; -var isRead: boolean; -var classSet: React.ClassSet = { - "message": true, - "message-important": isImportant, - "message-read": isRead -}; -var cx = React.addons.classSet; -var classes: string = cx(classSet); - -// -// React.addons (Transitions) -// -------------------------------------------------------------------------- - -React.createFactory(React.addons.TransitionGroup)({ component: "div" }); -React.createFactory(React.addons.CSSTransitionGroup)({ - component: React.createClass({ - render: (): React.ReactElement => null - }), - childFactory: (c) => c, - transitionName: "transition", - transitionAppear: false, - transitionEnter: true, - transitionLeave: true -}); - -// -// React.addons.TestUtils -// -------------------------------------------------------------------------- - -var that: React.Component; -var node = React.findDOMNode(that.refs["input"]); -React.addons.TestUtils.Simulate.click(node); -React.addons.TestUtils.Simulate.change(node); -React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter"}); - -interface GreetingProps { - name: string; -} -interface GreetingState { - morning: boolean; -} -interface Greeting extends React.Component { -} -var Greeting = React.createClass({ - displayName: "Greeting", - getInitialState: function() { - return {morning: true}; - }, - render: function() { - var me = this; - return React.DOM.div( - null, - me.state.morning ? "Hello " : "Goodbye ", - me.props.name); - } -}); - -var root = React.addons.TestUtils.renderIntoDocument( - React.createElement(Greeting, {name: "John"})); -var greeting = React.addons.TestUtils - .findRenderedComponentWithType(root, Greeting); -greeting.setState({ - morning: false -}); diff --git a/sanitize-html/sanitize-html-tests.ts b/sanitize-html/sanitize-html-tests.ts new file mode 100644 index 000000000..22811faac --- /dev/null +++ b/sanitize-html/sanitize-html-tests.ts @@ -0,0 +1,33 @@ +/// + +import sanitizeHtml = require('sanitize-html'); + +var s: string; +var t: string; + +t = sanitizeHtml(s); +t = sanitizeHtml(s, { +}); +t = sanitizeHtml(s, { + allowedTags: ["a", "br"], + allowedSchemes: ["http"], + allowedAttributes: { "a": ["href"] }, + allowedClasses: { "a": ["someclass"] }, + transformTags: { + "a": "b", + "br": function(tagName: string, attributes: {[index: string]: string}): { tagName: string; attributes: {[index: string]: string};} { + return { tagName: tagName, attributes: attributes }; + } + }, + exclusiveFilter: { + "a": function(frame: { + tag: string; + attribs: { [index: string]: string }; + text: string; + tagPosition: number; + }): boolean { + return false; + } + } +}); + diff --git a/sanitize-html/sanitize-html.d.ts b/sanitize-html/sanitize-html.d.ts new file mode 100644 index 000000000..1875eedab --- /dev/null +++ b/sanitize-html/sanitize-html.d.ts @@ -0,0 +1,27 @@ +// Type definitions for sanitize-html 1.6.0 +// Project: https://github.com/punkave/sanitize-html +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module "sanitize-html" { + + function sanitizeHtml(s: string, opts?: { + allowedTags?: string[]; + allowedSchemes?: string[]; + allowedAttributes?: { [index: string]: string[] }; + allowedClasses?: { [index: string]: string[] }; + transformTags?: { [index: string]: any }; + exclusiveFilter?: { + [index: string]: (frame: { + tag: string; + attribs: { [index: string]: string }; + text: string; + tagPosition: number; + }) => boolean + }; + + }): string; + + export = sanitizeHtml; +} diff --git a/sax/sax-tests.ts b/sax/sax-tests.ts new file mode 100644 index 000000000..3eeecc4fc --- /dev/null +++ b/sax/sax-tests.ts @@ -0,0 +1,43 @@ +/// +/// +import sax = require("sax"); + +var opts: sax.SAXOptions = { + lowercase: true, + normalize: true, + xmlns: true, + position: true +}; + +var parser = sax.parser(/*strict=*/true, opts); + +parser.onerror = function(e: Error) { +}; + +parser.ontext = function(text: string) { +}; + +parser.onopentag = function(tag: sax.Tag) { +}; + +parser.onattribute = function(attr: { name: string; value: string; }) { +}; + +parser.onend = function() { +}; + +parser.write("Hello, world!").close(); + + +var saxStream = sax.createStream(/*strict=*/true, opts); + +saxStream.on("error", function(e: Error) { + this._parser.error = null; + this._parser.resume(); +}); + +import fs = require("fs"); +fs.createReadStream("file.xml") + .pipe(saxStream) + .pipe(fs.createWriteStream("file-copy.xml")); + diff --git a/sax/sax.d.ts b/sax/sax.d.ts new file mode 100644 index 000000000..fb3d7e785 --- /dev/null +++ b/sax/sax.d.ts @@ -0,0 +1,78 @@ +// Type definitions for sax js +// Project: https://github.com/isaacs/sax-js +// Definitions by: Asana +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + +declare module "sax" { + export var EVENTS: string[]; + + interface SAXOptions { + trim?: boolean; + normalize?: boolean; + lowercase?: boolean; + xmlns?: boolean; + noscript?: boolean; + position?: boolean; + } + + export interface Tag { + name: string; + attributes: { [key: string]: string }; + + // Available if opt.xmlns + ns?: { [key: string]: string }; + prefix?: string; + local?: string; + uri?: string; + } + + export function parser(strict: boolean, opt: SAXOptions): SAXParser; + export class SAXParser { + constructor(strict: boolean, opt: SAXOptions); + + // Methods + end(): void; + write(s: string): SAXParser; + resume(): SAXParser; + close(): SAXParser; + flush(): void; + + // Members + line: number; + column: number; + error: Error; + position: number; + startTagPosition: number; + closed: boolean; + strict: boolean; + opt: SAXOptions; + tag: string; + + // Events + onerror(e: Error): void; + ontext(t: string): void; + ondoctype(doctype: string): void; + onprocessinginstruction(node: { name: string; body: string }): void; + onopentag(tag: Tag): void; + onclosetag(tagName: string): void; + onattribute(attr: { name: string; value: string }): void; + oncomment(comment: string): void; + onopencdata(): void; + oncdata(cdata: string): void; + onclosecdata(): void; + onopennamespace(ns: { prefix: string; uri: string }): void; + onclosenamespace(ns: { prefix: string; uri: string }): void; + onend(): void; + onready(): void; + onscript(script: string): void; + } + + import stream = require("stream"); + export function createStream(strict: boolean, opt: SAXOptions): SAXStream; + export class SAXStream extends stream.Duplex { + constructor(strict: boolean, opt: SAXOptions); + private _parser: SAXParser; + } +} + diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts new file mode 100644 index 000000000..0bbfe3f6d --- /dev/null +++ b/sequelize/sequelize-tests.ts @@ -0,0 +1,214 @@ +/// + +import Sequelize = require('sequelize'); + +var opts: Sequelize.Options; +var defOpts: Sequelize.DefineOptions = { + indexes: [{ + fields: [""], + type: "", + method: "" + }] +}; +var attrOpts: Sequelize.AttributeOptions; +var defIndexOpts: Sequelize.DefineIndexOptions; +var indexOpts: Sequelize.IndexOptions; +var dropOpts: Sequelize.DropOptions; +var transOpts: Sequelize.TransactionOptions; +var syncOpts: Sequelize.SyncOptions; +var assocOpts: Sequelize.AssociationOptions; +var schemaOpts: Sequelize.SchemaOptions; +var findOpts: Sequelize.FindOptions +var findCrOpts: Sequelize.FindOrCreateOptions; +var queryOpts: Sequelize.QueryOptions; +var buildOpts: Sequelize.BuildOptions; +var copyOpts: Sequelize.CopyOptions; +var bulkCrOpts: Sequelize.BulkCreateOptions; +var destroyOpts: Sequelize.DestroyOptions; +var destroyInstOpts: Sequelize.DestroyInstanceOptions; +var updateOpts: Sequelize.UpdateOptions; +var saveOpts: Sequelize.SaveOptions; +var valOpts: Sequelize.ValidateOptions; +var incrOpts: Sequelize.IncrementOptions; + +var promiseMe: Sequelize.Promise; +var emitMe: Sequelize.EventEmitter; + +var sequelize = new Sequelize("", ""); +sequelize = new Sequelize("", opts); +sequelize = new Sequelize("", "", ""); +sequelize = new Sequelize("", "", opts); +sequelize = new Sequelize("", "", "", opts); + +interface modelPojo { + name: string; +} + +interface modelInst extends Sequelize.Instance, modelPojo { + +}; + +var myModelInst: modelInst; +var myModelPojo: modelPojo; + +sequelize.define("MyTable", attrOpts, defOpts); +var model: Sequelize.Model = sequelize.model("MyTable"); +model = sequelize.import(""); +emitMe = sequelize.authenticate(); +sequelize.cast({}, ""); +sequelize.col("myCol"); +sequelize.models.MyTable; +emitMe = sequelize.drop(dropOpts); +emitMe = sequelize.createSchema("schema"); +emitMe = sequelize.dropAllSchemas(); +emitMe = sequelize.dropSchema("dbo"); +emitMe = sequelize.fn("upper", sequelize.col("username")); +sequelize.literal(""); +sequelize.literal(1234); +sequelize.and("", 1234); +sequelize.or("", 123); +sequelize.where("", ""); +sequelize.where("", sequelize.and("", "")); +promiseMe= sequelize.transaction(transOpts); +promiseMe = sequelize.transaction(transOpts, function (t:Sequelize.Transaction): boolean { return true; }); +emitMe = sequelize.query("", model).complete(function (err, result) { }); +emitMe = sequelize.query(""); +var dialect: string = sequelize.getDialect(); +emitMe = sequelize.showAllSchemas(); +emitMe = sequelize.sync(syncOpts); + +model.addHook("", "", function () { }); +model.addHook("", function () { }); +model.beforeValidate("", function () { }); +model.afterValidate("", function () { }); +model.beforeCreate("", function () { }); +model.afterCreate("", function () { }); +model.beforeDestroy("", function () { }); +model.afterDestroy("", function () { }); +model.beforeUpdate("", function () { }); +model.afterUpdate("", function () { }); +model.beforeBulkCreate("", function () { }); +model.afterBulkCreate("", function () { }); +model.beforeBulkDestroy("", function () { }); +model.afterBulkDestroy("", function () { }); +model.beforeBulkUpdate("", function () { }); +model.afterBulkUpdate("", function () { }); + + +model.hasOne(model); +model.hasOne(model, assocOpts); +model.belongsTo(model); +model.belongsTo(model, assocOpts); +model.hasMany(model); +model.hasMany(model, assocOpts); + +promiseMe = model.sync(); +promiseMe = model.drop(dropOpts); +model.schema("", schemaOpts); +model.getTableName(); +model = model.scope({}); +model = model.scope(""); +model = model.scope([]); +model = model.scope(null); + +model.find().then(function () { }, function () { }); +model.find().then(function () { }); +model.find().then(null, function () { }); +model.find().then(function (result: modelInst) { }); +model.find().then(function (result: modelInst): Sequelize.PromiseT { return model.find(1) }); +model.find().then(function (result: modelInst): Sequelize.PromiseT { return model.find(1) }, function (): Sequelize.PromiseT { return model.find(1) }); + +model.find().catch(function () { }); +model.find().catch(function (result: modelInst) { }); +model.find().catch(function (result: modelInst): Sequelize.Promise { return model.find(1) }); + +model.find().spread(function () { }, function () { }); +model.find().spread(function () { }); +model.find().spread(null, function () { }); +model.find().spread(function (result: modelInst) { }); +model.find().spread(function (result1: modelInst, result2: any) { }); +model.find().spread(null, function (result1: any, result2: boolean) { }); +model.find().spread(function (result: modelInst): Sequelize.Promise { return model.find(1) }); +model.find().spread(function (result: modelInst): Sequelize.PromiseT { return model.find(1) }); +model.find().spread(function (result: modelInst) { }, function (): Sequelize.PromiseT { return model.find(1) }); +model.find().spread(function (result: modelInst): Sequelize.PromiseT { return model.find(1) }, function (): Sequelize.PromiseT { return model.find(1) }); + +promiseMe = model.findAll(findOpts, queryOpts); +promiseMe = model.findAll(findOpts); +promiseMe = model.findAll(); +promiseMe = model.find(findOpts, queryOpts); +promiseMe = model.find(findOpts); +promiseMe = model.find(1, queryOpts); +promiseMe = model.find(1); +promiseMe = model.find(); +promiseMe = model.aggregate("", "", findOpts); +promiseMe = model.count(); +promiseMe = model.count(findOpts); +promiseMe = model.findAndCountAll(findOpts, queryOpts); +promiseMe = model.findAndCountAll(findOpts); +promiseMe = model.findAndCountAll(); +promiseMe = model.max("", findOpts); +promiseMe = model.max(""); +promiseMe = model.min("", findOpts); +promiseMe = model.min(""); +promiseMe = model.sum("", findOpts); +promiseMe = model.sum(""); +myModelInst = model.build(myModelPojo, buildOpts); +myModelInst = model.build(myModelPojo); +promiseMe = model.create(myModelPojo, copyOpts); +promiseMe = model.create(myModelPojo); +promiseMe = model.findOrInitialize({}, myModelPojo, queryOpts); +promiseMe = model.findOrInitialize({}, myModelPojo); +promiseMe = model.findOrInitialize({}); +promiseMe = model.findOrCreate({}, myModelPojo, findCrOpts); +promiseMe = model.findOrCreate({}, myModelPojo); +promiseMe = model.findOrCreate({}); +promiseMe = model.bulkCreate([myModelPojo], bulkCrOpts); +promiseMe = model.bulkCreate([myModelPojo]); +promiseMe = model.destroy({}, destroyOpts); +promiseMe = model.destroy({}); +promiseMe = model.destroy(); +promiseMe = model.update(myModelPojo, {}, updateOpts); +promiseMe = model.update(myModelPojo, {}); +promiseMe = model.describe(); +model.dataset; +//var isDefined: boolean = sequelize.isDefined(""); + +model.find().spread(function (arg1: string, arg2: number) { + return model.find(); +}); + +var isBool: boolean; +var strArr: Array; + +isBool = myModelInst.isNewRecord; +model = myModelInst.Model; +sequelize = myModelInst.sequelize; +isBool = myModelInst.isDeleted; +myModelPojo = myModelInst.values; +isBool = myModelInst.isDirty; +myModelPojo = myModelInst.primaryKeyValues; +myModelInst.getDataValue(""); +myModelInst.setDataValue("", ""); +myModelInst.setDataValue("", 123); +myModelInst.get(""); +myModelInst.set("", ""); +myModelInst.set("", 123); +isBool = myModelInst.changed(""); +strArr = myModelInst.changed(); +myModelInst.previous(""); +promiseMe = myModelInst.save(["", ""], saveOpts); +promiseMe = myModelInst.save(["", ""]); +promiseMe = myModelInst.reload(); +promiseMe = myModelInst.reload(findOpts); +promiseMe = myModelInst.validate(valOpts); +promiseMe = myModelInst.validate(); +promiseMe = myModelInst.updateAttributes(myModelPojo, saveOpts); +promiseMe = myModelInst.destroy(destroyInstOpts); +promiseMe = myModelInst.destroy(); +promiseMe = myModelInst.increment({}, incrOpts); +promiseMe = myModelInst.increment({}); +promiseMe = myModelInst.decrement({}, incrOpts); +isBool = myModelInst.equal(myModelInst); +isBool = myModelInst.equalsOneOf([myModelInst]); +myModelPojo = myModelInst.toJSON(); \ No newline at end of file diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts new file mode 100644 index 000000000..08eb47272 --- /dev/null +++ b/sequelize/sequelize.d.ts @@ -0,0 +1,2780 @@ +// Type definitions for Sequelize 2.0.0 dev13 +// Project: http://sequelizejs.com +// Definitions by: samuelneff , Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Based on original work by: samuelneff + +/// +/// + +declare module "sequelize" +{ + module sequelize { + interface SequelizeStaticAndInstance { + + /** + * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want + * to use Sequelize.Utils._, which is a reference to the lodash library, if you don't already have it imported in + * your project. + */ + Utils: Utils; + + /** + * A modified version of bluebird promises, that allows listening for sql events. + * + * @see Promise + */ + Promise: Promise; + + /** + * Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed + * both on the instance, and on the constructor. + * + * @see Validator + */ + Validator: Validator; + + QueryTypes: QueryTypes; + + /** + * A general error class. + */ + Error: Error; + + /** + * Emitted when a validation fails. + * + * @see ValidationError + */ + ValidationError: ValidationError; + + /** + * Creates a object representing a database function. This can be used in search queries, both in where and order + * parts, and as default values in column definitions. If you want to refer to columns in your function, you should + * use sequelize.col, so that the columns are properly interpreted as columns and not a strings. + * + * @param fn The function you want to call. + * @param args All further arguments will be passed as arguments to the function. + */ + fn(fn: string, ...args: Array): any; + + /** + * Creates a object representing a column in the DB. This is often useful in conjunction with sequelize.fn, since + * raw string arguments to fn will be escaped. + * + * @param col The name of the column + */ + col(col: string): Col; + + /** + * Creates a object representing a call to the cast function. + * + * @param val The value to cast. + * @param type The type to cast it to. + */ + cast(val: any, type: string): Cast; + + /** + * Creates a object representing a literal, i.e. something that will not be escaped. + * + * @param val Value to convert to a literal. + */ + literal(val: any): Literal; + + /** + * An AND query. + * + * @param args Each argument (string or object) will be joined by AND. + */ + and(...args: Array): And; + + /** + * An OR query. + * + * @param args Each argument (string or object) will be joined by OR. + */ + or(...args: Array): Or; + + /** + * A way of specifying attr = condition. Mostly used internally. + * + * @param attr The attribute + * @param condition The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.) + */ + where(attr: string, condition: any): Where; + } + + interface SequelizeStatic extends SequelizeStaticAndInstance, DataTypes { + /** + * Instantiate sequelize with name of database and username + * @param database database name + * @param username user name + */ + new (database: string, username: string): Sequelize; + + /** + * Instantiate sequelize with name of database, username and password + * @param database database name + * @param username user name + * @param password password + */ + new (database: string, username: string, password: string): Sequelize; + + /** + * Instantiate sequelize with name of database, username, password, and options. + * @param database database name + * @param username user name + * @param password password + * @param options options. @see Options + */ + new (database: string, username: string, password: string, options: Options): Sequelize; + + /** + * Instantiate sequelize with name of database, username, and options. + * + * @param database database name + * @param username user name + * @param options options. @see Options + */ + new (database: string, username: string, options: Options): Sequelize; + + /** + * Instantiate sequlize with an URI + * @param connectionString A full database URI + * @param options Options for sequelize. @see Options + */ + new (connectionString: string, options?: Options): Sequelize; + } + + interface Sequelize extends SequelizeStaticAndInstance { + /** + * Sequelize configuration (undocumented). + */ + config: Config; + + /** + * Sequelize options (undocumented). + */ + options: Options; + + /** + * Models are stored here under the name given to sequelize.define + */ + models: any; + modelManager: ModelManager; + daoFactoryManager: ModelManager; + transactionManager: TransactionManager; + importCache: any; + + /** + * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction. + * + * @see Transaction + */ + Transaction: TransactionStatic; + + /** + * Returns the specified dialect. + */ + getDialect(): string; + + /** + * Returns the singleton instance of QueryInterface. + */ + getQueryInterface(): QueryInterface; + + /** + * Returns the singleton instance of Migrator. + * @param options Migration options + * @param force A flag that defines if the migrator should get instantiated or not. + */ + getMigrator(options?: MigratorOptions, force?: boolean): Migrator; + + /** + * Define a new model, representing a table in the DB. + * + * @param daoName The name of the entity (table). Typically specified in singular form. + * @param attributes A hash of attributes to define. Each attribute can be either a string name for the attribute + * or can be an object defining the attribute and its options. Note attributes is not fully + * typed since TypeScript does not support union types--it can be either a string or an + * options object. @see AttributeOptions. + * @param options Table options. @see DefineOptions. + */ + define(daoName: string, attributes: any, options?: DefineOptions): Model; + + /** + * Fetch a DAO factory which is already defined. + * + * @param daoName The name of a model defined with Sequelize.define. + */ + model(daoName: string): Model; + + /** + * Checks whether a model with the given name is defined. + * + * @param daoName The name of a model defined with Sequelize.define. + */ + isDefined(daoName: string): boolean; + + /** + * Imports a model defined in another file. + * + * @param path The path to the file that holds the model you want to import. If the part is relative, it will be + * resolved relatively to the calling file + */ + import(path: string): Model; + + /** + * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. + * + * @param sql SQL statement to execute. + * + * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented + * by the factory. Equivalent to calling Model.build with the values provided by the query. + * + * @param options Query options. + * + * @param replacements Either an object of named parameter replacements in the format :param or an array of + * unnamed replacements to replace ? in your SQL. + */ + query(sql: string, callee?: Model, options?: QueryOptions, replacements?: any): EventEmitter; + + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitterT>; + + /** + * Create a new database schema. + * + * @param schema Name of the schema. + */ + createSchema(schema: string): EventEmitter; + + /** + * Show all defined schemas. + */ + showAllSchemas(): EventEmitter; + + /** + * Drop a single schema. + * + * @param schema Name of the schema. + */ + dropSchema(schema: string): EventEmitter; + + /** + * Drop all schemas. + */ + dropAllSchemas(): EventEmitter; + + /** + * Sync all defined DAOs to the DB. + * + * @param options Options. + */ + sync(options?: SyncOptions): EventEmitter; + + /** + * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model. + * + * @param options The options passed to each call to Model.drop. + */ + drop(options: DropOptions): EventEmitter; + + /** + * Test the connection by trying to authenticate. Alias for 'validate'. + */ + authenticate(): EventEmitter; + + /** + * Alias for authenticate(). Test the connection by trying to authenticate. Alias for 'validate'. + */ + validate(): EventEmitter; + + /** + * !! DEPRECATED : When passing a callback to a transaction a promise chain is expected in return, + * the transaction will be committed or rejected based on the promise chain returned to the callback. + * + * Start a transaction. When using transactions, you should pass the transaction in the options argument in order + * for the query to happen under that transaction. + * + * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction + * argument (overload available for error and transaction arguments too). + */ + transaction(callback: (transaction: Transaction) => boolean): Promise; + + /** + * Start a transaction. When using transactions, you should pass the transaction in the options argument in order + * for the query to happen under that transaction. + * + * @param options Transaction options. + * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction + * argument (overload available for error and transaction arguments too). + */ + transaction(options?: TransactionOptions, callback?: (transaction: Transaction) => void): PromiseT; + + close(): void; + } + + interface Config { + database?: string; + username?: string; + password?: string; + host?: string; + port?: number; + pool?: PoolOptions; + protocol?: string; + queue?: boolean; + native?: boolean; + ssl?: boolean; + replication?: ReplicationOptions; + dialectModulePath?: string; + maxConcurrentQueries?: number; + dialectOptions?: any; + } + + interface Model extends Hooks, Associations { + /** + * A reference to the sequelize instance. + */ + sequelize: Sequelize; + + /** + * The name of the model, typically singular. + */ + name: string; + + /** + * The name of the underlying database table, typically plural. + */ + tableName: string; + + options: DefineOptions; + attributes: any; + rawAttributes: any; + modelManager: ModelManager; + daoFactoryManager: ModelManager; + associations: any; + scopeObj: any; + + /** + * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model + * instance (this). + */ + sync(options?: SyncOptions): PromiseT>; + + /** + * Drop the table represented by this Model. + * + * @param options + */ + drop(options?: DropOptions): Promise; + + /** + * Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - + * "schema"."tableName", while the schema will be prepended to the table name for mysql and sqlite - + * 'schema.tablename'. + * + * @param schema The name of the schema. + * @param options Schema options. + */ + schema(schema: string, options?: SchemaOptions): Model; + + /** + * Get the tablename of the model, taking schema into account. The method will return The name as a string if the + * model has no schema, or an object with tableName, schema and delimiter properties. + */ + getTableName(): any; + + /** + * Apply a scope created in define to the model. + * + * @param options The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of + * arguments. To apply simple scopes, pass them as strings. For scope function, pass an object, + * with a method property. The value can either be a string, if the method does not take any + * arguments, or an array, where the first element is the name of the method, and consecutive + * elements are arguments to that method. Pass null to remove all scopes, including the default. + */ + scope(options: any): Model; + + /** + * Search for multiple instances.. + * + * @param options A hash of options to describe the scope of the search. + * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built + * Instances. See sequelize.query for options. + */ + findAll(options?: FindOptions, queryOptions?: QueryOptions): PromiseT>; + + /** + * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. + * + * @param options A hash of options to describe the scope of the search. + * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built + * Instances. See sequelize.query for options + */ + find(options?: FindOptions, queryOptions?: QueryOptions): PromiseT; + + /** + * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. + * + * @param options A number to search by id. + * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built + * Instances. See sequelize.query for options + */ + find(id?: number, queryOptions?: QueryOptions): PromiseT; + + /** + * Run an aggregation method on the specified field. + * + * @param field The field to aggregate over. Can be a field name or *. + * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc. + * @param options Query options, particularly options.dataType. + */ + aggregate(field: string, aggregateFunction: string, options: FindOptions): PromiseT; + + /** + * Count the number of records matching the provided where clause. + * + * @param options Conditions and options for the query. + */ + count(options?: FindOptions): PromiseT; + + /** + * Find all the rows matching your query, within a specified offset / limit, and get the total number of rows + * matching your query. This is very usefull for paging. + * + * @param findOptions Filtering options + * @param queryOptions Query options + */ + findAndCountAll(findOptions?: FindOptions, queryOptions?: QueryOptions): PromiseT>; + + /** + * Find the maximum value of field. + * + * @param field + * @param options + */ + max(field: string, options?: FindOptions): PromiseT; + + /** + * Find the minimum value of field. + * + * @param field + * @param options + */ + min(field: string, options?: FindOptions): PromiseT; + + /** + * Find the sum of field. + * + * @param field + * @param options + */ + sum(field: string, options?: FindOptions): PromiseT; + + /** + * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty. + * + * @param values any from which to build entity instance. + * @param options any construction options. + */ + build(values: TPojo, options?: BuildOptions): TInstance; + + /** + * Builds a new model instance and calls save on it.. + * + * @param values + * @param options + */ + create(values: TPojo, options?: CopyOptions): PromiseT; + + /** + * Find a row that matches the query, or build (but don't save) the row if none is found. The successfull result + * of the promise will be (instance, initialized) - Make sure to use .spread(). + * + * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax + * is { attr1: 42 } and NOT { where: { attr1: 42}}. This may be subject to change in 2.0 + * @param defaults Default values to use if building a new instance + * @param options Options passed to the find call + */ + findOrInitialize(where: any, defaults?: TPojo, options?: QueryOptions): PromiseT; + + /** + * Find a row that matches the query, or build and save the row if none is found The successfull result of the + * promise will be (instance, created) - Make sure to use .spread(). + * + * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax is + * { attr1: 42 } and NOT { where: { attr1: 42}}. This is subject to change in 2.0 + * @param defaults Default values to use if creating a new instance + * @param options Options passed to the find and create calls. + */ + findOrCreate(where: any, defaults?: TPojo, options?: FindOrCreateOptions): PromiseT; + + /** + * Create and insert multiple instances in bulk. + * + * @param records List of objects (key/value pairs) to create instances from. + * @param options + */ + bulkCreate(records: Array, options?: BulkCreateOptions): PromiseT>; + + /** + * Delete multiple instances. + */ + destroy(where?: any, options?: DestroyOptions): Promise; + + /** + * Update multiple instances that match the where options. + * + * @param attrValueHash A hash of fields to change and their new values + * @param where Options to describe the scope of the search. Note that these options are not wrapped in a + * { where: ... } is in find / findAll calls etc. This is probably due to change in 2.0. + */ + update(attrValueHash: TPojo, where: any, options?: UpdateOptions): Promise; + + /** + * Run a describe query on the table. The result will be return to the listener as a hash of attributes and their + * types. + */ + describe(): PromiseT; + + /** + * A proxy to the node-sql query builder, which allows you to build your query through a chain of method calls. + * The returned instance already has all the fields property populated with the field of the model. + */ + dataset(): any; + } + + interface Instance { + /** + * Returns true if this instance has not yet been persisted to the database. + */ + isNewRecord: boolean; + + /** + * Returns the Model the instance was created from. + */ + Model: Model; + + /** + * A reference to the sequelize instance. + */ + sequelize: Sequelize; + + /** + * If timestamps and paranoid are enabled, returns whether the deletedAt timestamp of this instance is set. + * Otherwise, always returns false. + */ + isDeleted: boolean; + + /** + * Get the values of this Instance. Proxies to this.get. + */ + values: TPojo; + + /** + * A getter for this.changed(). Returns true if any keys have changed. + */ + isDirty: boolean; + + /** + * Get the values of the primary keys of this instance. + */ + primaryKeyValues: TPojo; + + /** + * Get the value of the underlying data value. + * + * @param key Field to retrieve. + */ + getDataValue(key: string): any; + + /** + * Update the underlying data value. + * + * @param key Field to set. + * @param value Value to set. + */ + setDataValue(key: string, value: any): void; + + /** + * Retrieves the value for the key when specified. If no key is given, returns all values of the instance, also + * invoking virtual getters. + */ + get(key?: string): any; + + /** + * Set is used to update values on the instance (the sequelize representation of the instance that is, remember + * that nothing will be persisted before you actually call save). + */ + set(key: string, value: any, options?: SetOptions): void; + + /** + * If changed is called with a string it will return a boolean indicating whether the value of that key in + * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will + * return an array of keys that have changed. + */ + changed(key: string): any; + + /** + * If changed is called with a string it will return a boolean indicating whether the value of that key in + * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will + * return an array of keys that have changed. + */ + changed(): Array; + + /** + * Returns the previous value for key from _previousDataValues. + */ + previous(key: string): any; + + /** + * Validate this instance, and if the validation passes, persist it to the database. + */ + save(fields?: Array, options?: SaveOptions): PromiseT; + + /** + * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same + * object. This is different from doing a find(Instance.id), because that would create and return a new instance. + * With this method, all references to the Instance are updated with the new data and no new objects are created. + */ + reload(options?: FindOptions): PromiseT; + + /** + * Validate the attribute of this instance according to validation rules set in the model definition. + */ + validate(options?: ValidateOptions): PromiseT; + + /** + * This is the same as calling setAttributes, then calling save. + */ + updateAttributes(updates: TPojo, options: SaveOptions): PromiseT; + + /** + * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be + * completely deleted, or have its deletedAt timestamp set to the current time. + * + * @param options Allows caller to specify if delete should be forced. + */ + destroy(options?: DestroyInstanceOptions): Promise; + + /** + * Increment the value of one or more columns. This is done in the database, which means it does not use the + * values currently stored on the Instance. + * + * @param fields If a string is provided, that column is incremented by the value of by given in options. If an + * array is provided, the same is true for each column. If and object is provided, each column is + * incremented by the value given. + * @param options Increment options. + */ + increment(fields: any, options?: IncrementOptions): Promise; + + /** + * Decrement the value of one or more columns. This is done in the database, which means it does not use the + * values currently stored on the Instance. + * + * @param fields If a string is provided, that column is decremented by the value of by given in options. If an + * array is provided, the same is true for each column. If and object is provided, each column is + * decremented by the value given. + * @param options Decrement options. + */ + decrement(fields: any, options?: IncrementOptions): Promise; + + /** + * Check whether all values of this and other Instance are the same. + */ + equal(other: TInstance): boolean; + + /** + * Check if this is eqaul to one of others by calling equals. + * + * @param others Other instances to compare to. + */ + equalsOneOf(others: Array): boolean; + + /** + * Convert the instance to a JSON representation. Proxies to calling get with no keys. This means get all values + * gotten from the DB, and apply all custom getters. + */ + toJSON(): TPojo; + } + + interface Transaction extends TransactionStatic { + /** + * Commit the transaction. + */ + commit(): Transaction; + + /** + * Rollback (abort) the transaction. + */ + rollback(): Transaction; + } + + interface TransactionStatic { + /** + * The possible isolation levels to use when starting a transaction + */ + ISOLATION_LEVELS: TransactionIsolationLevels; + + /** + * Possible options for row locking. Used in conjuction with find calls. + */ + LOCK: TransactionLocks; + } + + interface TransactionIsolationLevels { + READ_UNCOMMITTED: string;// "READ UNCOMMITTED" + READ_COMMITTED: string; // "READ COMMITTED" + REPEATABLE_READ: string; // "REPEATABLE READ" + SERIALIZABLE: string; // "SERIALIZABLE" + } + + interface TransactionLocks { + UPDATE: string; // UPDATE + SHARE: string; // SHARE + } + + interface Hooks { + + /** + * Add a named hook to the model. + * + * @param hooktype + */ + addHook(hooktype: string, name: string, fn: (...args: Array) => void): boolean; + + /** + * Add a hook to the model. + * + * @param hooktype + */ + addHook(hooktype: string, fn: (...args: Array) => void): boolean; + + /** + * A named hook that is run before validation. + */ + beforeValidate(name: string, validator: (dao: T, callback: (err?: Error) => void) => void): void; + + /** + * A hook that is run before validation. + */ + beforeValidate(validator: (dao: T, callback: (err?: Error) => void) => void): void; + + /** + * A named hook that is run before validation. + */ + afterValidate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before validation. + */ + afterValidate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before creating a single instance. + */ + beforeCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before creating a single instance. + */ + beforeCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after creating a single instance. + */ + afterCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after creating a single instance. + */ + afterCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before destroying a single instance. + */ + beforeDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before destroying a single instance. + */ + beforeDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after destroying a single instance. + */ + afterDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after destroying a single instance. + */ + afterDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before updating a single instance. + */ + beforeUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before updating a single instance. + */ + beforeUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after updating a single instance. + */ + afterUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after updating a single instance. + */ + afterUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before creating instances in bulk. + */ + beforeBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before creating instances in bulk. + */ + beforeBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after creating instances in bulk. + */ + afterBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after creating instances in bulk. + */ + afterBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before destroying instances in bulk. + */ + beforeBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A hook that is run before destroying instances in bulk. + */ + beforeBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A named hook that is run after destroying instances in bulk. + */ + afterBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A hook that is run after destroying instances in bulk. + */ + afterBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A named hook that is run before updating instances in bulk. + */ + beforeBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + + /** + * A hook that is run before updating instances in bulk. + */ + beforeBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + + /** + * A named hook that is run after updating instances in bulk. + */ + afterBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + + /** + * A hook that is run after updating instances in bulk. + */ + afterBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + } + + interface Associations { + /** + * Creates an association between this (the source) and the provided target. The foreign key is added on the target. + * + * @param target + * @param options + */ + hasOne(target: Model, options?: AssociationOptions): void; + + /** + * Creates an association between this (the source) and the provided target. The foreign key is added on the source. + * + * @param target + * @param options + */ + belongsTo(target: Model, options?: AssociationOptions): void; + + /** + * Create an association that is either 1:m or n:m. + * + * @param target + * @param options + */ + hasMany(target: Model, options?: AssociationOptions): void; + } + + /** + * Extension of external project that doesn't have definitions. + * + * See https://github.com/chriso/validator.js and https://github.com/sequelize/sequelize/blob/master/lib/instance-validator.js + */ + interface Validator { + + } + + /** + * Custom class defined, but no extra methods or functionality even. + */ + interface ValidationError extends Error { + + } + + interface QueryChainer { + /** + * Add an query to the chainer. This can be done in two ways - either by invoking the method like you would + * normally, and then adding the returned emitter to the chainer, or by passing the class that you want to call a + * method on, the name of the method, and its parameters to the chainer. The second form might sound a bit + * cumbersome, but it is used when you want to run queries in serial. + * + * @param emitterOrKlass + * @param method + * @param params + * @param options + */ + add(emitterOrKlass: any, method?: string, params?: any, options?: any): QueryChainer; + + /** + * Run the query chainer. In reality, this means, wait for all the added emitters to finish, since the queries + * began executing as soon as you invoked their methods. + */ + run(): EventEmitter; + + /** + * Run the chainer serially, so that each query waits for the previous one to finish before it starts. + * + * @param options @see QueryChainerRunSeriallyOptions + */ + runSerially(options?: QueryChainerRunSeriallyOptions): EventEmitter; + } + + interface QueryInterface { + + /** + * Returns the dialect-specific sql generator. + */ + QueryGenerator: QueryGenerator; + + /** + * Queries the schema (table list). + * + * @param schema The schema to query. Applies only to Postgres. + */ + createSchema(schema?: string): EventEmitter; + + /** + * Drops the specified schema (table). + * + * @param schema The name of the table to drop. + */ + dropSchema(schema: string): EventEmitter; + + /** + * Drops all tables. + */ + dropAllSchemas(): EventEmitter; + + /** + * Queries all table names in the database. + * + * @param options + */ + showAllSchemas(options?: QueryOptions): EventEmitter; + + /** + * Creates a table with specified attributes. + * @param tableName Name of table to create + * @param attributes Hash of attributes, key is attribute name, value is data type + * @param options Query options. + * + * @return The return type will be a Promise when dialect is Postgres and an EventEmitter for MySQL and SQLite. + */ + createTable(tableName: string, attributes: any, options?: QueryOptions): any; + + /** + * Drops the specified table. + * + * @param tableName Table name. + * @param options Query options, particularly "force". + */ + dropTable(tableName: string, options?: QueryOptions): EventEmitter; + dropAllTables(options?: QueryOptions): EventEmitter; + dropAllEnums(options?: QueryOptions): EventEmitter; + renameTable(before: string, after: string): EventEmitter; + showAllTables(options?: QueryOptions): EventEmitter; + describeTable(tableName: string, options?: QueryOptions): EventEmitter; + addColumn(tableName: string, attributeName: any, dataTypeOrOptions?: any): EventEmitter; + removeColumn(tableName: string, attributeName: string): EventEmitter; + changeColumn(tableName: string, attributeName: string, dataTypeOrOptions: any): EventEmitter; + renameColumn(tableName: string, attrNameBefore: string, attrNameAfter: string): EventEmitter; + addIndex(tableName: string, attributes: Array, options?: QueryOptions): EventEmitter; + showIndex(tableName: string, options?: QueryOptions): EventEmitter; + getForeignKeysForTables(tableNames: Array): EventEmitter; + removeIndex(tableName: string, attributes: Array): EventEmitter; + removeIndex(tableName: string, indexName: string): EventEmitter; + insert(dao: TModel, tableName: string, values: any, options?: QueryOptions): EventEmitter; + /** + * Inserts several records into the specified table. + * @param tableName Table to insert into. + * @param records Array of key/value pairs to insert as records. + * @param options Query options + * @param attributes For Postgres only, used to identify if an attribute is auto-increment and thus handled specially. + */ + bulkInsert(tableName: string, records: Array, options?: QueryOptions, attributes?: any): EventEmitter; + + update(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; + bulkUpdate(tableName: string, values: Array, where: any, options?: QueryOptions, attributes?: any): EventEmitter; + delete(dao: TModel, tableName: string, where: any, options?: QueryOptions): EventEmitter; + bulkDelete(tableName: string, where: any, options?: QueryOptions): EventEmitter; + bulkDelete(tableName: string, where: any, options: QueryOptions, model: TModel): EventEmitter; + select(factory: TModel, tableName: string, scope?: any, queryOptions?: QueryOptions): EventEmitter; + increment(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; + rawSelect(tableName: string, options: QueryOptions, attributeSelector: string, model: TModel): EventEmitter; + /** + * Postgres only. Creates a trigger on specified table to call the specified function with supplied parameters. + * + * @param tableName + * @param triggerName + * @param timingType + * @param fireOnArray + * @param functionName + * @param functionParams + * @param optionsArray + */ + createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: Array, functionName: string, functionParams: Array, optionsArray: Array): EventEmitter; + /** + * Postgres only. Drops the specified trigger. + * + * @param tableName + * @param triggerName + */ + dropTrigger(tableName: string, triggerName: string): EventEmitter; + renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): EventEmitter; + createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: QueryOptions): EventEmitter; + dropFunction(functionName: string, params: Array): EventEmitter; + renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): EventEmitter; + /** + * Escape an identifier (e.g. a table or attribute name). If force is true, + * the identifier will be quoted even if the `quoteIdentifiers` option is + * false. + */ + quoteIdentifier(identifier: string, force: boolean): EventEmitter; + quoteTable(tableName: string): EventEmitter; + quoteIdentifiers(identifiers: string, force: boolean): EventEmitter; + escape(value: string): EventEmitter; + setAutocommit(transaction: Transaction, value: boolean): EventEmitter; + setIsolationLevel(transaction: Transaction, value: string): EventEmitter; + startTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + commitTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + rollbackTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + } + + interface QueryGenerator { + createSchema(schemaName: string): string; + dropSchema(schemaName: string): string; + showSchemasQuery(): string; + addSchema(param: Model): Schema; + createTableQuery(tableName: string, attributes: Array, options?: CreateTableQueryOptions): string; + describeTableQuery(tableName: string, schema: string, schemaDelimiter: string): string; + dropTableQuery(tableName: string, options?: { cascade: string }): string; + renameTableQuery(before: string, after: string): string; + showTablesQuery(): string; + addColumnQuery(tableName: string, attributes: any): string; + removeColumnQuery(tableName: string, attributeName: string): string; + changeColumnQuery(tableName: string, attributes: any): string; + renameColumnQuery(tableName: string, attrNameBefore: string, attrNameAfter: string): string; + insertQuery(table: string, valueHash: any, modelAttributes: any): string; + bulkInsertQuery(tableName: string, attrValueHashes: any): string; + updateQuery(tableName: string, attrValueHash: any, where: any, options: InsertOptions, attributes: any): string; + deleteQuery(tableName: string, where: any, options: DestroyOptions): string; + deleteQuery(tableName: string, where: any, options: DestroyOptions, model: Model): string; + /** + * Creates a query to increment a value. Note "options" here is an additional hash of values to update. + * + * @param tableName + * @param attrValueHash + * @param where + * @param options + */ + incrementQuery(tableName: string, attrValueHash: any, where: any, options?: any): string; + addIndexQuery(tableName: string, attributes: Array, options?: IndexOptions): string; + /** + * Return indices for a table. Not options may be passed but is not used, so can be anything. + * @param tableName + * @param options + */ + showIndexQuery(tableName: string, options?: any): string; // options is actually not used + removeIndexQuery(tableName: string, indexNameOrAttributes: string): string; + removeIndexQuery(tableName: string, indexNameOrAttributes: Array): string; + attributesToSQL(attributes: Array): string; + findAutoIncrementField(factory: Model): Array; + quoteTable(param: any, as: boolean): string; + quote(obj: any, parent: any, force: boolean): string; + createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: TriggerOptions, functionName: string, functionParams: Array): string; + dropTrigger(tableName: string, triggerName: string): string; + renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): string; + createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: Array): string; + dropFunction(functionName: string, params: Array): string; + renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): string; + quoteIdentifier(identifier: string, force?: boolean): string; + quoteIdentifiers(identifiers: string, force?: boolean): string; + /** + * Not documented, and reading through the code, I'm not sure what all the options available are for value/field. + * + * @param value + * @param field + */ + escape(value: any, field: any): string; + getForeignKeysQuery(tableName: string, schemaName: string): string; + dropForeignKeyQuery(tableName: string, foreignKey: string): string; + selectQuery(tableName: string, options: SelectOptions, model?: Model): string; + selectQuery(tableName: Array, options: SelectOptions, model?: Model): string; + selectQuery(tableName: Array>, options: SelectOptions, model?: Model): string; + setAutocommitQuery(value: boolean): string; + setIsolationLevelQuery(value: string): string; + /** + * Returns start transaction query. Options is not used. + * @param options + */ + startTransactionQuery(options?: any): string; + /** + * Returns start transaction query. Options is not used. + * @param options + */ + commitTransactionQuery(options?: any): string; + /** + * Returns start transaction query. Options is not used. + * @param options + */ + rollbackTransactionQuery(options?: any): string; + addLimitAndOffset(options: SelectOptions, query?: string): string; + getWhereConditions(smth: any, tableName: string, factory: Model, options?: any, prepend?: boolean): string; + prependTableNameToHash(tableName: string, hash?: any): string; + findAssociation(attribute: string, dao: Model): string; + getAssociationFilterDAO(filterStr: string, dao: Model): string; + isAssociationFilter(filterStr: string, dao: Model, options?: any): string; + getAssociationFilterColumn(filterStr: string, dao: Model, options?: { include: boolean }): string; + getConditionalJoins(options: { where?: any }, originalDao: Model): string; + arrayValue(value: Array, key: string, _key: string, factory?: any, logicResult?: any): string; + hashToWhereConditions(hash: any, dao: Model, options?: HashToWhereConditionsOption): string; + booleanValue(value: boolean): string; + } + + interface Schema { + tableName: string; + table: string; + name: string; + schema: string; + delimiter: string; + } + + interface QueryTypes { + SELECT: string; + BULKUPDATE: string; + BULKDELETE: string; + } + + interface ModelManager { + daos: Array>; + sequelize: Sequelize; + addDAO(dao: Model): Model; + removeDAO(dao: Model): void; + getDAO(daoName: string, options?: ModelMangerGetDaoOptions): Model; + all: Array>; + + /** + * Iterate over DAOs in an order suitable for e.g. creating tables. Will + * take foreign key constraints into account so that dependencies are visited + * before dependents. + */ + forEachDAO(iterator: (dao: Model, name: string) => void, options?: ModelManagerForEachDaoOptions): void; + } + + interface TransactionManager { + sequelize: Sequelize; + connectorManagers: any; + getConnectorManager(uuid?: string): ConnectorManager; + releaseConnectionManager(uuid?: string): void; + + /** + * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. + * + * @param sql SQL statement to execute. + * + * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented + * by the factory. Equivalent to calling Model.build with the values provided by the query. + * + * @param options Query options. + * + */ + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; + + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; + } + + interface ConnectorManager { + + /** + * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. + * + * @param sql SQL statement to execute. + * + * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented + * by the factory. Equivalent to calling Model.build with the values provided by the query. + * + * @param options Query options. + * + */ + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; + + afterTransactionSetup(callback: () => void): void; + connect(): void; + disconnect(): void; + reconnect(): void; + cleanup(): void; + } + + interface Migrator { + queryInterface: QueryInterface; + migrate(options?: MigratorOptions): EventEmitter; + getUndoneMigrations(callback: (err: Error, result: Array) => void): void; + findOrCreateMetaDAO(syncOptions?: SyncOptions): EventEmitter; + exec(filename: string, options?: MigratorExecOptions): EventEmitter; + getLastMigrationFromDatabase(): EventEmitter; + getLastMigrationIdFromDatabase(): EventEmitter; + getFormattedDateString(s: string): string; + stringToDate(s: string): Date; + saveSuccessfulMigration(from: Migration, to: Migration, callback: (metaData: MetaInstance) => void): void; + deleteUndoneMigration(from: Migration, to: Migration, callback: () => void): void; + execute(options?: MigrationExecuteOptions): EventEmitter; + isBefore(date: Date, options?: MigrationCompareOptions): boolean; + isAfter(date: Date, options?: MigrationCompareOptions): boolean; + + } + + interface Migration extends QueryInterface { + migrator: Migrator; + path: string; + filename: string; + migrationId: number; + date: Date; + queryInterface: QueryInterface; + migration: (err: Error, migration: Migration, dataTypes: any, callback: (err: Error) => void) => void; + + } + + interface EventEmitter extends EventEmitterT, NodeJS.EventEmitter { } + + interface EventEmitterT extends NodeJS.EventEmitter { + /** + * Create a new emitter instance. + * + * @param handler + */ + new (handler: (emitter: EventEmitterT) => void): EventEmitterT; + + /** + * Run the function that was passed when the emitter was instantiated. + */ + run(): EventEmitterT; + + /** + * Listen for success events. + * + * @param onSuccess + */ + success(onSuccess: (result: R) => void): EventEmitterT; + + /** + * Alias for success(handler). Listen for success events. + * + * @param onSuccess + */ + ok(onSuccess: (result: R) => void): EventEmitterT; + + /** + * Listen for error events. + * + * @param onError + */ + error(onError: (err: Error) => void): EventEmitterT; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError + */ + fail(onError: (err: Error) => void): EventEmitterT; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError + */ + failure(onError: (err: Error) => void): EventEmitterT; + + /** + * Listen for both success and error events. + * + * @param onDone + */ + done(onDone: (err: Error, result: R) => void): EventEmitterT; + + /** + * Alias for done(handler). Listen for both success and error events. + * + * @param onDone + */ + complete(onDone: (err: Error, result: R) => void): EventEmitterT; + + /** + * Attach a function that is called every time the function that created this emitter executes a query. + * + * @param onSQL + */ + sql(onSQL: (sql: string) => void): EventEmitterT; + + /** + * Proxy every event of this event emitter to another one. + * + * @param emitter The event emitter that should receive the events. + * @param options Contains an array of the events to proxy. Defaults to sql, error and success + */ + proxy(emitter: EventEmitterT, options?: ProxyOptions): EventEmitterT; + + + } + + interface Options { + /** + * The dialect you of the database you are connecting to. One of mysql, postgres, sqlite and mariadb. + * Default is mysql. + */ + dialect?: string; + + /** + * If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when + * connecting to a pg database, you should specify 'pg.js' here + */ + dialectModulePath?: string; + + /** + * The host of the relational database. Default 'localhost'. + */ + host?: string; + + /** + * Integer The port of the relational database. + */ + port?: number; + + /** + * The protocol of the relational database. Default 'tcp'. + */ + protocol?: string; + + /** + * Default options for model definitions. See sequelize.define for options. + */ + define?: DefineOptions; + + /** + * Default options for sequelize.query + */ + query?: QueryOptions; + + /** + * Default options for sequelize.sync + */ + sync?: SyncOptions; + + /** + * The timezone used when converting a date from the database into a javascript date. The timezone is also used to + * SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time + * related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. + * Default '+00:00'. + */ + timezone?: string; + + /** + * Logging options. Function used to log. Default is console.log. Signature is (message:string) => void. + * + * Set to "false" to disable logging. + */ + logging?: any; + + /** logging=console.log] Function A function that gets executed everytime Sequelize would log something. + * A flag that defines if null values should be passed to SQL queries or not. + */ + omitNull?: boolean; + + /** + * Boolean Queue queries, so that only maxConcurrentQueries number of queries are executing at once. If false, all + * queries will be executed immediately. + */ + queue?: boolean; + + /** + * The maximum number of queries that should be executed at once if queue is true. + */ + maxConcurrentQueries?: number; + + /** + * A flag that defines if native library shall be used or not. Currently only has an effect for postgres + */ + native?: boolean; + + /** + * Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write + * should be an object (a single server for handling writes), and read an array of object (several servers to + * handle reads). Each read/write server can have the following properties?: host, port, username, password, database + */ + replication?: ReplicationOptions; + + /** + * Connection pool options. + * + */ + pool?: PoolOptions; + + /** + * Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them. + * Default true. + */ + quoteIdentifiers?: boolean; + + /** + * Language. Default "en". + */ + language?: string; + } + + interface PoolOptions { + maxConnections?: number; + + minConnections?: number; + + /** + * The maximum time, in milliseconds, that a connection can be idle before being released. + */ + maxIdleTime?: number; + + /** + * A function that validates a connection. Called with client. The default function checks that client is an + * object, and that its state is not disconnected. + * + * Note, this is not documented, and after reading code I'm not sure what client's type is. + */ + validateConnection?: (client?: any) => boolean; + } + + interface AttributeOptions { + /** + * A string or a data type + */ + type?: string; + + /** + * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance + * is saved. + */ + allowNull?: boolean; + + /** + * A literal default value, a javascript function, or an SQL function (see sequelize.fn) + */ + defaultValue?: any; + + /** + * If true, the column will get a unique constraint. If a string is provided, the column will be part of a + * composite unique index. If multiple columns have the same string, they will be part of the same unique index. + */ + unique?: any; + + primaryKey?: boolean; + + /** + * If set, sequelize will map the attribute name to a different name in the database. + */ + field?: string; + + autoIncrement?: boolean; + + comment?: string; + + /** + * If this column references another table, provide it here as a Model, or a string. + */ + references?: any; + + /** + * The column of the foreign table that this column references. Default 'id'. + */ + referencesKey?: string; + + /** + * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. + */ + onUpdate?: string; + + /** + * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. + */ + onDelete?: string; + + /** + * Provide a custom getter for this column. Use this.getDataValue(String) to manipulate the underlying values. + */ + get?: () => any; + + /** + * Provide a custom setter for this column. Use this.setDataValue(String, Value) to manipulate the underlying values. + */ + set?: (value?: any) => void; + + /** + * An object of validations to execute for this column every time the model is saved. Can be either the name of a + * validation provided by validator.js, a validation function provided by extending validator.js (see the + * DAOValidator property for more details), or a custom validation function. Custom validation functions are called + * with the value of the field, and can possibly take a second callback argument, to signal that they are + * asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async, + * the callback should be called with the error text. + */ + validate?: any; + } + + interface ForeignKeyAttributeOptions extends AttributeOptions { + /** + * The name of the foreign key in the target table. Defaults to the name of source + primary key of source. + */ + fieldName: string; + } + + interface DefineOptions { + /** + * Define the default search scope to use for this model. Scopes have the same form as the options passed to + * find / findAll. + */ + defaultScope?: FindOptions; + + /** + * More scopes, defined in the same way as defaultScope above. See Model.scope for more information about how + * scopes are defined, and what you can do with them + */ + scopes?: any; + + /** + * Don't persits null values. This means that all columns with null values will not be saved. + */ + omitNull?: boolean; + + /** + * Adds createdAt and updatedAt timestamps to the model. Default true. + */ + timestamps?: boolean; + + /** + * Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs + * timestamps=true to work. Default false. + */ + paranoid?: boolean; + + /** + * Converts all camelCased columns to underscored if true. Default false. + */ + underscored?: boolean; + + /** + * Converts camelCased model names to underscored tablenames if true. Default false. + */ + underscoredAll?: boolean; + + /** + * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the + * dao name will be pluralized. Default false. + */ + freezeTableName?: boolean; + + /** + * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true. + */ + createdAt?: any; + + /** + * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true. + */ + updatedAt?: any; + + /** + * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true. + */ + deletedAt?: any; + + /** + * Defaults to pluralized DAO name, unless freezeTableName is true, in which case it uses DAO name verbatim. + */ + tableName?: string; + + /** + * Provide getter functions that work like those defined per column. If you provide a getter method with the same + * name as a column, it will be used to access the value of that column. If you provide a name that does not match + * a column, this function will act as a virtual getter, that can fetch multiple other values. + */ + getterMethods?: any; + + /** + * Provide setter functions that work like those defined per column. If you provide a setter method with the same + * name as a column, it will be used to update the value of that column. If you provide a name that does not match + * a column, this function will act as a virtual setter, that can act on and set other values, but will not be + * persisted + */ + setterMethods?: any; + + /** + * Provide functions that are added to each instance (DAO). + */ + instanceMethods?: any; + + /** + * Provide functions that are added to the model (Model). + */ + classMethods?: any; + + /** + * Default 'public'. + */ + schema?: string; + schemaDelimiter?: string; + engine?: string; + charset?: string; + comment?: string; + collate?: string; + whereCollection?: any; + language?: string; + + /** + * An object of hook function that are called before and after certain lifecycle events. The possible hooks are?: + * beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, + * beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and + * afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can + * either be a function, or an array of functions. + */ + hooks?: Hooks; + + /** + * An object of model wide validations. Validations have access to all model values via this. If the validator + * function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional + * error. + */ + validate?: any; + + /** + * + */ + indexes?: Array; + } + + interface DefineIndexOptions { + /** + * The name of the index. Defaults to model name + _ + fields concatenated. + */ + name?: string; + + /** + * Index type. Only used by mysql. One of UNIQUE, FULLTEXT and SPATIAL. + */ + type: string; + + /** + * The method to create the index by (USING statement in SQL). BTREE and HASH are supported by mysql and postgres, + * and postgres additionally supports GIST and GIN. + */ + method: string; + + /** + * Should the index by unique? Can also be triggered by setting type to UNIQUE. Default false (unless type = "UNIQUE", + * then true). + */ + unique?: boolean; + + /** + * PostgreSQL will build the index without taking any write locks. Postgres only. Default false. + */ + concurrently?: boolean; + + /** + * An array of the fields to index. Each field can either be a string containing the name of the field, or an object + * with the following attributes: attribute (field name), length (create a prefix index of length chars), order (the + * direction the column should be sorted in), collate (the collation (sort order) for the column) + */ + fields: Array; + } + + interface QueryOptions { + /** + * If true, sequelize will not try to format the results of the query, or build an instance of a model from the + * result. + */ + raw?: boolean; + + /** + * The transaction that the query should be executed under. + */ + transaction?: Transaction; + + /** + * The type of query you are executing. The query type affects how results are formatted before they are passed + * back. If no type is provided sequelize will try to guess the right type based on the sql, and fall back to + * SELECT. The type is a string, but Sequelize.QueryTypes is provided is convenience shortcuts. Current options + * are SELECT, BULKUPDATE and BULKDELETE. + * + * Default is SELECT. + */ + type?: string; + + /** + * Lock the selected rows in either share or update mode. Possible options are transaction.LOCK.UPDATE and + * transaction.LOCK.SHARE. See transaction.LOCK for an example. + */ + lock?: string; + + /** + * For aggregate function calls, the type of the result. If field is a field in this Model, the default will be the + * type of that field, otherwise defaults to float. + */ + dataType?: any; + + /** + * A function that logs sql queries, or false for no logging. + */ + logging?: any; + + /** + * If plain is true, then sequelize will only return the first record of the result set. In case of false it will + * all records. + */ + plain?: boolean; + } + + interface SyncOptions { + /** + * If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table. + * Default false. + */ + force?: boolean; + + /** + * A function that logs sql queries, or false for no logging. + */ + logging?: any; + + /** + * The schema that the tables should be created in. This can be overriden for each table in sequelize.define. + * Default 'public'. + */ + schema?: string; + } + + interface ReplicationOptions { + read?: Array; + write?: Server; + } + + interface Server { + host?: string; + port?: number; + database?: string; + username?: string; + password?: string; + } + + interface DropOptions { + /** + * Also drop all objects depending on this table, such as views. Only works in postgres. + * + * Default false. + */ + cascade?: boolean; + } + + interface SchemaOptions { + /** + * The character(s) that separates the schema name from the table name. Default '.'. + */ + schemaDelimiter?: string; + } + + interface FindOptions { + /** + * A hash of attributes to describe your search. + */ + where?: any; + + /** + * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with two + * elements - the first is the name of the attribute in the DB (or some kind of expression such as + * Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the + * returned instance + */ + attributes?: Array; + + /** + * A list of associations to eagerly load. Supported is either { include?: [ Model1, Model2, ...] } or { include?: + * [ { model?: Model1, as?: 'Alias' } ] }. If your association are set up with an as (eg. X.hasMany(Y, { as?: 'Z }, + * you need to specify Z in the as attribute when eager loading Y). When using the object form, you can also + * specify attributes to specify what columns to load, where to limit the relations, and include to load further + * nested relations + */ + include?: any; + + /** + * Specifies an ordering. If a string is provided, it will be esacped. Using an array, you can provide several + * columns / functions to order by. Each element can be further wrapped in a two-element array. The first element + * is the column / function to order by, the second is the direction. For example?: order?: [['name', 'DESC']]. In + * this way the column will be escaped, but the direction will not. + */ + order?: any; + + limit?: number; + + offset?: number; + } + + interface BuildOptions { + /** + * If set to true, values will ignore field and virtual setters. Default false. + */ + raw?: boolean; + + /** + * Default true. + */ + isNewRecord?: boolean; + + /** + * Default true. + */ + isDirty?: boolean; + + /** + * an array of include options - Used to build prefetched/included model instances. See set. + */ + include?: Array; + } + + interface CopyOptions extends BuildOptions { + /** + * If set, only columns matching those in fields will be saved. + */ + fields?: Array; + + /** + * + */ + transaction?: Transaction; + } + + interface FindOrCreateOptions extends FindOptions, QueryOptions { + + } + + interface BulkCreateOptions { + /** + * Fields to insert (defaults to all fields). + */ + fields?: Array; + + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails + * validation. Default false. + */ + validate?: boolean; + + /** + * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run. Default false; + */ + hooks?: boolean; + + /** + * Ignore duplicate values for primary keys? (not supported by postgres). Default false. + */ + ignoreDuplicates?: boolean; + } + + interface DestroyOptions { + /** + * If set to true, destroy will find all records within the where parameter and will execute before-/ after + * bulkDestroy hooks on each row. + */ + hooks?: boolean; + + /** + * How many rows to delete + */ + limit?: number; + + /** + * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the + * where and limit options are ignored. + */ + truncate?: boolean; + } + + interface DestroyInstanceOptions { + /** + * If set to true, paranoid models will actually be deleted. + */ + force: boolean; + } + + interface InsertOptions { + limit?: number; + returning?: string; + allowNull?: string; + } + + interface UpdateOptions { + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails + * validation. Default true. + */ + validate?: boolean; + + /** + * Run before / after bulkUpdate hooks? Default false. + */ + hooks?: boolean; + + /** + * How many rows to update (only for mysql and mariadb). + */ + limit?: number; + } + + interface SetOptions { + /** + * If set to true, field and virtual setters will be ignored. Default false. + */ + raw?: boolean; + + /** + * Clear all previously set data values. Default false. + */ + reset?: boolean; + + include?: any; + } + + interface SaveOptions { + /** + * An alternative way of setting which fields should be persisted. + */ + fields?: any; + + /** + * If true, the updatedAt timestamp will not be updated. Default false. + */ + silent?: boolean; + + transaction?: Transaction; + } + + interface ValidateOptions { + /** + * An array of strings. All properties that are in this array will not be validated. + */ + skip: Array; + } + + interface IncrementOptions { + /** + * The number to increment by. Default 1. + */ + by?: number; + + transaction?: Transaction; + } + + interface IndexOptions { + indicesType?: string; + indexType?: string; + indexName?: string; + parser?: any; + } + + interface ProxyOptions { + /** + * An array of the events to proxy. Defaults to sql, error and success. + */ + events: Array; + } + + interface AssociationOptions { + /** + * Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For + * example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile + * will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks. + * Default false. + */ + hooks?: boolean; + + /** + * The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model + * if you want to define the junction table yourself and add extra attributes to it. + */ + through?: any; + + /** + * The alias of this model. If you create multiple associations between the same tables, you should provide an + * alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should + * provide the same alias when eager loading and when getting assocated models. Defaults to the singularized + * version of target.name + */ + as?: string; + + /** + * The foreignKey can be either a string name of the foreign key in the target table, + * or can be an object defining the foreign key and its options. Note foreignKey is not fully + * typed since TypeScript does not support union types--it can be either a string or an + * options object. String name defaults to the name of source + primary key of source. + * + * @see ForeignKeyAttributeOptions. + */ + foreignKey?: any; + + /** + * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. Default SET NULL. + */ + onDelete?: string; + + /** + * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. Default CASCADE. + */ + onUpdate?: string; + + /** + * Should on update and on delete constraints be enabled on the foreign key. + */ + constraints?: boolean; + } + + interface TriggerOptions { + insert?: Array; + update?: Array; + delete?: Array; + truncate?: Array; + } + + interface TriggerParam { + type: string; + direction?: string; + name?: string; + } + + interface SelectOptions { + limit?: number; + offset?: number; + attributes?: Array; + hasIncludeWhere?: boolean; + hasIncludeRequired?: boolean; + hasMultiAssociation?: boolean; + tableAs?: string; + table?: string; + include?: Array; + includeIgnoreAttributes?: boolean; + where?: any; + /** + * String field name or array of strings of field names. + */ + group?: any; + having?: any; + order?: any; + lock?: string; + } + + interface HashToWhereConditionsOption { + include?: boolean; + keysEscaped?: boolean; + } + + interface ModelMangerGetDaoOptions { + attribute: string; + } + + interface ModelManagerForEachDaoOptions { + /** + * Default true. + */ + reverse: boolean; + } + + interface MigratorOptions { + /** + * A flag that defines if the migrator should get instantiated or not.. + */ + force: boolean; + } + + interface FindAndCountResult { + /** + * The matching model instances. + */ + rows?: Array; + + /** + * The total number of rows. This may be more than the rows returned if a limit and/or offset was supplied. + */ + count?: number; + } + + interface Col { + /** + * Column name. + */ + col: string; + } + + interface Cast { + /** + * The value to cast. + */ + val: any; + + /** + * The type to cast it to. + */ + type: string; + } + + interface Literal { + val: any; + } + + interface And { + /** + * Each argument (string or object) will be joined by AND. + */ + args: Array; + } + + interface Or { + /** + * Each argument (string or object) will be joined by OR. + */ + args: Array; + } + + interface Where { + /** + * The attribute. + */ + attribute: string; + + /** + * The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.). + */ + logic: any; + } + + interface TransactionOptions { + /** + * + */ + autocommit?: boolean; + + /** + * One of: 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', 'SERIALIZABLE'. Default 'REPEATABLE READ'. + */ + isolationLevel?: string; + } + + interface QueryChainerRunSeriallyOptions { + /** + * If set to true, all pending emitters will be skipped if a previous emitter failed. Default false. + */ + skipOnError: boolean; + } + + interface CreateTableQueryOptions { + comment?: string; + uniqueKeys?: Array; + charset?: string; + } + + interface MigratorExecOptions { + before?: (migrator: Migrator) => void; + after?: (migrator: Migrator) => void; + success?: (migrator: Migrator) => void; + } + + interface MigrationExecuteOptions { + method: string; + } + + interface MigrationCompareOptions { + /** + * Default false. + */ + withoutEquals: boolean; + } + + interface Promise { + /** + * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * + * @param evt Event + * @param fct Handler + */ + on(evt: string, fct: () => void): void; + + /** + * Emit an event from the emitter. + * + * @param type The type of event. + * @param value All other arguments will be passed to the event listeners. + */ + emit(type: string, ...value: Array): void; + + /** + * Listen for success events. + */ + success(onSuccess: () => void): Promise; + + /** + * Alias for success(handler). Listen for success events. + */ + ok(onSuccess: () => void): Promise; + + /** + * Listen for error events. + * + * @param onError Error handler. + */ + error(onError: (err?: Error) => void): Promise; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError Error handler. + */ + fail(onError: (err?: Error) => void): Promise; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError Error handler. + */ + failure(onError: (err?: Error) => void): Promise; + + /** + * Listen for both success and error events.. + */ + done(handler: (err: Error, result?: any) => void): Promise; + + /** + * Alias for done(handler). Listen for both success and error events.. + */ + complete(handler: (err: Error, result?: any) => void): Promise; + + /** + * Attach a function that is called every time the function that created this emitter executes a query. + * + * @param onSQL + */ + sql(onSQL: (sql: string) => void): Promise; + + /** + * Proxy every event of this promise to another one. + * + * @param promise The promise that should receive the events. + * @param options Contains an array of the events to proxy. Defaults to sql, error and success + */ + proxy(promise: Promise, options?: ProxyOptions): Promise; + + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => Promise, onRejected?: (result?: any) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => void): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => void): PromiseT; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: any) => Promise): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: any) => PromiseT): PromiseT; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: any) => void): Promise; + } + + interface PromiseT extends Promise { + /** + * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * + * @param evt Event + * @param fct Handler + */ + on(evt: string, fct: (t: T) => void): void; + + /** + * Emit an event from the emitter. + * + * @param type The type of event. + * @param value All other arguments will be passed to the event listeners. + */ + emit(type: string, ...value: Array): void; + + /** + * Listen for success events. + */ + success(onSuccess: (t: T) => void): PromiseT; + + /** + * Alias for success(handler). Listen for success events. + */ + ok(onSuccess: (t: T) => void): PromiseT; + + /** + * Listen for both success and error events.. + */ + done(handler: (err: Error, result: T) => void): PromiseT; + + /** + * Alias for done(handler). Listen for both success and error events.. + */ + complete(handler: (err: Error, result: T) => void): PromiseT; + + /** + * Attach a function that is called every time the function that created this emitter executes a query. + * + * @param onSQL + */ + sql(onSQL: (sql: string) => void): PromiseT; + + /** + * Proxy every event of this promise to another one. + * + * @param promise The promise that should receive the events. + * @param options Contains an array of the events to proxy. Defaults to sql, error and success + */ + proxy(promise: PromiseT, options?: ProxyOptions): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => Promise, onRejected?: (result?: T) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => void): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: T) => Promise): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: T) => PromiseT): PromiseT; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: T) => void): Promise; + } + + interface Utils { + _: Lodash; + + /** + * Formats a string to parse and interpolate values into the string based on the optionally provided SQL dialect. + * @param arr Array where first element is string with placeholders and remaining attributes are values to replace placeholders. + * @param dialect SQL Dialect. + */ + format(arr: Array, dialect?: string): string; + + /** + * Formats a SQL string replacing named placeholders with values from the parameters object with matching key names. + * + * @param sql String to format. + * @param parameters Key/value hash with values to replace in string. + * @param dialect SQL Dialect + */ + formatNamedParameters(sql: string, parameters: any, dialect?: string): string; + + injectScope(scope: string, merge: boolean): any; + + smartWhere(whereArg: any, dialect: string): any; + + compileSmartWhere(obj: any, dialect: string): Array; + + getWhereLogic(logic: string, val?: any): string; + + isHash(obj: any): boolean; + + hasChanged(attrValue: any, value: any): boolean; + + argsArePrimaryKeys(args: Array, primaryKeys: any): boolean; + + /** + * Consistently combines two table names such that the alphabetically first name always comes first when combined. + * + * @param table1 + * @param table2 + */ + combineTableNames(table1: string, table2: string): string; + + singularize(s: string, language?: string): string; + + pluralize(s: string, language: string): string; + + /** + * Same concept as _.merge, but don't overwrite properties that have already been assigned + */ + mergeDefaults: typeof _.merge; + + lowercaseFirst(str: string): string; + + uppercaseFirst(str: string): string; + + spliceStr(str: string, index: number, count: number, add: string): string; + + camelize(str: string): string; + + removeCommentsFromFunctionString(s: string): string; + + toDefaultValue(value: any): any; + + defaultValueSchemable(value: any): boolean; + setAttributes(hash: any, identifier: string, instance: any, prefix: string): any; + removeNullValuesFromHash(hash: any, omitNull: boolean, options: any): any; + firstValueOfHash(obj: any): any; + inherit(subClass: any, superClass: any): any; + stack(): string; + now(dialect: string): Date; + + /** + * Runs provided function on next tick, depending on environment. + * + * @param f + */ + tick(f: Function): void; + + /** + * Surrounds a string with tick marks while removing all existing tick marks from the string. + * @param s String to tick + * @param tickChar Tick mark. Default ` + */ + addTicks(s: string, tickChar?: string): string; + + removeTicks(s: string, tickChar?: string): string; + + generateUUID(): string; + + validateParameter(value: any, expectation: any): boolean; + + CustomEventEmitter: EventEmitter; + Promise: Promise; + QueryChainer: QueryChainer; + Lingo: any; // external project, no definitions yet} + } + + interface Lodash extends _.LoDashStatic { + includes(str: string, needle: string): boolean; + camelizeIf(str: string, condition: boolean): string; + camelizeIf(str: string, condition: any): string; + underscoredIf(str: string, condition: boolean): string; + underscoredIf(str: string, condition: any): string; + /** + * * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered falsey. + * + * @param arr Array to compact. + */ + compactLite(arr: Array): Array; + } + + interface MetaPojo { + from: string; + to: string; + } + interface MetaInstance extends MetaPojo, Model { + + } + + interface DataTypeStringBase { + BINARY: DataTypeString; + } + interface DataTypeNumberBase { + UNSIGNED: boolean; + ZEROFILL: boolean; + } + + interface DataTypeString extends DataTypeStringBase { + } + interface DataTypeChar extends DataTypeStringBase { + } + interface DataTypeInteger extends DataTypeNumberBase { + } + interface DataTypeBigInt extends DataTypeNumberBase { + } + interface DataTypeFloat extends DataTypeNumberBase { + } + interface DataTypeBlob { + } + interface DataTypeDecimal { + PRECISION: number; + SCALE: number; + } + + interface DataTypeVirtual { + } + interface DataTypeEnum { + (...values: Array): DataTypeEnum; + } + interface DataTypeArray { + } + interface DataTypeHstore { + } + + interface DataTypes { + STRING: DataTypeString; + CHAR: DataTypeChar; + TEXT: string; + INTEGER: DataTypeInteger; + BIGINT: DataTypeBigInt; + DATE: string; + BOOLEAN: string; + FLOAT: DataTypeFloat; + NOW: string; + BLOB: DataTypeBlob; + DECIMAL: DataTypeDecimal; + UUID: string; + UUIDV1: string; + UUIDV4: string; + VIRTUAL: DataTypeVirtual; + NONE: DataTypeVirtual; + ENUM: DataTypeEnum; + ARRAY: DataTypeArray; + HSTORE: DataTypeHstore; + } + } + + var sequelize: sequelize.SequelizeStatic; + + export = sequelize; +} \ No newline at end of file diff --git a/stats/stats.d.ts b/stats/stats.d.ts index 48a2fc54f..e940212ee 100644 --- a/stats/stats.d.ts +++ b/stats/stats.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Stats.js r11 +// Type definitions for Stats.js r12 // Project: http://github.com/mrdoob/stats.js // Definitions by: Gregory Dalton // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/webaudioapi/readme.md b/webaudioapi/readme.md index 08eac0767..715eeda42 100644 --- a/webaudioapi/readme.md +++ b/webaudioapi/readme.md @@ -12,5 +12,7 @@ The WebKit nightly builds try to keep up with the editors draft version of the s ### Adding the reference to your project /// + or - /// \ No newline at end of file + + /// diff --git a/webaudioapi/waa-tests.ts b/webaudioapi/waa-tests.ts index 505f6214e..fc92bd06a 100644 --- a/webaudioapi/waa-tests.ts +++ b/webaudioapi/waa-tests.ts @@ -323,3 +323,11 @@ declare var footstepsBuffer: any; context.startRendering(); } +// Test automatic type inference of the audio processing event handler +() => { + var context = new AudioContext(); + var recorder = context.createScriptProcessor(2048, 1, 1); + recorder.onaudioprocess = function (e) { + e.inputBuffer; + }; +} diff --git a/webaudioapi/waa.d.ts b/webaudioapi/waa.d.ts index 128855da8..59fab23ce 100644 --- a/webaudioapi/waa.d.ts +++ b/webaudioapi/waa.d.ts @@ -601,6 +601,10 @@ interface AudioBufferSourceNode extends AudioNode { interface MediaElementAudioSourceNode extends AudioNode { } +interface AudioProcessingEventHandler { + (e: AudioProcessingEvent): void; +} + /** * This interface is an AudioNode which can generate, process, or analyse audio directly using JavaScript. * @@ -617,7 +621,7 @@ interface ScriptProcessorNode extends AudioNode { /** * An event listener which is called periodically for audio processing. An event of type AudioProcessingEvent will be passed to the event handler. */ - onaudioprocess: EventHandler; + onaudioprocess: AudioProcessingEventHandler; /** * The size of the buffer (in sample-frames) which needs to be processed each time onprocessaudio is called. Legal values are (256, 512, 1024, 2048, 4096, 8192, 16384).