diff --git a/.gitignore b/.gitignore index 4f0152028d3433..94299767d978f3 100644 --- a/.gitignore +++ b/.gitignore @@ -35,5 +35,5 @@ node_modules .sublimets .settings/launch.json - .vscode +yarn.lock \ No newline at end of file diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 44f0d8e9a03fdf..8b263f19aefbc4 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii) * [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000) * [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped) +* [:link:](ejson/ejson.d.ts) [ejson](https://www.npmjs.com/package/ejson) by [Shantanu Bhadoria](https://github.com/shantanubhadoria) * [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped) * [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan) * [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak) @@ -1189,7 +1190,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](ng-stomp/ng-stomp.d.ts) [ngStomp](https://github.com/beevelop/ng-stomp) by [Lukasz Potapczuk](https://github.com/lpotapczuk) * [:link:](ngstorage/ngstorage.d.ts) [ngstorage](https://github.com/gsklee/ngStorage) by [Jakub Pistek](https://github.com/kubiq) * [:link:](nightmare/nightmare.d.ts) [Nightmare](https://github.com/segmentio/nightmare) by [horiuchi](https://github.com/horiuchi) -* [:link:](noble/noble.d.ts) [noble](https://github.com/sandeepmistry/noble) by [Seon-Wook Park](https://github.com/swook), [Hans Bakker](https://github.com/wind-rider) +* [:link:](noble/noble.d.ts) [noble](https://github.com/sandeepmistry/noble) by [Seon-Wook Park](https://github.com/swook), [Hans Bakker](https://github.com/wind-rider), [Shantanu Bhadoria](https://github.com/shantanubhadoria) * [:link:](nock/nock.d.ts) [nock](https://github.com/pgte/nock) by [bonnici](https://github.com/bonnici) * [:link:](node-imap/imap.d.ts) [node imap](https://github.com/mscdex/node-imap) by [Steve Fenton](https://github.com/Steve-Fenton) * [:link:](oauth2-server/oauth2-server.d.ts) [Node OAuth2 Server](https://github.com/thomseddon/node-oauth2-server) by [Robbie Van Gorkom](https://github.com/vangorra) diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 730bd78af2b5db..053b2c3eaea9d7 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,8 +1,16 @@ -case 1. Add a new type definition. -- [ ] checked compilation succeeds with `--target es6` and `--noImplicitAny` options. -- [ ] has correct [naming convention](http://definitelytyped.org/guides/contributing.html#naming-the-file) -- [ ] has a [test file](http://definitelytyped.org/guides/contributing.html#tests) with the suffix of `-tests.ts` or `-tests.tsx`. +Please fill in this template. -case 2. Improvement to existing type definition. -- documentation or source code reference which provides context for the suggested changes. url http://api.jquery.com/html . - - it has been reviewed by a DefinitelyTyped member. +- [ ] Prefer to make your PR against the `types-2.0` branch. +- [ ] The package does not provide its own types, and you can not add them. +- [ ] Test the change in your own code. +- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped#make-a-pull-request). +- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes). + +If adding a new definition: +- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package. +- [ ] Run `tsc` without errors. +- [ ] Include the required [files](https://github.com/DefinitelyTyped/DefinitelyTyped#create-a-new-package) and header. + +If changing an existing definition: +- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <> +- [ ] Increase the version number in the header if appropriate. diff --git a/README.md b/README.md index 7da7d1530bc91e..8caef8c8e2b9c1 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ The `Project` link does not have to be to GitHub, but prefer linking to a source "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -149,14 +149,18 @@ and you may also add the `"jsx"` compiler option if your library needs it. DefinitelyTyped members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down. +For a good example package, see [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/types-2.0/base64-js). #### Common mistakes * First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html). * Formatting: Either use all tabs, or always use 4 spaces. Also, always use semicolons, and use egyptian braces. * `interface X {}`: An empty interface is essentially the `{}` type: it places no constraints on an object. -* `interface Foo { new(): Foo }`: +* `interface IFoo {}`: Don't add `I` to the front of an interface name. +* `interface Foo { new(): Foo; }`: This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); } +* `const Class: { new(): IClass; }`: + Prefer to use a class declaration `class Class { constructor(); }` instead of a new-able constant. * `namespace foo {}`: Do not add a namespace just so that the `import * as foo` syntax will work. If it is commonJs module with a single export, you should use the `import foo = require("foo")` syntax. @@ -194,7 +198,7 @@ Changes to the `master` branch are also manually merged into the `types-2.0` bra #### I'm writing a definition that depends on another definition. Should I use `` or an import? -If the module you're referencing is an written as an external module (uses `export`), use an import. +If the module you're referencing is an external module (uses `export`), use an import. If the module you're referenceing is an ambient module (uses `declare module`, or just declares globals), use ``. #### What do I do about older versions of typings? @@ -209,6 +213,10 @@ A `package.json` may be included for the sake of specifying dependencies. Here's We do not allow other fields, such as `"description"`, to be defined manually. Also, if you need to reference an older version of typings, you must do that by adding `"dependencies": { "@types/foo": "x.y.z" }` to the package.json. +#### I notice some `tsconfig.json` are missing `"noImplicitAny": true` or `"strictNullChecks": true`. + +Then they are wrong. You can help by submitting a pull request to fix them. + #### Definitions in types-2.0 seem written differently than in master. If you're targeting types-2.0, write it like the types-2.0 definitions. diff --git a/ajv/index.d.ts b/ajv/index.d.ts index 691b6b6ad04cb2..bf487fd34189b7 100644 --- a/ajv/index.d.ts +++ b/ajv/index.d.ts @@ -81,7 +81,7 @@ declare namespace Ajv { passContext?: boolean; loopRequired?: number; ownProperties?: boolean; - multipleOfPrecision?: boolean; + multipleOfPrecision?: boolean | number; errorDataPath?: string, messages?: boolean; beautify?: boolean; diff --git a/angular-material/index.d.ts b/angular-material/index.d.ts index 610dcf34d747b2..7895732ada2996 100644 --- a/angular-material/index.d.ts +++ b/angular-material/index.d.ts @@ -336,6 +336,7 @@ declare module 'angular' { onRemoving?: Function; onDomRemoved?: Function; origin?: string | JQuery | Element; + onCloseSuccess?: ((panel: IPanelRef, closeReason: string) => any); } interface IPanelRef { @@ -408,6 +409,16 @@ declare module 'angular' { interceptorTypes: { CLOSE: string, }; + closeReasons: { + CLICK_OUTSIDE: string, + ESCAPE: string, + }; + absPosition: { + TOP: string, + RIGHT: string, + BOTTOM: string, + LEFT: string, + }; } } } diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index 8e0711d6f78e76..29a344426f8da2 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -191,8 +191,25 @@ mod.controller({ MyCtrl2: function() {}, MyCtrl3: ['$fooService', function($fooService: any) { }] }); -mod.directive('name', function ($scope: ng.IScope) { }) -mod.directive('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => { + return (scope, el, attrs) => { + let foo = 'none'; + el.click(e => { + foo = e.type; + $rootScope.$apply(); + }); + scope.$watch(() => foo, () => el.text(foo)); + }; +}); +mod.directive('myDirectiveB', ['$rootScope', function ($rootScope: ng.IRootScopeService) { + return { + link(scope, el, attrs) { + el.click(e => { + el.hide(); + }); + } + }; +}]); mod.directive({ myFooDir: () => ({ template: 'my-foo-dir.tpl.html' diff --git a/angular/index.d.ts b/angular/index.d.ts index 62deb4742f5281..d07777d2cfdcc4 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -1775,7 +1775,7 @@ declare namespace angular { /////////////////////////////////////////////////////////////////////////// interface IDirectiveFactory { - (...args: any[]): IDirective; + (...args: any[]): IDirective | IDirectiveLinkFn; } interface IDirectiveLinkFn { @@ -1783,8 +1783,8 @@ declare namespace angular { scope: IScope, instanceElement: JQuery, instanceAttributes: IAttributes, - controller: {}, - transclude: ITranscludeFunction + controller?: IController | IController[] | {[key: string]: IController}, + transclude?: ITranscludeFunction ): void; } @@ -1812,7 +1812,6 @@ declare namespace angular { controller?: string | Injectable; controllerAs?: string; /** - * @deprecated * Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before * the controller constructor is called, this use is now deprecated. Please place initialization code that * relies upon bindings inside a $onInit method on the controller, instead. diff --git a/async/async-tests.ts b/async/async-tests.ts index b7245823683e18..c4a35064153cbb 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -1,9 +1,10 @@ /// import fs = require("fs"); +import process = require("process"); -var path: { - exists: (path: string, callback?: (err: string, exists: boolean) => any) => void; +declare var path: { + exists: (path: string, callback?: (err: Error, exists: boolean) => any) => void; }; function callback() { } @@ -33,8 +34,8 @@ async.series([ function () { } ]); -var data = []; -function asyncProcess(item, callback) { } +var data: any[] = []; +function asyncProcess(item: any, callback: (err: Error, result: any) => void) { } async.map(data, asyncProcess, function (err, results) { console.log(results); }); @@ -49,11 +50,11 @@ var saveFile = function () { } async.each(openFiles, saveFile, function (err) { }); async.eachSeries(openFiles, saveFile, function (err) { }); -var documents, requestApi; +var documents: any, requestApi: any; async.eachLimit(documents, 20, requestApi, function (err) { }); // forEachOf* functions. May accept array or object. -function forEachOfIterator(item, key, forEachOfIteratorCallback) { +function forEachOfIterator(item: string, key: string, forEachOfIteratorCallback: any) { console.log("ForEach: item=" + item + ", key=" + key); forEachOfIteratorCallback(); } @@ -64,9 +65,8 @@ async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { }); async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { }); async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { }); -var process; var numArray = [1, 2, 3]; -function reducer(memo, item, callback) { +function reducer(memo: any, item: any, callback: any) { process.nextTick(function () { callback(null, memo + item) }); @@ -103,20 +103,20 @@ async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { async.series([ function (callback) { - callback(null, 'one'); + callback(undefined, 'one'); }, function (callback) { - callback(null, 'two'); + callback(undefined, 'two'); }, ], function (err, results) { }); async.series([ function (callback) { - callback(null, 'one'); + callback(undefined, 'one'); }, function (callback) { - callback(null, 'two'); + callback(undefined, 'two'); }, ], function (err, results) { }); @@ -124,12 +124,12 @@ function (err, results) { }); async.series({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, @@ -138,25 +138,25 @@ function (err, results) { }); async.series({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, function (err, results) { }); async.times(5, function(n, next) { - next(null, n) + next(undefined as any, n) }, function(err, results) { console.log(results) }) async.timesSeries(5, function(n, next) { - next(null, n) + next(undefined as any, n) }, function(err, results) { console.log(results) }) @@ -164,12 +164,12 @@ async.timesSeries(5, function(n, next) { async.parallel([ function (callback) { setTimeout(function () { - callback(null, 'one'); + callback(undefined, 'one'); }, 200); }, function (callback) { setTimeout(function () { - callback(null, 'two'); + callback(undefined, 'two'); }, 100); }, ], @@ -178,12 +178,12 @@ function (err, results) { }); async.parallel([ function (callback) { setTimeout(function () { - callback(null, 'one'); + callback(undefined, 'one'); }, 200); }, function (callback) { setTimeout(function () { - callback(null, 'two'); + callback(undefined, 'two'); }, 100); }, ], @@ -193,12 +193,12 @@ function (err, results) { }); async.parallel({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, @@ -207,12 +207,12 @@ function (err, results) { }); async.parallel({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, @@ -221,12 +221,12 @@ async.parallel({ async.parallelLimit({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, @@ -235,7 +235,7 @@ async.parallelLimit({ ); -function whileFn(callback) { +function whileFn(callback: any) { count++; setTimeout(callback, 1000); } @@ -258,19 +258,19 @@ async.forever(function (errBack) { ); async.waterfall([ - function (callback) { + function (callback: any) { callback(null, 'one', 'two'); }, - function (arg1, arg2, callback) { + function (arg1: any, arg2: any, callback: any) { callback(null, 'three'); }, - function (arg1, callback) { + function (arg1: any, callback: any) { callback(null, 'done'); } ], function (err, result) { }); -var q = async.queue(function (task: any, callback) { +var q = async.queue(function (task: any, callback: any) { console.log('hello ' + task.name); callback(); }, 2); @@ -323,7 +323,7 @@ q.resume(); q.kill(); // tests for strongly typed tasks -var q2 = async.queue(function (task: string, callback) { +var q2 = async.queue(function (task: string, callback: any) { console.log('Task: ' + task); callback(); }, 1); @@ -358,26 +358,26 @@ var cargo = async.cargo(function (tasks, callback) { // add some items -cargo.push({ name: 'foo' }, function (err) { +cargo.push({ name: 'foo' }, function (err: Error) { console.log('finished processing foo'); }); -cargo.push({ name: 'bar' }, function (err) { +cargo.push({ name: 'bar' }, function (err: Error) { console.log('finished processing bar'); }); -cargo.push({ name: 'baz' }, function (err) { +cargo.push({ name: 'baz' }, function (err: Error) { console.log('finished processing baz'); }); var filename = ''; async.auto({ - get_data: function (callback) { }, - make_folder: function (callback) { }, + get_data: function (callback: any) { }, + make_folder: function (callback: any) { }, //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback) { + write_file: ['get_data', 'make_folder', function (callback: any) { callback(null, filename); }], //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback, results) { }] + email_link: ['write_file', function (callback: any, results: any) { }] }); async.retry(3, function (callback, results) { }, function (err, result) { }); @@ -411,13 +411,13 @@ async.parallel([ }, ]); -var call_order = []; +var call_order: string[] = []; async.nextTick(function () { call_order.push('two'); }); call_order.push('one'); -var slow_fn = function (name, callback) { +var slow_fn = function (name: string, callback: any) { callback(null, 123); }; var fn = async.memoize(slow_fn); @@ -427,15 +427,369 @@ async.ensureAsync(function () { }); async.constant(42); async.asyncify(function () { }); -async.log(function (name, callback) { +async.log(function (name: any, callback: any) { setTimeout(function () { callback(null, 'hello ' + name); }, 0); }, "world" ); -async.dir(function (name, callback) { +async.dir(function (name: string, callback: any) { setTimeout(function () { callback(null, { hello: name }); }, 1000); }, "world"); + +// each + +async.each({ + "a": 1, + "b": 2 +}, function(val: number, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.each: ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.each: done."); + +}); + +async.eachSeries({ + "a": 1, + "b": 2 +}, function(val: number, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.eachSeries: ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.eachSeries: done."); + +}); + +async.eachLimit({ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + "f": 6 +}, 2, function(val: number, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.eachLimit: ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.eachLimit: done."); + +}); + +// forEachOf/eachOf + +async.eachOf({ + "a": 1, + "b": 2 +}, function(val: number, key: string, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.forEachOf/eachOf: ${key} = ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.forEachOf/eachOf: done."); + +}); + +async.forEachOfSeries({ + "a": 1, + "b": 2 +}, function(val: number, key: string, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.forEachOfSeries: ${key} = ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.forEachOfSeries: done."); + +}); + +async.forEachOfLimit({ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + "f": 6 +}, 2, function(val: number, key: string, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.forEachOfLimit: ${key} = ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.forEachOfLimit: done."); + +}); + +// map + +async.map({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.map: ${val}`); + + next(undefined as any, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.map: done with results", results); + +}); + +async.mapSeries({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.mapSeries: ${val}`); + + next(undefined as any, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.mapSeries: done with results", results); + +}); + +async.mapLimit({ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + "f": 6 +}, 2, function(val: number, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.mapLimit: ${val}`); + + next(undefined as any, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.mapLimit: done with results", results); + +}); + +// mapValues + +async.mapValues({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, key: string, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.mapValues: ${key} = ${val}`); + + next(undefined as any, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.mapValues: done with results", results); + +}); + +async.mapValuesSeries({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, key: string, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.mapValuesSeries: ${key} = ${val}`); + + next(undefined as any, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.mapValuesSeries: done with results", results); + +}); + +// filter/select/reject + +async.filter({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, next: AsyncBooleanResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.filter/select: ${val}`); + + next(undefined as any, val % 2 === 0); + + }, 500); + +}, function(err: Error, results: number[]): void { + + console.log("async.filter/select: done with results", results); + +}); + +async.reject({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, next: AsyncBooleanResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.reject: ${val}`); + + next(undefined as any, val % 2 === 0); + + }, 500); + +}, function(err: Error, results: number[]): void { + + console.log("async.reject: done with results", results); + +}); + +// concat + +async.concat({ + "a": "1", + "b": "2", + "c": "3" +}, function(item: string, next: AsyncResultCallback): void { + + console.log(`async.concat: ${item}`); + + next(undefined as any, [item, item, item]); + +}, function(err: Error, results: string[]) { + + console.log("async.concat: done with results", results); + +}); + +// detect/find + +async.detect({ + "a": 1, + "b": 2, + "c": 3 +}, function(item: number, next: AsyncBooleanResultCallback): void { + + console.log(`async.detect/find: ${item}`); + + next(undefined as any, item > 1); + +}, function(err: Error, result: number) { + + if (err) { + + console.log(err); + + } else { + + console.log("async.detect/find: done with result", result); + } + +}); + +// every/all + +async.every({ + "a": 1, + "b": 2, + "c": 3 +}, function(item: number, next: AsyncBooleanResultCallback): void { + + console.log(`async.every/all: ${item}`); + + next(undefined as any, item > 0); + +}, function(err: Error, result: boolean) { + + console.log("async.every/all: done with result", result); + +}); + +// some/any + +async.some({ + "a": 1, + "b": 2, + "c": 3 +}, function(item: number, next: AsyncBooleanResultCallback): void { + + console.log(`async.some/any: ${item}`); + + next(undefined as any, item > 2); + +}, function(err: Error, result: boolean) { + + console.log("async.some/any: done with result", result); + +}); diff --git a/async/index.d.ts b/async/index.d.ts index 96da35c1ead43f..8b564fbd807aa4 100644 --- a/async/index.d.ts +++ b/async/index.d.ts @@ -1,11 +1,13 @@ // Type definitions for Async 2.0.1 // Project: https://github.com/caolan/async -// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman +// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman , Angus Fenying // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Dictionary { [key: string]: T; } interface ErrorCallback { (err?: Error): void; } +interface AsyncWaterfallCallback { (err: Error, ...args: any[]): void; } +interface AsyncBooleanResultCallback { (err: Error, truthValue: boolean): void; } interface AsyncResultCallback { (err: Error, result: T): void; } interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } @@ -15,7 +17,7 @@ interface AsyncIterator { (item: T, callback: ErrorCallback): void; } interface AsyncForEachOfIterator { (item: T, key: number|string, callback: ErrorCallback): void; } interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } -interface AsyncBooleanIterator { (item: T, callback: (err: string, truthValue: boolean) => void): void; } +interface AsyncBooleanIterator { (item: T, callback: AsyncBooleanResultCallback): void; } interface AsyncWorker { (task: T, callback: ErrorCallback): void; } interface AsyncVoidFunction { (callback: ErrorCallback): void; } @@ -89,52 +91,74 @@ interface Async { // Collections each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; - eachSeries(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; + each(arr: Dictionary, iterator: AsyncIterator, callback?: ErrorCallback): void; + eachSeries: typeof async.each; eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; - forEachOf(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; + eachLimit(arr: Dictionary, limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; + forEach: typeof async.each; + forEachSeries: typeof async.each; + forEachLimit: typeof async.eachLimit; forEachOf(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - forEachOfSeries(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; - forEachOfSeries(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOf(obj: Dictionary, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfSeries: typeof async.forEachOf; forEachOfLimit(obj: T[], limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - mapSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - mapValuesLimit(obj: {[name: string]: T}, limit: number, iteratee: (value: string, key: T, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; - mapValues(obj: {[name: string]: T}, iteratee: (value: string, key: T, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + forEachOfLimit(obj: Dictionary, limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + eachOf: typeof async.forEachOf; + eachOfSeries: typeof async.forEachOf; + eachOfLimit: typeof async.forEachOfLimit; + map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + map(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + mapSeries: typeof async.map; + mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + mapLimit(arr: Dictionary, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; mapValuesSeries: typeof async.mapValues; - filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - select(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - filterSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - selectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - selectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - reject(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - rejectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - rejectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; - inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; - foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; - reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - detect(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filter(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filterSeries: typeof async.filter; + filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filterLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + select: typeof async.filter; + selectSeries: typeof async.filter; + selectLimit: typeof async.filterLimit; + reject: typeof async.filter; + rejectSeries: typeof async.filter; + rejectLimit: typeof async.filterLimit; + reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): void; + inject: typeof async.reduce; + foldl: typeof async.reduce; + reduceRight: typeof async.reduce; + foldr: typeof async.reduce; + detect(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detect(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detectSeries: typeof async.detect; + detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detectLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; find: typeof async.detect; - detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; - findSeries: typeof async.detectSeries; - detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + findSeries: typeof async.detect; findLimit: typeof async.detectLimit; - sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - some(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; - someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; - anyLimit: typeof async.someLimit; - someSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + some(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + some(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + someSeries: typeof async.some; + someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + someLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + any: typeof async.some; anySeries: typeof async.someSeries; - any(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; - every(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; - everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; - all(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; - concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - concatSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + anyLimit: typeof async.someLimit; + every(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + every(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + everySeries: typeof async.every; + everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + everyLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + all: typeof async.every; + allSeries: typeof async.every; + allLimit: typeof async.everyLimit; + + concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + concat(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + concatSeries: typeof async.concat; // Control Flow series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; @@ -143,14 +167,14 @@ interface Async { parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; - whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void; - forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void; - waterfall(tasks: Function[], callback?: (err: Error, results?: any) => void): void; + whilst(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; + doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; + until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; + doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; + during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; + doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; + forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; + waterfall(tasks: Function[], callback?: AsyncResultCallback): void; compose(...fns: Function[]): Function; seq(...fns: Function[]): Function; applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. @@ -158,19 +182,15 @@ interface Async { queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; - auto(tasks: any, concurrency?: number, callback?: (error: Error, results: any) => void): void; - autoInject(tasks: any, callback?: (error: Error, results: any) => void): void; - retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: (error: Error, results: any) => void): void; - retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; + auto(tasks: any, concurrency?: number, callback?: AsyncResultCallback): void; + autoInject(tasks: any, callback?: AsyncResultCallback): void; + retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: AsyncResultCallback): void; + retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: AsyncResultCallback): void; retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; apply(fn: Function, ...arguments: any[]): AsyncFunction; nextTick(callback: Function, ...args: any[]): void; setImmediate: typeof async.nextTick; - allLimit(arr: T[], limit: number, iteratee: AsyncBooleanIterator, cb?: (result: boolean) => any) : any; - everySeries(arr: T[], iteratee: AsyncBooleanIterator, cb?: (result: boolean) => any) : any - allSeries: typeof async.everySeries; - reflect(fn: AsyncFunction) : (callback: (err: void, result: {error?: Error, value?: T}) => void) => void; reflectAll(tasks: AsyncFunction[]): ((callback: (err: void, result: {error?: Error, value?: T}) => void) => void)[]; diff --git a/async/tsconfig.json b/async/tsconfig.json index c655cc101ae26b..5c890605cd5886 100644 --- a/async/tsconfig.json +++ b/async/tsconfig.json @@ -2,8 +2,8 @@ "compilerOptions": { "module": "commonjs", "target": "es6", - "noImplicitAny": false, - "strictNullChecks": false, + "noImplicitAny": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/aws-sdk/index.d.ts b/aws-sdk/index.d.ts index 031047490fb0ee..fbee8f926c8985 100644 --- a/aws-sdk/index.d.ts +++ b/aws-sdk/index.d.ts @@ -428,7 +428,8 @@ export declare class S3 { endpoint: Endpoint; getObject(params: s3.GetObjectRequest, callback?: (err: Error, data: any) => void): any; - putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void; + putObject(params: s3.PutObjectRequest, callback?: (err: Error, data: any) => void): any; + copyObject(params: s3.CopyObjectRequest, callback?: (err: Error, data: any) => void): any; deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void; headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; getSignedUrl(operation: string, params: any): string; @@ -2303,6 +2304,40 @@ export declare module s3 { WebsiteRedirectLocation?: string; } + export interface CopyObjectRequest { + Bucket: string; + CopySource: string; + Key: string; + ACL?: string; + CacheControl?: string; + ContentDisposition?: string; + ContentEncoding?: string; + ContentLanguage?: string; + ContentType?: string; + CopySourceIfMatch?: string; + CopySourceIfModifiedSince?: any; + CopySourceIfNoneMatch?: string; + CopySourceIfUnmodifiedSince?: any; + CopySourceSSECustomerAlgorithm?: string; + CopySourceSSECustomerKey?: any; + CopySourceSSECustomerKeyMD5?: string; + Expires?: any; + GrantFullControl?: string; + GrantRead?: string; + GrantReadACP?: string; + GrantWriteACP?: string; + Metadata?: { [key: string]: string; }; + MetadataDirective?: string; + RequestPayer?: string; + SSECustomerAlgorithm?: string; + SSECustomerKey?: any; + SSECustomerKeyMD5?: string; + SSEKMSKeyId?: string; + ServerSideEncryption?: string; + StorageClass?: string; + WebsiteRedirectLocation?: string; + } + export interface GetObjectRequest { Bucket: string; IfMatch?: string; diff --git a/bootstrap-select/bootstrap-select-tests.ts b/bootstrap-select/bootstrap-select-tests.ts new file mode 100644 index 00000000000000..e2e8c885604205 --- /dev/null +++ b/bootstrap-select/bootstrap-select-tests.ts @@ -0,0 +1,40 @@ +/// + +$(".selectpicker").selectpicker({ + actionsBox: true, + container: "body", + countSelectedText: "counts > #", + deselectAllText: "test", + dropdownAlignRight: true, + dropupAuto: true, + header: "test", + hideDisabled: true, + iconBase: "fa", + liveSearch: true, + liveSearchNormalize: true, + liveSearchPlaceholder: "test", + liveSearchStyle: "contains", + maxOptions: 10, + maxOptionsText: "test", + mobile: true, + multipleSeparator: ", ", + noneSelectedText: "test", + selectAllText: "test", + selectedTextFormat: "values", + selectOnTab: true, + showContent: true, + showIcon: true, + showSubtext: true, + showTick: true, + size: "auto", + style: "test", + tickIcon: "test", + title: "test", + width: "auto" +}) + +$(".selectpicker").selectpicker("val", "foo") +$(".selectpicker").selectpicker("val", ["foo", "bar"]) +$(".selectpicker").selectpicker("selectAll") +$(".selectpicker").selectpicker("setStyle", "btn-large", "add") + diff --git a/bootstrap-select/index.d.ts b/bootstrap-select/index.d.ts new file mode 100644 index 00000000000000..5f511685ba0cb8 --- /dev/null +++ b/bootstrap-select/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for bootstrap-select v1.11.2 +// Project: https://silviomoreto.github.io/bootstrap-select/ +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface BootstrapSelectOptions { + actionsBox?: boolean + container?: string | boolean + countSelectedText?: string | Function + deselectAllText?: string + dropdownAlignRight?: string | boolean + dropupAuto?: boolean + header?: string + hideDisabled?: boolean + iconBase?: string + liveSearch?: boolean + liveSearchNormalize?: boolean + liveSearchPlaceholder?: string + liveSearchStyle?: string + maxOptions?: number | boolean + maxOptionsText?: string | Array | Function + mobile?: boolean + multipleSeparator?: string + noneSelectedText?: string + selectAllText?: string + selectedTextFormat?: string + selectOnTab?: boolean + showContent?: boolean + showIcon?: boolean + showSubtext?: boolean + showTick?: boolean + size?: string | number | boolean + style?: string + tickIcon?: string + title?: string + width?: string | boolean +} + +interface JQuery { + selectpicker(opts?: BootstrapSelectOptions): void + selectpicker(method: string, ...args: Array>): void +} diff --git a/bootstrap-select/tsconfig.json b/bootstrap-select/tsconfig.json new file mode 100644 index 00000000000000..366216ab7f3c15 --- /dev/null +++ b/bootstrap-select/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bootstrap-select-tests.ts" + ] +} \ No newline at end of file diff --git a/chance/index.d.ts b/chance/index.d.ts index 6390b5786436ad..7ce79b431f141b 100644 --- a/chance/index.d.ts +++ b/chance/index.d.ts @@ -5,13 +5,19 @@ declare namespace Chance { + interface Seeded { + seed: number; + } + + type SeededChance = Chance & Seeded; + interface ChanceStatic { (): Chance - (seed: number): Chance + (seed: number): SeededChance (generator: () => any): Chance new(): Chance; - new(seed: number): Chance; + new(seed: number): SeededChance; new(generator: () => any): Chance; } diff --git a/color/color-tests.ts b/color/color-tests.ts new file mode 100644 index 00000000000000..1b2d9369e0b584 --- /dev/null +++ b/color/color-tests.ts @@ -0,0 +1,79 @@ +import * as Color from "color" + +var color: Color.Color = Color("white") +var colorOther: Color.Color = Color("black") + +var colorRGB: Color.Color = color.rgb(0, 0, 0) +var colorRGB: Color.Color = color.rgb([0, 0, 0]) +var rgb: Color.RGBColor = color.rgb() + +var colorHSL: Color.Color = color.hsl([0, 0, 0]) +var hsl: Color.HSLColor = color.hsl() + +var colorHSV: Color.Color = color.hsv([0, 0, 0]) +var hsv: Color.HSVColor = color.hsv() + +var colorHBW: Color.Color = color.hbw([0, 0, 0]) +var hbw: Color.HBWColor = color.hbw() + +var colorCMYK: Color.Color = color.cmyk([0, 0, 0, 0]) +var cmyk: Color.CMYKColor = color.cmyk() + +var hex: string = color.hexString() +var percent: string = color.percentString() +var keyword: string | void = color.keyword() +var alpha: number = color.alpha() +var red: number = color.red() +var green: number = color.green() +var blue: number = color.blue() +var hue: number = color.hue() +var saturation: number = color.saturation() +var lightness: number = color.lightness() +var saturationv: number = color.saturationv() +var value: number = color.value() +var whiteness: number = color.whiteness() +var blackness: number = color.blackness() +var cyan: number = color.cyan() +var magenta: number = color.magenta() +var yellow: number = color.yellow() +var black: number = color.black() +var luminosity: number = color.luminosity() +var contrast: number = color.contrast(colorOther) +var dark: boolean = color.dark() +var light: boolean = color.light() +var level: string = color.level(colorOther) + +var chain: Color.Color = color + .rgb(0, 0, 0) + .hsl([0, 0, 0]) + .hsv([0, 0, 0]) + .hbw([0, 0, 0]) + .cmyk([0, 0, 0 ,0]) + .alpha(0) + .red(0) + .green(0) + .blue(0) + .hue(0) + .saturation(0) + .lightness(0) + .saturationv(0) + .value(0) + .whiteness(0) + .blackness(0) + .cyan(0) + .magenta(0) + .yellow(0) + .black(0) + .negate() + .lighten(0) + .darken(0) + .saturate(0) + .desaturate(0) + .greyscale() + .whiten(0) + .blacken(0) + .clearer(0) + .opaquer(0) + .rotate(0) + .mix(colorOther, 0) + .clone() diff --git a/color/index.d.ts b/color/index.d.ts new file mode 100644 index 00000000000000..0395cd1bf90c94 --- /dev/null +++ b/color/index.d.ts @@ -0,0 +1,161 @@ +// Type definitions for color v0.12.0 +// Project: https://github.com/qix-/color +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Color { + + interface RGBColor { + r: number + g: number + b: number + a?: number + } + + interface FullRGBColor { + red: number + green: number + blue: number + alpha?: number + } + + interface HSLColor { + h: number + s: number + l: number + a?: number + } + + interface FullHSLColor { + hue: number + saturation: number + lightness: number + alpha?: number + } + + interface HSVColor { + h: number + s: number + v: number + } + + interface FullHSVColor { + hue: number + saturation: number + value: number + } + + interface HBWColor { + h: number + b: number + w: number + } + + interface FullHBWColor { + hue: number + whiteness: number + blackness: number + } + + interface CMYKColor { + c: number + m: number + y: number + k: number + } + + interface FullCMYKColor { + cyan: number + magenta: number + yellow: number + black: number + } + + type ColorParam = string | RGBColor | FullRGBColor | HSLColor | FullHSLColor | HSVColor + | FullHSVColor | HBWColor | FullHBWColor | CMYKColor | FullCMYKColor + + interface Color { + (color: ColorParam | Color) : Color + rgb(values: Array): Color + rgb(r: number, g: number, b: number, a?: number): Color + rgb(values: RGBColor): Color + rgb(values: FullRGBColor): Color + rgb(): RGBColor + rgbArray(): Array + rgbString(): string + rgbaString(): string + rgbNumber(): number + hsl(values: Array): Color + hsl(): HSLColor + hslArray(): Array + hslString(): string + hslaString(): string + hsv(values: Array): Color + hsv(): HSVColor + hsvArray(): Array + hsvString(): string + hbw(values: Array): Color + hbw(): HBWColor + hbwArray(): Array + hbwString(): string + cmyk(values: Array): Color + cmyk(): CMYKColor + cmykArray(): Array + cmykString(): string + hexString(): string + percentString(): string + keyword(): string | void + alpha(alpha: number): Color + alpha(): number + red(red: number): Color + red(): number + green(green: number): Color + green(): number + blue(blue: number): Color + blue(): number + hue(hue: number): Color + hue(): number + saturation(saturation: number): Color + saturation(): number + lightness(lightness: number): Color + lightness(): number + saturationv(saturationv: number): Color + saturationv(): number + value(value: number): Color + value(): number + whiteness(whiteness: number): Color + whiteness(): number + blackness(blackness: number): Color + blackness(): number + cyan(cyan: number): Color + cyan(): number + magenta(magenta: number): Color + magenta(): number + yellow(yellow: number): Color + yellow(): number + black(black: number): Color + black(): number + luminosity(): number + contrast(color: Color): number + dark(): boolean + light(): boolean + negate(): Color + lighten(value: number): Color + darken(value: number): Color + saturate(value: number): Color + desaturate(value: number): Color + greyscale(): Color + whiten(value: number): Color + blacken(value: number): Color + clearer(value: number): Color + opaquer(value: number): Color + rotate(value: number): Color + mix(color: Color, value?: number): Color + level(color: Color): string + clone(): Color + } +} + +declare const Color: Color.Color; +export = Color; +export as namespace Color; diff --git a/color/tsconfig.json b/color/tsconfig.json new file mode 100644 index 00000000000000..860f35d441204b --- /dev/null +++ b/color/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-tests.ts" + ] +} \ No newline at end of file diff --git a/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts b/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts new file mode 100644 index 00000000000000..6e4317ac9daec5 --- /dev/null +++ b/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts @@ -0,0 +1,119 @@ +var log = (msg : string) => {}; +var devices: BLECentralPlugin.PeripheralData[] = []; +var demoDevice :BLECentralPlugin.PeripheralData = { + "name": "Battery Demo", + "id": "20:FF:D0:FF:D1:C0", + "advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121], + "rssi": -55 +}; + +devices.push(demoDevice); +var demoExtendedData : BLECentralPlugin.PeripheralDataExtended = { + "name": "Battery Demo", + "id": "20:FF:D0:FF:D1:C0", + "advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121], + "rssi": -55, + "services": [ + "1800", + "1801", + "180f" + ], + "characteristics": [ + { + "service": "1800", + "characteristic": "2a00", + "properties": [ + "Read" + ] + }, + { + "service": "1800", + "characteristic": "2a01", + "properties": [ + "Read" + ] + }, + { + "service": "1801", + "characteristic": "2a05", + "properties": [ + "Read" + ] + }, + { + "service": "180f", + "characteristic": "2a19", + "properties": [ + "Read" + ], + "descriptors": [ + { + "uuid": "2901" + }, + { + "uuid": "2904" + } + ] + } + ] +}; + + +//get updates about the bluethooth states +ble.startStateNotifications((state) => log(`BLE state ${state}`)); + +ble.isEnabled(()=> log(`bluetooth is enabled`), ()=>log(`bluetooth is not enabled`)); + +//here we try to enable bluetooth +ble.enable(() => log(`yes it worked, or it was already enabled `), () => log(`nope it didn't work, the user pressed cancel, or we are in iOS`)); + +ble.showBluetoothSettings(() => log(`yes it worked`), () => log(`nope it didn't work`)) + +//stop getting updates about the bluethooth states +ble.stopStateNotifications() + +//scan 5 seconds +ble.scan([], 5000, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ); + +//scan continously +ble.startScan([], (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ) + +////scan continously +ble.startScanWithOptions([], {reportDuplicates:false }, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ) + +//stop scanning +ble.stopScan(()=> log('all good'), ()=> log('couldn\'t stop scanning')); + +//are we conenected to that device? +ble.isConnected(demoDevice.id, () => log(`already connected to this device`), ()=> log(`not yet connected to that device`)); + +//connect to a specific device +var extendedData : BLECentralPlugin.PeripheralDataExtended; +ble.connect(demoDevice.id, (data)=> extendedData = data, () => log(`couldn't connect to the device`) ); + +//read some data from a characteristic +var charsOfOneOfItsServices = demoExtendedData.characteristics.filter((value) => value.service == demoExtendedData.services[0]); +ble.read(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data) => log(`we've received some data`), ()=> log(`couldn't read any data`)); + +//read the rssi +ble.readRSSI(demoDevice.id, (rssi)=>log(`Device ${demoDevice.name} has an RSSI of ${rssi}`)); + +var notificationsReceived : number = 0; +//get notified of changes for that characteristic +ble.startNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data)=> notificationsReceived++, ()=> log(`darn`)); + +//write some data +ble.write(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`)); +//write some data without getting notified +ble.writeWithoutResponse(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`)); + +//stop getting notified of changes. +ble.stopNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic); + +//notificationsReceived == 1 + +//just disconnect +ble.disconnect(demoDevice.id); + + + diff --git a/cordova-plugin-ble-central/index.d.ts b/cordova-plugin-ble-central/index.d.ts new file mode 100644 index 00000000000000..ccf239683337b2 --- /dev/null +++ b/cordova-plugin-ble-central/index.d.ts @@ -0,0 +1,108 @@ +// Type definitions for cordova-plugin-ble-central 1.1.2 +// Project: https://github.com/don/cordova-plugin-ble-central +// Definitions by: Gidon Junge +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare namespace BLECentralPlugin { + + interface PeripheralCharacteristic { + service: string; + characteristic: string; + properties: string[]; + descriptors?: any[]; + } + + interface PeripheralData { + name: string; + id: string; + rssi: number + advertising: ArrayBuffer|any; + } + + + interface PeripheralDataExtended extends PeripheralData{ + services: string[]; + characteristics: PeripheralCharacteristic[] + } + + + + + interface StartScanOptions { + reportDuplicates?: boolean; + } + + export interface BLECentralPluginStatic { + scan(services: string[], seconds: number, success : (data: PeripheralData) => any): void; + scan(services: string[], seconds: number, success : (data: PeripheralData) => any, failure : () => any): void; + + startScan(services: string[], success: (data: PeripheralData) => any): void; + startScan(services: string[], success: (data: PeripheralData) => any, failure: () => any): void; + + startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any): void; + startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any, failure: () => any): void; + + stopScan(): void; + stopScan(success: () => any): void; + stopScan(success: () => any, failure: () => any): void; + + connect(device_id:string, success: (data: PeripheralDataExtended) => any, failure: () => any): void; + + disconnect(device_id:string): void; + disconnect(device_id:string, success: () => any): void; + disconnect(device_id:string, success: () => any, failure: () => any): void; + + read(device_id: string, service_uuid:string, characteristic_uuid:string): void; + read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void; + read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void; + + write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void; + write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void; + write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void; + + /* Writes data to a characteristic without a response from the peripheral. You are not notified if the write fails in the BLE stack. + The success callback is be called when the characteristic is written.*/ + writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void; + writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void; + writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void; + + /* Register to be notified when the value of a characteristic changes. */ + startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void; + startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void; + + stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string): void; + stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any): void; + stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any, failure: () => any): void; + + /* Reports if bluetooth is enabled. */ + isEnabled(success: () => any , failure: () => any): void; + + /* Calls the success callback when the peripheral is connected and the failure callback when not connected. */ + isConnected(device_id: string, success: () => any): void; + isConnected(device_id: string, success: () => any, failure: () => any): void; + + startStateNotifications(success: (state: string) => any): void; + startStateNotifications(success: (state: string) => any, failure: () => any): void; + + stopStateNotifications(): void; + stopStateNotifications(success: () => any): void; + stopStateNotifications(success: () => any, failure: () => any): void; + + /* Opens the Bluetooth settings for the operating systems. + [iOS] showBluetoothSettings is not supported on iOS. */ + showBluetoothSettings(): void; + showBluetoothSettings(success: () => any): void; + showBluetoothSettings(success: () => any, failure: () => any): void; + + /* Enable Bluetooth on the device. + [iOS] enable is not supported on iOS. */ + enable(success: () => any, failure: () => any): void; + + + readRSSI(device_id:string, success: (rssi: number) => any): void; + readRSSI(device_id:string, success: (rssi: number) => any, failure: () => any): void; + } +} + +declare var ble: BLECentralPlugin.BLECentralPluginStatic; \ No newline at end of file diff --git a/cordova-plugin-ble-central/tsconfig.json b/cordova-plugin-ble-central/tsconfig.json new file mode 100644 index 00000000000000..cfff519c0b694f --- /dev/null +++ b/cordova-plugin-ble-central/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova-plugin-ble-central-tests.ts" + ] +} \ No newline at end of file diff --git a/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts b/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts new file mode 100644 index 00000000000000..fec3c119d2d87d --- /dev/null +++ b/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts @@ -0,0 +1,532 @@ +/// + +cordova.plugins.diagnostic.isLocationAvailable(function(available){ + console.log("Location is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isWifiAvailable(function(available){ + console.log("WiFi is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isCameraAvailable(function(available){ + console.log("Camera is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isBluetoothAvailable(function(available){ + console.log("Bluetooth is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.switchToLocationSettings(); +cordova.plugins.diagnostic.switchToMobileDataSettings(); +cordova.plugins.diagnostic.switchToBluetoothSettings(); +cordova.plugins.diagnostic.switchToWifiSettings(); + +cordova.plugins.diagnostic.isWifiEnabled(function(enabled){ + console.log("WiFi is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.setWifiState(function(){ + console.log("Wifi was enabled"); + }, function(error){ + console.error("The following error occurred: "+error); + }, true +); + +cordova.plugins.diagnostic.setBluetoothState(function(){ + console.log("Bluetooth was enabled"); + }, function(error){ + console.error("The following error occurred: "+error); + }, true +); + +cordova.plugins.diagnostic.isLocationEnabled(function(enabled){ + console.log("Location setting is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isLocationAuthorized(function(enabled){ + console.log("Location authorization is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getLocationAuthorizationStatus(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission not requested"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted always"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE: + console.log("Permission granted only when in use"); + break; + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestLocationAuthorization(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission not requested"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted always"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE: + console.log("Permission granted only when in use"); + break; + } +}, function(error){ + console.error(error); +}, cordova.plugins.diagnostic.locationAuthorizationMode.ALWAYS); + +cordova.plugins.diagnostic.isCameraPresent(function(present){ + console.log("Camera is " + (present ? "present" : "absent")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isCameraAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to the camera"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getCameraAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Camera use is authorized"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestCameraAuthorization(function(status){ + console.log("Authorization request for camera use was " + (status == cordova.plugins.diagnostic.permissionStatus.GRANTED ? "granted" : "denied")); +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isMicrophoneAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to the microphone"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getMicrophoneAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Microphone use is authorized"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestMicrophoneAuthorization(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Microphone use is authorized"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isContactsAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to contacts"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getContactsAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Contacts use is authorized"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.requestContactsAuthorization(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Contacts use is authorized"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isCalendarAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to calendar"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getCalendarAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Calendar use is authorized"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestCalendarAuthorization(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Calendar use is authorized"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.switchToSettings(function(){ + console.log("Successfully switched to Settings app"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getBluetoothState(function(state){ + if(state === cordova.plugins.diagnostic.bluetoothState.POWERED_ON){ + console.log("Bluetooth is able to connect"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.registerBluetoothStateChangeHandler(function(state){ + if(state === cordova.plugins.diagnostic.bluetoothState.POWERED_ON){ + console.log("Bluetooth is able to connect"); + } +}); + +cordova.plugins.diagnostic.registerLocationStateChangeHandler(function(state){ + if((device.platform === "Android" && state !== cordova.plugins.diagnostic.locationMode.LOCATION_OFF) + || (device.platform === "iOS") && ( state === cordova.plugins.diagnostic.permissionStatus.GRANTED + || state === cordova.plugins.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE + )){ + console.log("Location is available"); + } +}); + +cordova.plugins.diagnostic.getLocationMode(function(locationMode){ + switch(locationMode){ + case cordova.plugins.diagnostic.locationMode.HIGH_ACCURACY: + console.log("High accuracy"); + break; + case cordova.plugins.diagnostic.locationMode.BATTERY_SAVING: + console.log("Battery saving"); + break; + case cordova.plugins.diagnostic.locationMode.DEVICE_ONLY: + console.log("Device only"); + break; + case cordova.plugins.diagnostic.locationMode.LOCATION_OFF: + console.log("Location off"); + break; + } +},function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isGpsLocationAvailable(function(available){ + console.log("GPS location is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isGpsLocationEnabled(function(enabled){ + console.log("GPS location is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isNetworkLocationAvailable(function(available){ + console.log("Network location is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isNetworkLocationEnabled(function(enabled){ + console.log("Network location is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getLocationMode(function(locationMode){ + switch(locationMode){ + case cordova.plugins.diagnostic.locationMode.HIGH_ACCURACY: + console.log("High accuracy"); + break; + case cordova.plugins.diagnostic.locationMode.BATTERY_SAVING: + console.log("Battery saving"); + break; + case cordova.plugins.diagnostic.locationMode.DEVICE_ONLY: + console.log("Device only"); + break; + case cordova.plugins.diagnostic.locationMode.LOCATION_OFF: + console.log("Location off"); + break; + } +},function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getPermissionAuthorizationStatus(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use the camera"); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use the camera has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use the camera - ask again?"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use the camera - guess we won't be using it then!"); + break; + } +}, function(error){ + console.error("The following error occurred: "+error); +}, cordova.plugins.diagnostic.permission.CAMERA); + +cordova.plugins.diagnostic.getPermissionsAuthorizationStatus(function(statuses){ + for (var permission in statuses){ + switch(statuses[permission]){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use "+permission); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use "+permission+" has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use "+permission+" - ask again?"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use "+permission+" - guess we won't be using it then!"); + break; + } + } +}, function(error){ + console.error("The following error occurred: "+error); +},[ + cordova.plugins.diagnostic.permission.ACCESS_FINE_LOCATION, + cordova.plugins.diagnostic.permission.ACCESS_COARSE_LOCATION +]); + +cordova.plugins.diagnostic.requestRuntimePermission(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use the camera"); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use the camera has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use the camera - ask again?"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use the camera - guess we won't be using it then!"); + break; + } +}, function(error){ + console.error("The following error occurred: "+error); +}, cordova.plugins.diagnostic.permission.CAMERA); + +cordova.plugins.diagnostic.requestRuntimePermissions(function(statuses){ + for (var permission in statuses){ + switch(statuses[permission]){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use "+permission); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use "+permission+" has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use "+permission+" - ask again?"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use "+permission+" - guess we won't be using it then!"); + break; + } + } +}, function(error){ + console.error("The following error occurred: "+error); +},[ + cordova.plugins.diagnostic.permission.ACCESS_FINE_LOCATION, + cordova.plugins.diagnostic.permission.ACCESS_COARSE_LOCATION +]); + +if(!cordova.plugins.diagnostic.isRequestingPermission()){ + console.log("Request some permissions"); +}else{ + cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(function(statuses){ + cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(null); // de-register handler after single call + console.log("Request some permissions"); + }); +} + +function onPermissionRequestComplete(statuses:any){ + console.info("Permission request complete"); + for (var permission in statuses){ + switch(statuses[permission]){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use "+permission); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use "+permission+" has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use "+permission); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use "+permission); + break; + } + } + cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(null); // de-register handler +} +cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(onPermissionRequestComplete) + +cordova.plugins.diagnostic.isBluetoothEnabled(function(enabled){ + console.log("Bluetooth is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.hasBluetoothSupport(function(supported){ + console.log("Bluetooth is " + (supported ? "supported" : "unsupported")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.hasBluetoothLESupport(function(supported){ + console.log("Bluetooth LE is " + (supported ? "supported" : "unsupported")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.hasBluetoothLEPeripheralSupport(function(supported){ + console.log("Bluetooth LE Peripheral Mode is " + (supported ? "supported" : "unsupported")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isCameraRollAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to the camera roll"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getCameraRollAuthorizationStatus(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission not requested"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted"); + break; + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestCameraRollAuthorization(function(status){ + console.log("Authorization request for camera roll was " + (status == cordova.plugins.diagnostic.permissionStatus.GRANTED ? "granted" : "denied")); +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isRemoteNotificationsEnabled(function(enabled){ + console.log("Remote notifications are " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isRegisteredForRemoteNotifications(function(registered){ + console.log("Device " + (registered ? "is" : "isn't") + " registered for remote notifications"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getRemoteNotificationTypes(function(types){ + for(var type in types){ + console.log(type + " is " + (types[type] ? "enabled" : "disabled")); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isRemindersAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to reminders"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getRemindersAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Reminders authorization allowed"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestRemindersAuthorization(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Reminders authorization allowed"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isBackgroundRefreshAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "not authorized") + " to perform background refresh"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getBackgroundRefreshStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Background refresh is allowed"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestBluetoothAuthorization(function(){ + console.log("Bluetooth authorization requested"); +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isMotionAvailable(function(available){ + console.log("Motion tracking is " + (available ? "available" : "not available") + " on this device"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isMotionRequestOutcomeAvailable(function(available){ + console.log("Motion tracking request outcome is " + (available ? "available" : "not available") + " on this device"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestAndCheckMotionAuthorization(function(status){ + console.log("Motion authorization is " +status); +}, function(error){ + console.error(error); +}); \ No newline at end of file diff --git a/cordova.plugins.diagnostic/index.d.ts b/cordova.plugins.diagnostic/index.d.ts new file mode 100644 index 00000000000000..381b61562e7551 --- /dev/null +++ b/cordova.plugins.diagnostic/index.d.ts @@ -0,0 +1,738 @@ +// Type definitions for cordova.plugins.diagnostic v3.3.0 +// Project: https://github.com/dpa99c/cordova-diagnostic-plugin +// Definitions by: Dave Alden +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Checks whether device hardware features are enabled or available to the app, e.g. camera, GPS, wifi + */ +interface Diagnostic { + + /** + * ANDROID ONLY + * "Dangerous" permissions that need to be requested at run-time (Android 6.0/API 23 and above) + * See http://developer.android.com/guide/topics/security/permissions.html#perm-groups + * @type {Object} + */ + permission?: any; + + /** + * ANDROID ONLY + * Permission groups indicate which associated permissions will also be requested if a given permission is requested. + * See http://developer.android.com/guide/topics/security/permissions.html#perm-groups + * @type {Object} + */ + permissionGroups?: any; + + /** + * ANDROID and iOS ONLY + * Constants for requesting and reporting the various permission states. + * @type {Object} + */ + permissionStatus?: any; + + /** + * iOS ONLY + * Location authorization mode + * @type {Object} + */ + locationAuthorizationMode?: any; + + + /** + * ANDROID ONLY + * Constants for the various location modes on Android. + * @type {Object} + */ + locationMode?: any; + + /** + * ANDROID and iOS ONLY + * Constants for the various Bluetooth hardware states. + * @type {Object} + */ + bluetoothState?: any; + + + /** + * Checks if app is able to access device location. + * @param successCallback + * @param errorCallback + */ + isLocationAvailable: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * Checks if Wifi is available. + * On iOS this returns true if the device is connected to a network by WiFi. + * On Android and Windows 10 Mobile this returns true if the WiFi setting is set to enabled, and is the same as isWifiEnabled() + * @param successCallback + * @param errorCallback + */ + isWifiAvailable: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * Checks if camera is available. + * On Android & iOS this returns true if the device has a camera AND the application is authorized to use it. + * On Windows 10 Mobile this returns true if the device has a rear-facing camera. + * @param successCallback + * @param errorCallback + */ + isCameraAvailable: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * Checks if Bluetooth is available to the app. + * Returns true if the device has Bluetooth capabilities AND if Bluetooth setting is switched on (same on Android, iOS and Windows 10 Mobile) + * @param successCallback + * @param errorCallback + */ + isBluetoothAvailable: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and WINDOWS ONLY + * Displays the device location settings to allow user to enable location services/change location mode. + */ + switchToLocationSettings?: () => void; + + /** + * ANDROID and WINDOWS ONLY + * Displays mobile settings to allow user to enable mobile data. + */ + switchToMobileDataSettings?: () => void; + + /** + * ANDROID and WINDOWS ONLY + * Displays Bluetooth settings to allow user to enable Bluetooth. + */ + switchToBluetoothSettings?: () => void; + + /** + * ANDROID and WINDOWS ONLY + * Displays WiFi settings to allow user to enable WiFi. + */ + switchToWifiSettings?: () => void; + + /** + * ANDROID and WINDOWS ONLY + * Returns true if the WiFi setting is set to enabled, and is the same as isWifiAvailable() + * @param successCallback + * @param errorCallback + */ + isWifiEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and WINDOWS ONLY + * Enables/disables WiFi on the device. + * @param successCallback + * @param errorCallback + * @param state + */ + setWifiState?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void, + state: boolean + ) => void; + + /** + * ANDROID and WINDOWS ONLY + * Enables/disables Bluetooth on the device. + * @param successCallback + * @param errorCallback + * @param state + */ + setBluetoothState?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void, + state: boolean + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns true if the device setting for location is on. + * On Android this returns true if Location Mode is switched on. + * On iOS this returns true if Location Services is switched on. + * @param successCallback + * @param errorCallback + */ + isLocationEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use location. + * @param successCallback + * @param errorCallback + */ + isLocationAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the location authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getLocationAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests location authorization for the application. + * @param successCallback + * @param errorCallback + * @param mode - (iOS-only / optional) location authorization mode specified as a locationAuthorizationMode constant. If not specified, defaults to WHEN_IN_USE. + */ + requestLocationAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void, + mode?: string + ) => void; + + + /** + * ANDROID and iOS ONLY + * Checks if camera hardware is present on device. + * @param successCallback + * @param errorCallback + */ + isCameraPresent?: ( + successCallback: (present: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use the camera. + * @param successCallback + * @param errorCallback + */ + isCameraAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the camera authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getCameraAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests camera authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestCameraAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use the microphone. + * @param successCallback + * @param errorCallback + */ + isMicrophoneAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the microphone authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getMicrophoneAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests microphone authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestMicrophoneAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use contacts (address book). + * @param successCallback + * @param errorCallback + */ + isContactsAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the contacts authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getContactsAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests contacts authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestContactsAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use the calendar. + * @param successCallback + * @param errorCallback + */ + isCalendarAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the calendar authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getCalendarAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests calendar authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestCalendarAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Opens settings page for this app. + * On Android, this opens the "App Info" page in the Settings app. + * On iOS, this opens the app settings page in the Settings app. This works only on iOS 8+ - iOS 7 and below will invoke the errorCallback. + */ + switchToSettings?: ( + successCallback: () => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the state of Bluetooth on the device. + * @param successCallback + * @param errorCallback + */ + getBluetoothState?: ( + successCallback: (state: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Registers a function to be called when a change in Bluetooth state occurs. Pass in a falsey value to de-register the currently registered function. + * @param successCallback + */ + registerBluetoothStateChangeHandler?: ( + successCallback: (state: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Registers a function to be called when a change in Location state occurs. Pass in a falsey value to de-register the currently registered function. + * On Android, this occurs when the Location Mode is changed. + * On iOS, this occurs when location authorization status is changed. This can be triggered either by the user's response to a location permission authorization dialog, by the user turning on/off Location Services, or by the user changing the Location authorization state specifically for your app. + * @param successCallback + */ + registerLocationStateChangeHandler?: ( + successCallback: (state: string) => void + ) => void; + + + /** + * ANDROID ONLY + * Checks if high-accuracy locations are available to the app from GPS hardware. + * Returns true if Location mode is enabled and is set to "Device only" or "High accuracy" AND if the app is authorised to use location. + * @param successCallback + * @param errorCallback + */ + isGpsLocationAvailable?: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device location setting is set to return high-accuracy locations from GPS hardware. + * Returns true if Location mode is enabled and is set to either Device only or High accuracy + * @param successCallback + * @param errorCallback + */ + isGpsLocationEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if low-accuracy locations are available to the app from network triangulation/WiFi access points. + * Returns true if Location mode is enabled and is set to "Battery saving" or "High accuracy" AND if the app is authorised to use location. + * @param successCallback + * @param errorCallback + */ + isNetworkLocationAvailable?: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device location setting is set to return high-accuracy locations from GPS hardware. + * Returns true if Location mode is enabled and is set to either Battery saving or High accuracy + * @param successCallback + * @param errorCallback + */ + isNetworkLocationEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Returns the current location mode setting for the device. + * @param successCallback + * @param errorCallback + */ + getLocationMode?: ( + successCallback: (mode: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Returns the current authorisation status for a given permission. + * @param successCallback + * @param errorCallback + * @param permission + */ + getPermissionAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void, + permission: string + ) => void; + + /** + * ANDROID ONLY + * Returns the current authorisation status for multiple permissions. + * @param successCallback + * @param errorCallback + * @param permissions + */ + getPermissionsAuthorizationStatus?: ( + successCallback: (status: string[]) => void, + errorCallback: (error: string) => void, + permissions: string[] + ) => void; + + /** + * ANDROID ONLY + * Requests app to be granted authorisation for a runtime permission. + * @param successCallback + * @param errorCallback + * @param permission + */ + requestRuntimePermission?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void, + permission: string + ) => void; + + /** + * ANDROID ONLY + * Requests app to be granted authorisation for multiple runtime permissions. + * @param successCallback + * @param errorCallback + * @param permissions + */ + requestRuntimePermissions?: ( + successCallback: (status: string[]) => void, + errorCallback: (error: string) => void, + permissions: string[] + ) => void; + + /** + * ANDROID ONLY + * Indicates if the plugin is currently requesting a runtime permission via the native API. + */ + isRequestingPermission?: () => boolean; + + /** + * ANDROID ONLY + * Registers a function to be called when a runtime permission request has completed. Pass in a falsey value to de-register the currently registered function. + * @param successCallback + */ + registerPermissionRequestCompleteHandler?: ( + successCallback: (statuses: any) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device setting for Bluetooth is switched on. + * @param successCallback + * @param errorCallback + */ + isBluetoothEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device has Bluetooth capabilities. + * @param successCallback + * @param errorCallback + */ + hasBluetoothSupport?: ( + successCallback: (supported: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device has Bluetooth Low Energy (LE) capabilities. + * @param successCallback + * @param errorCallback + */ + hasBluetoothLESupport?: ( + successCallback: (supported: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device supports Bluetooth Low Energy (LE) Peripheral mode. + * @param successCallback + * @param errorCallback + */ + hasBluetoothLEPeripheralSupport?: ( + successCallback: (supported: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if the application is authorized to use the Camera Roll in Photos app. + * @param successCallback + * @param errorCallback + */ + isCameraRollAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Returns the authorization status for the application to use the Camera Roll in Photos app. + * @param successCallback + * @param errorCallback + */ + getCameraRollAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Requests camera roll authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestCameraRollAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if remote (push) notifications are enabled. + * @param successCallback + * @param errorCallback + */ + isRemoteNotificationsEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Indicates if the app is registered for remote (push) notifications on the device. + * @param successCallback + * @param errorCallback + */ + isRegisteredForRemoteNotifications?: ( + successCallback: (registered: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Indicates the current setting of notification types for the app in the Settings app. + * @param successCallback + * @param errorCallback + */ + getRemoteNotificationTypes?: ( + successCallback: (types: any) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if the application is authorized to use reminders. + * @param successCallback + * @param errorCallback + */ + isRemindersAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Returns the reminders authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getRemindersAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Requests reminders authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestRemindersAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if the application is authorized for background refresh. + * @param successCallback + * @param errorCallback + */ + isBackgroundRefreshAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Returns the background refresh authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getBackgroundRefreshStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Requests Bluetooth authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestBluetoothAuthorization?: ( + successCallback: () => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if motion tracking is available on the current device. + * @param successCallback + * @param errorCallback + */ + isMotionAvailable?: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if it's possible to determine the outcome of a motion authorization request on the current device. + * @param successCallback + * @param errorCallback + */ + isMotionRequestOutcomeAvailable?: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Requests and checks motion authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestAndCheckMotionAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; +} + +interface CordovaPlugins { + diagnostic: Diagnostic +} \ No newline at end of file diff --git a/cordova.plugins.diagnostic/tsconfig.json b/cordova.plugins.diagnostic/tsconfig.json new file mode 100644 index 00000000000000..43c76ef639cbcc --- /dev/null +++ b/cordova.plugins.diagnostic/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova.plugins.diagnostic-tests.ts" + ] +} \ No newline at end of file diff --git a/credit-card-type/credit-card-type-tests.ts b/credit-card-type/credit-card-type-tests.ts new file mode 100644 index 00000000000000..de2c6fade4aec7 --- /dev/null +++ b/credit-card-type/credit-card-type-tests.ts @@ -0,0 +1,5 @@ +import * as creditCardType from "credit-card-type" + +var cardTypes: Array = creditCardType("") +var cardInfo: creditCardType.CreditCardTypeInfo = creditCardType.getTypeInfo("") +var types: { [type: string]: string } = creditCardType.types diff --git a/credit-card-type/index.d.ts b/credit-card-type/index.d.ts new file mode 100644 index 00000000000000..59886b5e60b548 --- /dev/null +++ b/credit-card-type/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for Credit Card Type v5.0.0 +// Project: https://github.com/braintree/credit-card-type +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace creditCardType { + + type CardBrand = "american-express" | "diners-club" | "discover" | "jcb" | "maestro" | "master-card" | "unionpay" | "visa" + + interface CreditCardTypeInfo { + niceType?: string + type?: CardBrand + pattern?: RegExp + gaps?: Array + lengths?: Array + code?: { + name?: string + size?: number + } + } + + interface CreditCardType { + (number: string): Array + getTypeInfo (type: string): CreditCardTypeInfo + types: { [type: string]: string } + } +} + +declare const creditCardType: creditCardType.CreditCardType +export = creditCardType diff --git a/credit-card-type/tsconfig.json b/credit-card-type/tsconfig.json new file mode 100644 index 00000000000000..7b38d340d46a79 --- /dev/null +++ b/credit-card-type/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "credit-card-type-tests.ts" + ] +} \ No newline at end of file diff --git a/electron/electron-prebuilt.d.ts b/electron/electron-prebuilt.d.ts deleted file mode 100644 index 585c9e4668bc6c..00000000000000 --- a/electron/electron-prebuilt.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for electron 1.3.3 -// Project: https://github.com/electron-userland/electron-prebuilt -// Definitions by: rhysd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -// this file will be removed. diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index 490b708011ed8c..77bd63e3e6175b 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -201,7 +201,7 @@ namespace ShallowWrapperTest { } function test_state() { - shallowWrapper.state(); + const state: MyComponentState = shallowWrapper.state(); shallowWrapper.state('key'); const tmp: String = shallowWrapper.state('key'); } diff --git a/enzyme/index.d.ts b/enzyme/index.d.ts index ddbee13c28a6c2..d531d12f0364b1 100644 --- a/enzyme/index.d.ts +++ b/enzyme/index.d.ts @@ -202,8 +202,9 @@ interface CommonWrapper { * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. * @param [key] */ - state(key?: string): any; - state(key?: string): T; + state(): S; + state(key: string): any; + state(key: string): T; /** * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. diff --git a/es6-error/es6-error-tests.ts b/es6-error/es6-error-tests.ts new file mode 100644 index 00000000000000..26ed7b6677e2ef --- /dev/null +++ b/es6-error/es6-error-tests.ts @@ -0,0 +1,9 @@ +import * as ExtendableError from "es6-error" + +class TestError extends ExtendableError { + constructor (message: string = "TestError") { + super(message) + } +} + +throw new TestError("Test Message") diff --git a/es6-error/index.d.ts b/es6-error/index.d.ts new file mode 100644 index 00000000000000..c1d3d5ce21a8d3 --- /dev/null +++ b/es6-error/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for es6-error v4.0.0 +// Project: https://github.com/bjyoungblood/es6-error +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Error; diff --git a/es6-error/tsconfig.json b/es6-error/tsconfig.json new file mode 100644 index 00000000000000..a36756343e941f --- /dev/null +++ b/es6-error/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "es6-error-tests.ts" + ] +} \ No newline at end of file diff --git a/eventemitter3/eventemitter3-tests.ts b/eventemitter3/eventemitter3-tests.ts index c0a532fc8760aa..9c8e379ec94ee7 100644 --- a/eventemitter3/eventemitter3-tests.ts +++ b/eventemitter3/eventemitter3-tests.ts @@ -1,585 +1,116 @@ -/// -/// 'use strict'; -import EventEmitter = require('eventemitter3'); -import util = require('util'); -import * as EventEmitter3ImportedAsES6Module from 'eventemitter3'; +import * as EventEmitter from 'eventemitter3'; -declare namespace Assume { - interface Class { - new(...args: any[]): T; - } - - interface Assume { - equals(compare: T): Assume; - equal(compare: T): Assume; - eqls(compare: T): Assume; - is: Assume; - deep: Assume; - to: Assume; - either(arr: T[]): Assume; - instanceOf(clazz: Class): Assume; - a(typeofString: string): Assume; - } - - export function assume(input: T): Assume; -} - -let assume = Assume.assume; - -class EventEmitterTest { - v: any; +const eventName = 'test'; +const eventSymbol: symbol = Symbol('test'); +const fn = () => console.log(1); +// Extending EventEmitter +class TestEmitter extends EventEmitter { constructor() { - this.v = new EventEmitter(); - this.v = new EventEmitter3ImportedAsES6Module(); - - // Some methods are missing or incompatible with current implementation (v4.2.x) of NodeJS.EventEmitter - // (e.g. getMaxListenters or listeners) - // var n: NodeJS.EventEmitter = this.v; - } - - listeners() { - var v1: Function[] = this.v.listeners('click'); - } - - emit() { - var v1: boolean = this.v.emit('click'); - var v2: boolean = this.v.emit('click', 1); - var v3: boolean = this.v.emit('click', 1, '1'); - var v4: boolean = this.v.emit('click', 1, '1', true); - var v5: boolean = this.v.emit('click', 1, '1', true, new Date()); - } - - on() { - var fn = () => console.log(1); - var v1 = this.v.on('click', fn); - var v2 = this.v.on('click', fn, this); - } - - once() { - var fn = () => console.log(1); - var v1 = this.v.once('click', fn); - var v2 = this.v.once('click', fn, this); - } - - removeListener() { - var fn = () => console.log(1); - var v1 = this.v.removeListener('click', fn); - var v2 = this.v.removeListener('click', fn, true); - } - - removeAllListeners() { - var v1 = this.v.removeAllListeners('click'); + super(); } - off() { - var fn = () => console.log(1); - var v1 = this.v.off('click', fn); - var v2 = this.v.off('click', fn, true); - } - - addListener() { - var fn = () => console.log(1); - var v1 = this.v.addListener('click', fn); - var v2 = this.v.addListener('click', fn, this); - } - - setMaxListeners() { - var v1 = this.v.setMaxListeners(); + test() { + return this; } } +const ee: TestEmitter = new TestEmitter(); -describe('EventEmitter', function tests() { - 'use strict'; - - it('exposes a `prefixed` property', function () { - assume(EventEmitter.prefixed).is.either([false, '~']); - }); - - it('inherits when used with require(util).inherits', function () { - class Beast extends EventEmitter { - /* rawr, i'm a beast */ - } +// EventEmitter.prefixed +// should be boolean or string static property +const prefix = EventEmitter.prefixed; +if (typeof prefix === 'boolean') { + console.log(prefix.valueOf()); +} else { + console.log(prefix.length); +} - class BeastES6 extends EventEmitter3ImportedAsES6Module { - /* rawr, i'm a beast */ +// EventEmitter.eventNames() +// should return array of strings or symbols +ee.eventNames().every((event) => { + if (typeof event === 'symbol') { + return false; + } else { + return event.length > 0; } +}); - util.inherits(Beast, EventEmitter); - - var moop = new Beast() - , meap = new Beast(); - - assume(moop).is.instanceOf(Beast); - assume(moop).is.instanceOf(EventEmitter); - - moop.listeners(); - meap.listeners(); - - moop.on('data', function () { - throw new Error('I should not emit'); - }); - - meap.emit('data', 'rawr'); - meap.removeListener('foo'); - meap.removeAllListeners(); - }); - - describe('EventEmitter#emit', function () { - it('should return false when there are not events to emit', function () { - var e = new EventEmitter(); - - assume(e.emit('foo')).equals(false); - assume(e.emit('bar')).equals(false); - }); - - it('emits with context', function (done) { - var context = { bar: 'baz' } - , e = new EventEmitter(); - - e.on('foo', function (bar: string) { - assume(bar).equals('bar'); - assume(this).equals(context); - - done(); - }, context).emit('foo', 'bar'); - }); - - it('emits with context, multiple arguments (force apply)', function (done) { - var context = { bar: 'baz' } - , e = new EventEmitter(); - - e.on('foo', function (bar: string) { - assume(bar).equals('bar'); - assume(this).equals(context); - - done(); - }, context).emit('foo', 'bar', 1,2,3,4,5,6,7,8,9,0); - }); - - it('can emit the function with multiple arguments', function () { - var e = new EventEmitter(); - - for(var i = 0; i < 100; i++) { - (function (j: number) { - for (var i = 0, args: number[] = []; i < j; i++) { - args.push(j); - } - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.emit.apply(e, (['args'] as any[]).concat(args)); - })(i); - } - }); - - it('can emit the function with multiple arguments, multiple listeners', function () { - var e = new EventEmitter(); - - for(var i = 0; i < 100; i++) { - (function (j: number) { - for (var i = 0, args: number[] = []; i < j; i++) { - args.push(j); - } - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.emit.apply(e, (['args'] as any[]).concat(args)); - })(i); - } - }); - - it('emits with context, multiple listeners (force loop)', function () { - var e = new EventEmitter(); - - e.on('foo', function (bar: string) { - assume(this).eqls({ foo: 'bar' }); - assume(bar).equals('bar'); - }, { foo: 'bar' }); - - e.on('foo', function (bar: string) { - assume(this).eqls({ bar: 'baz' }); - assume(bar).equals('bar'); - }, { bar: 'baz' }); - - e.emit('foo', 'bar'); - }); - - it('emits with different contexts', function () { - var e = new EventEmitter() - , pattern = ''; - - function writer() { - pattern += this; - } - - e.on('write', writer, 'foo'); - e.on('write', writer, 'baz'); - e.once('write', writer, 'bar'); - e.once('write', writer, 'banana'); - - e.emit('write'); - assume(pattern).equals('foobazbarbanana'); - }); - - it('should return true when there are events to emit', function (done) { - var e = new EventEmitter(); - - e.on('foo', function () { - process.nextTick(done); - }); - - assume(e.emit('foo')).equals(true); - assume(e.emit('foob')).equals(false); - }); - - it('receives the emitted events', function (done) { - var e = new EventEmitter(); - - e.on('data', function (a: string, b: any, c: Date, d: void, undef: void) { - assume(a).equals('foo'); - assume(b).equals(e); - assume(c).is.instanceOf(Date); - assume(undef).equals(undefined); - assume(arguments.length).equals(3); - - done(); - }); - - e.emit('data', 'foo', e, new Date()); - }); - - it('emits to all event listeners', function () { - var e = new EventEmitter() - , pattern: string[] = []; - - e.on('foo', function () { - pattern.push('foo1'); - }); - - e.on('foo', function () { - pattern.push('foo2'); - }); - - e.emit('foo'); - - assume(pattern.join(';')).equals('foo1;foo2'); - }); - - (function each(keys: string[]) { - var key = keys.shift(); - - if (!key) return; - - it('can store event which is a known property: '+ key, function (next) { - var e = new EventEmitter(); - - e.on(key, function (key: string) { - assume(key).equals(key); - next(); - }).emit(key, key); - }); - - each(keys); - })([ - 'hasOwnProperty', - 'constructor', - '__proto__', - 'toString', - 'toValue', - 'unwatch', - 'watch' - ]); - }); - - describe('EventEmitter#listeners', function () { - it('returns an empty array if no listeners are specified', function () { - var e = new EventEmitter(); - - assume(e.listeners('foo')).is.a('array'); - assume(e.listeners('foo').length).equals(0); - }); - - it('returns an array of function', function () { - var e = new EventEmitter(); - - function foo() {} - - e.on('foo', foo); - assume(e.listeners('foo')).is.a('array'); - assume(e.listeners('foo').length).equals(1); - assume(e.listeners('foo')).deep.equals([foo]); - }); - - it('is not vulnerable to modifications', function () { - var e = new EventEmitter(); - - function foo() {} - - e.on('foo', foo); - - assume(e.listeners('foo')).deep.equals([foo]); - - e.listeners('foo').length = 0; - assume(e.listeners('foo')).deep.equals([foo]); - }); - - it('can return a boolean as indication if listeners exist', function () { - var e = new EventEmitter(); - - function foo() {} - - e.once('once', foo); - e.once('multiple', foo); - e.once('multiple', foo); - e.on('on', foo); - e.on('multi', foo); - e.on('multi', foo); - - assume(e.listeners('foo', true)).equals(false); - assume(e.listeners('multiple', true)).equals(true); - assume(e.listeners('on', true)).equals(true); - assume(e.listeners('multi', true)).equals(true); - - e.removeAllListeners(); - - assume(e.listeners('multiple', true)).equals(false); - assume(e.listeners('on', true)).equals(false); - assume(e.listeners('multi', true)).equals(false); - }); - }); - - describe('EventEmitter#once', function () { - it('only emits it once', function () { - var e = new EventEmitter() - , calls = 0; - - e.once('foo', function () { - calls++; - }); - - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - - assume(e.listeners('foo').length).equals(0); - assume(calls).equals(1); - }); - - it('only emits once if emits are nested inside the listener', function () { - var e = new EventEmitter() - , calls = 0; - - e.once('foo', function () { - calls++; - e.emit('foo'); - }); - - e.emit('foo'); - assume(e.listeners('foo').length).equals(0); - assume(calls).equals(1); - }); - - it('only emits once for multiple events', function () { - var e = new EventEmitter() - , multi = 0 - , foo = 0 - , bar = 0; - - e.once('foo', function () { - foo++; - }); - - e.once('foo', function () { - bar++; - }); - - e.on('foo', function () { - multi++; - }); - - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - - assume(e.listeners('foo').length).equals(1); - assume(multi).equals(5); - assume(foo).equals(1); - assume(bar).equals(1); - }); - - it('only emits once with context', function (done) { - var context = { foo: 'bar' } - , e = new EventEmitter(); - - e.once('foo', function (bar: string) { - assume(this).equals(context); - assume(bar).equals('bar'); - - done(); - }, context).emit('foo', 'bar'); - }); - }); - - describe('EventEmitter#removeListener', function () { - it('should only remove the event with the specified function', function () { - var e = new EventEmitter(); - - function bar() {} - e.on('foo', function () {}); - e.on('bar', function () {}); - e.on('bar', bar); - - assume(e.removeListener('foo', bar)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.listeners('bar').length).equals(2); - - assume(e.removeListener('foo')).equals(e); - assume(e.listeners('foo').length).equals(0); - assume(e.listeners('bar').length).equals(2); - - assume(e.removeListener('bar', bar)).equals(e); - assume(e.listeners('bar').length).equals(1); - assume(e.removeListener('bar')).equals(e); - assume(e.listeners('bar').length).equals(0); - }); - - it('should only remove once events when using the once flag', function () { - var e = new EventEmitter(); - - function foo() {} - e.on('foo', foo); - - assume(e.removeListener('foo', function () {}, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo)).equals(e); - assume(e.listeners('foo').length).equals(0); - - e.on('foo', foo); - e.once('foo', foo); - - assume(e.removeListener('foo', function () {}, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(2); - assume(e.removeListener('foo', foo, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(1); - - e.once('foo', foo); - - assume(e.removeListener('foo', foo)).equals(e); - assume(e.listeners('foo').length).equals(0); - }); - - it('should only remove listeners matching the correct context', function () { - var e = new EventEmitter() - , context = { foo: 'bar' }; - - function foo() {} - function bar() {} - e.on('foo', foo, context); - - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', function () {}, context)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo, { baz: 'quux' })).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo, context)).equals(e); - assume(e.listeners('foo').length).equals(0); - - e.on('foo', foo, context); - e.on('foo', bar); - - assume(e.listeners('foo').length).equals(2); - assume(e.removeListener('foo', foo, { baz: 'quux' })).equals(e); - assume(e.listeners('foo').length).equals(2); - assume(e.removeListener('foo', foo, context)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.listeners('foo')[0]).equals(bar); - - e.on('foo', foo, context); - - assume(e.listeners('foo').length).equals(2); - assume(e.removeAllListeners('foo')).equals(e); - assume(e.listeners('foo').length).equals(0); - }); - }); - - describe('EventEmitter#removeAllListeners', function () { - it('removes all events for the specified events', function () { - var e = new EventEmitter(); - - e.on('foo', function () { throw new Error('oops'); }); - e.on('foo', function () { throw new Error('oops'); }); - e.on('bar', function () { throw new Error('oops'); }); - e.on('aaa', function () { throw new Error('oops'); }); - - assume(e.removeAllListeners('foo')).equals(e); - assume(e.listeners('foo').length).equals(0); - assume(e.listeners('bar').length).equals(1); - assume(e.listeners('aaa').length).equals(1); - - assume(e.removeAllListeners('bar')).equals(e); - assume(e.removeAllListeners('aaa')).equals(e); - - assume(e.emit('foo')).equals(false); - assume(e.emit('bar')).equals(false); - assume(e.emit('aaa')).equals(false); - }); - - it('just nukes the fuck out of everything', function () { - var e = new EventEmitter(); - - e.on('foo', function () { throw new Error('oops'); }); - e.on('foo', function () { throw new Error('oops'); }); - e.on('bar', function () { throw new Error('oops'); }); - e.on('aaa', function () { throw new Error('oops'); }); - - assume(e.removeAllListeners()).equals(e); - assume(e.listeners('foo').length).equals(0); - assume(e.listeners('bar').length).equals(0); - assume(e.listeners('aaa').length).equals(0); - - assume(e.emit('foo')).equals(false); - assume(e.emit('bar')).equals(false); - assume(e.emit('aaa')).equals(false); - }); - }); - - describe('#setMaxListeners', function () { - it('is a function', function () { - var e = new EventEmitter(); - - assume(e.setMaxListeners).is.a('function'); - }); - - it('returns self when called', function () { - var e = new EventEmitter(); - - assume(e.setMaxListeners()).to.equal(e); - }); - }); +// EventEmitter.listeners() +// should return array of functions +ee.listeners(eventName).map((listener) => { + return listener.bind(this); +}); +// should accept symbol as event name +ee.listeners(eventSymbol).map((listener) => { + return listener.bind(this); }); +// should return boolean with 'exists' flag +const hasListeners: boolean = ee.listeners(eventName, true); + +// EventEmitter.emit() +// should support any number of arguments +ee.emit(eventName, 1, true, {}, [], 'test', Symbol(), null); +// should accept symbol as event name +ee.emit(eventSymbol); + +// EventEmitter.addListener() and EventEmitter.on() +// should accept function +ee.on(eventName, fn); +ee.addListener(eventName, fn); +// should accept optional context argument +ee.on(eventName, fn, this); +ee.addListener(eventName, fn, this); +// should accept symbol as event name +ee.on(eventSymbol, fn); +ee.addListener(eventSymbol, fn); +// should support fluent interface +ee.on(eventSymbol, fn).test(); +ee.addListener(eventSymbol, fn).test(); + +// EventEmitter.once() +// should accept event name and function +ee.once(eventName, fn); +// should accept optional context argument +ee.once(eventName, fn, this); +ee.once(eventName, fn, {}); +// should accept symbol as event name +ee.once(eventSymbol, fn); +// should support fluent interface +ee.once(eventSymbol, fn).test(); + +// EventEmitter.removeListener() and EventEmitter.off() +// should accept event name +ee.removeListener(eventName); +ee.off(eventName); +// should accept optional function +ee.removeListener(eventName, fn); +ee.off(eventName, fn); +// should accept optional context argument +ee.removeListener(eventName, fn, {}); +ee.off(eventName, fn, {}); +// should accept optional boolean flag for removing listeners added with `EventEmitter.once()` +ee.removeListener(eventName, fn, null, true); +ee.off(eventName, fn, null, true); +// should accept symbol as event name +ee.removeListener(eventSymbol); +ee.off(eventSymbol); +// should support fluent interface +ee.removeListener(eventName).test(); +ee.off(eventName).test(); + +// EventEmitter.removeAllListeners() +// should not require any arguments +ee.removeAllListeners(); +// should accept optional event name +ee.removeAllListeners(eventName); +// should accept symbol as event name +ee.removeAllListeners(eventSymbol); +// should support fluent interface +ee.removeAllListeners(eventName).test(); + +// EventEmitter.setMaxListeners() +// should support fluent interface +ee.setMaxListeners().test(); \ No newline at end of file diff --git a/eventemitter3/eventemitter3-tests.ts.tscparams b/eventemitter3/eventemitter3-tests.ts.tscparams new file mode 100644 index 00000000000000..30c9419a578c48 --- /dev/null +++ b/eventemitter3/eventemitter3-tests.ts.tscparams @@ -0,0 +1 @@ +-m commonjs diff --git a/eventemitter3/index.d.ts b/eventemitter3/index.d.ts index 31ede80c21851e..9c1fe2397e86b6 100644 --- a/eventemitter3/index.d.ts +++ b/eventemitter3/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for EventEmitter3 1.1.1 +// Type definitions for EventEmitter3 1.2.0 // Project: https://github.com/primus/eventemitter3 -// Definitions by: Yuichi Murata , Leon Yu +// Definitions by: Yuichi Murata , Leon Yu , Boriss Nazarovs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = EventEmitter; @@ -10,6 +10,10 @@ declare namespace EventEmitter { } type self = EventEmitter; +/** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + */ declare class EventEmitter { static prefixed: string | boolean; @@ -28,96 +32,91 @@ declare class EventEmitter { constructor(); /** - * Return a list of assigned event listeners. + * Return an array listing the events for which the emitter has registered listeners. * - * @param {String} event The events that should be listed. - * @returns {Array} - * @api public + * @returns {(string | symbol)[]} */ - listeners(event?: string): Function[]; + eventNames(): (string | symbol)[]; /** - * Return a list of assigned event listeners. + * Return the listeners registered for a given event. * - * @param {String} event The events that should be listed. - * @param {Boolean} exists We only need to know if there are listeners. - * @returns {Boolean} - * @api public + * @param {(string | symbol)} event The event name. + * @returns {Function[]} */ - listeners(event: string, param: boolean): boolean; + listeners(event: string | symbol): Function[]; /** - * Emit an event to all registered event listeners. + * Check if there listeners for a given event. + * If `exists` argument is not `true` lists listeners. * - * @param {String} event The name of the event. - * @returns {Boolean} Indication if we've emitted an event. - * @api public + * @param {(string | symbol)} event The event name. + * @param {boolean} exists Only check if there are listeners. + * @returns {boolean} */ - emit(event: string, ...args: any[]): boolean; + listeners(event: string | symbol, exists: boolean): boolean; /** - * Register a new EventListener for the given event. + * Calls each of the listeners registered for a given event. * - * @param {String} event Name of the event. - * @param {Function} fn Callback function. - * @param {Mixed} [context=this] The context of the function. - * @api public + * @param {(string | symbol)} event The event name. + * @param {...*} args Arguments that are passed to registered listeners + * @returns {boolean} `true` if the event had listeners, else `false`. */ - on(event: string, fn: Function, context?: any): EventEmitter; + emit(event: string | symbol, ...args: any[]): boolean; /** - * Add an EventListener that's only called once. + * Add a listener for a given event. * - * @param {String} event Name of the event. - * @param {Function} fn Callback function. - * @param {Mixed} [context=this] The context of the function. - * @api public + * @param {(string | symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. */ - once(event: string, fn: Function, context?: any): EventEmitter; + on(event: string | symbol, fn: Function, context?: any): this; /** - * Remove event listeners. + * Add a one-time listener for a given event. * - * @param {String} event The event we want to remove. - * @param {Function} fn The listener that we need to find. - * @param {Mixed} context Only remove listeners matching this context. - * @param {Boolean} once Only remove once listeners. - * @api public + * @param {(string | symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. */ - removeListener(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + once(event: string | symbol, fn: Function, context?: any): this; /** - * Remove all listeners or only the listeners for the specified event. + * Remove the listeners of a given event. * - * @param {String} event The event want to remove all listeners for. - * @api public + * @param {(string | symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. */ - removeAllListeners(event?: string): EventEmitter; + removeListener(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; /** - * Remove event listeners. + * Remove all listeners, or those of the specified event. * - * @param {String} event The event we want to remove. - * @param {Function} fn The listener that we need to find. - * @param {Mixed} context Only remove listeners matching this context. - * @param {Boolean} once Only remove once listeners. - * @api public + * @param {(string | symbol)} event The event name. + * @returns {EventEmitter} `this`. */ - off(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + removeAllListeners(event?: string | symbol): this; /** - * Register a new EventListener for the given event. - * - * @param {String} event Name of the event. - * @param {Function} fn Callback function. - * @param {Mixed} [context=this] The context of the function. - * @api public + * Alias method for `removeListener` + */ + off(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; + + /** + * Alias method for `on` */ - addListener(event: string, fn: Function, context?: any): EventEmitter; + addListener(event: string | symbol, fn: Function, context?: any): this; /** * This function doesn't apply anymore. * @deprecated */ - setMaxListeners(): EventEmitter; + setMaxListeners(): this; } diff --git a/fusioncharts/fusioncharts-tests.ts b/fusioncharts/fusioncharts-tests.ts new file mode 100644 index 00000000000000..9bbf6402258892 --- /dev/null +++ b/fusioncharts/fusioncharts-tests.ts @@ -0,0 +1,49 @@ +FusionCharts.addEventListener('ready',(eventObject)=>{ + eventObject.stopPropagation(); +}); + +FusionCharts.ready((fusioncharts)=>{ + +}); + +FusionCharts.version; + +FusionCharts('chartId').render();; + +FusionCharts["debugger"].enable(true); + +let chartData ={ + type: 'column2d', + renderAt: 'chart-container', + width: '450', + height: '200', + dataFormat: 'json', + dataSource: { + "chart": { + "caption": "Monthly revenue for last year", + "subCaption": "Harry's SuperMart", + }, + "data": [{ + "label": "Jan", + "value": "420000" + }, { + "label": "Feb", + "value": "810000" + } + ] + } +}; + +let chart = new FusionCharts(chartData); +chart.render(); +chart.isActive(); +chart.addEventListener('ready',function(eventObject){ + eventObject.type; +}); +chart.chartType(); +chart.addVariable(); +chart.clone(); +chart.zoomTo(0,3); +chart.zoomOut(); +chart.setJSONData(chartData); +chart.ref; \ No newline at end of file diff --git a/fusioncharts/index.d.ts b/fusioncharts/index.d.ts new file mode 100644 index 00000000000000..dc053859b93f6e --- /dev/null +++ b/fusioncharts/index.d.ts @@ -0,0 +1,297 @@ +// Type definitions for FusionCharts 3.11.2 +// Project: http://www.fusioncharts.com +// Definitions by: Shivaraj KV +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare namespace FusionCharts { + + type ChartDataFormats = 'json' | 'jsonurl' | 'csv' | 'xml' | 'xmlurl'; + + type ImageHAlign = 'left' | 'right' | 'middle'; + + type ImageVAlign = 'top' | 'bottom' | 'middle'; + + interface EventObject { + type: string; + + eventId: number; + + sender: FusionCharts; + + cancelled: boolean; + + stopPropagation: () => void; + + prevented: boolean; + + preventDefault: () => void; + + detached: boolean; + + detachHandler: () => void; + } + + interface ChartObject { + + type?: string; + + id?: string; + + width?: number | string; + + height?: number | string; + + renderAt?: string; + + dataFormat?: ChartDataFormats; + + dataSource?: string | {}; + + events?: {}; + + link?: {}; + + showDataLoadingMessage?: boolean; + + showChartLoadingMessage?: boolean; + + baseChartMessageFont?: string; + + baseChartMessageFontSize?: string; + + baseChartMessageColor?: string; + + dataLoadStartMessage?: string; + + dataLoadErrorMessage?: string; + + dataInvalidMessage?: string; + + dataEmptyMessage?: string; + + typeNotSupportedMessage?: string; + + loadMessage?: string; + + renderErrorMessage?: string; + + containerBackgroundColor?: string; + + containerBackgroundOpacity?: number; + + containerClassName?: string; + + baseChartMessageImageHAlign?: ImageHAlign; + + dataLoadErrorMessageImageVAlign?: ImageVAlign; + + dataLoadErrorMessageImageAlpha?: number; + + dataLoadErrorMessageImageScale?: number; + + dataLoadStartMessageImageHAlign?: ImageHAlign; + + dataLoadStartMessageImageVAlign?: ImageVAlign; + + dataLoadStartMessageImageAlpha?: number; + + dataLoadStartMessageImageScale?: number; + + dataInvalidMessageImageHAlign?: ImageHAlign; + + dataInvalidMessageImageVAlign?: ImageVAlign; + + dataInvalidMessageImageAlpha?: number; + + dataInvalidMessageImageScale?: number; + + dataEmptyMessageImageHAlign?: ImageHAlign; + + dataEmptyMessageImageVAlign?: ImageVAlign; + + dataEmptyMessageImageAlpha?: number; + + dataEmptyMessageImageScale?: number; + + renderErrorMessageImageHAlign?: ImageHAlign; + + renderErrorMessageImageVAlign?: ImageVAlign; + + renderErrorMessageImageAlpha?: number; + + renderErrorMessageImageScale?: number; + + loadMessageImageHAlign?: ImageHAlign; + + loadMessageImageVAlign?: ImageVAlign; + + loadMessageImageAlpha?: number; + + loadMessageImageScale?: number; + } + + interface Debugger { + outputFormat(format: any): void; + + outputTo(callback: (message: any) => any): void; + + enable(state:any,outputTo?:(message: any) =>any,outputFormat?:any):void + + enableFirebugLite():any; + } + + interface FusionCharts { + clone(overrides?: {}, argsOnly?: boolean): any; + + isActive(): boolean; + + chartType(value?: string, options?: any): string; + + addEventListener(type: string | string[], listener: (eventObject?: EventObject, eventArgs?: {}) => void): void; + + removeEventListener(type: string | string[], listener: (eventObject?: EventObject, eventArgs?: {}) => void): void; + + configureLink(param: {} | any[], level?: number): void; + + setChartAttribute(attributes: ChartObject | String, value?: string): void; + + getChartAttribute(attribute?: string | string[]): ChartObject; + + getXMLData(): any; + + setXMLData(data: string | {}): void; + + setXMLUrl(url: string): void; + + setChartDataUrl(url: string, format: ChartDataFormats): void; + + setChartData(data: string | {}, format: ChartDataFormats): void; + + getChartData(format: ChartDataFormats): any; + + dataReady(available?: boolean): boolean; + + feedData(stream: string): void; + + getData(): any; + + getDataWithId(): any; + + setData(value: number, label: string): void; + + stopUpdate(): void; + + restartUpdate(): void; + + isUpdateActive(): boolean; + + clearChart(): void; + + getSWFHTML(): any; + + addVariable(): void; + + getXML(): any; + + setDataXML(data: string | {}): void; + + setDataURL(url: string): void; + + hasRendered(): boolean; + + setTransparent(transparency?: boolean): void; + + isPlotItemSliced(index: number): boolean; + + slicePlotItem(index: number, slice: boolean): void; + + centerLabel(labelText: string, options?: {}): void; + + startingAngle(angle?: number, relative?: boolean): void; + + zoomOut(): void; + + zoomTo(startIndex: number, endIndex: number): void; + + resetChart(): void; + + setZoomMode(yes: boolean): void; + + getViewStartIndex(): number; + + getViewEndIndex(): number; + + print(options?: {}): void; + + exportChart(options?: {}): void; + + getSVGString(): string; + + lockResize(state: boolean): boolean; + + showChartMessage(text: string, modal?: boolean, cancelable?: boolean): void; + + getJSONData(): JSON; + + setJSONData(data: string | {}): void; + + setJSONUrl(url: string): void; + + getCSVData(): any; + + getDataAsCSV(): any; + + render(containerElement?: string | Element, insertMode?: string, callback?: () => any): FusionCharts; + + resizeTo(width: number | string, height: number | string): any; + + dispose(): void; + + configure(options: {}): void; + + ref: {}; + + } + + interface FusionChartStatic { + new (chartObject: ChartObject|{}): FusionCharts; + + (chartId: string): FusionCharts; + + getObjectReference(elementId: string): Element; + + addEventListener(type: string | string[], listener: (eventObject?: EventObject, eventArgs?: {}) => void): void; + + removeEventListener(type: string | string[], listener: (eventObject?: EventObject, eventArgs?: {}) => void): void; + + ready(callback: (fusionChartStatic?: FusionChartStatic) => any, context?: any): FusionChartStatic; + + transcodeData(data: string | {}, source: ChartDataFormats, target: ChartDataFormats, advanced: boolean): any; + + batchExport(options: {}): void; + + formatNumber(num: number, type?: string, config?: {}): Element; + + setCurrentRenderer(name: string): void + + getCurrentRenderer(): string; + + render(options?: ChartObject, callback?: () => any): FusionCharts; + + version: string[]; + + items: {}; + + options: {}; + + debugger:Debugger; + + + } + +} + +declare var FusionCharts: FusionCharts.FusionChartStatic; +export = FusionCharts; +export as namespace FusionCharts; diff --git a/fusioncharts/tsconfig.json b/fusioncharts/tsconfig.json new file mode 100644 index 00000000000000..8abb296baba6c1 --- /dev/null +++ b/fusioncharts/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fusioncharts-tests.ts" + ] +} \ No newline at end of file diff --git a/gapi.analytics/gapi.analytics-tests.ts b/gapi.analytics/gapi.analytics-tests.ts new file mode 100644 index 00000000000000..2c35403d100c5d --- /dev/null +++ b/gapi.analytics/gapi.analytics-tests.ts @@ -0,0 +1,63 @@ +// Type definitions for Google Analytics API + +function test_namespace() { + var analytics : boolean = gapi.client.analytics instanceof Object; + + var provisioning : boolean = gapi.client.analytics.provisioning.createAccountTicket instanceof Function; + analytics = analytics && provisioning; + + var data : boolean = gapi.client.analytics.data.ga.get instanceof Function; + data = data && gapi.client.analytics.data.mcf.get instanceof Function; + data = data && gapi.client.analytics.data.realtime.get instanceof Function; + analytics = analytics && data; + + interface AnalyticsParameter { + "type" ?: string; + "description" ?: string; + "default" ?: string; + "enum" ?: string[]; + "enumDescriptions" ?: string[]; + "location" ?: string; + } + var kBI : AnalyticsParameter = gapi.client.analytics.kB.parameters.alt; + var kB = !!kBI; + kBI = gapi.client.analytics.kB.parameters.fields; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.key; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.oauth_token; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.prettyPrint; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.quotaUser; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.userIP; + kB = kB && !!kBI; + analytics = analytics && kB; + + var management : boolean = gapi.client.analytics.management.accountSummaries.list instanceof Function; + management = management && gapi.client.analytics.management.accountUserLinks.list instanceof Function; + management = management && gapi.client.analytics.management.accounts.list instanceof Function; + management = management && gapi.client.analytics.management.customDataSources.list instanceof Function; + management = management && gapi.client.analytics.management.customDimensions.list instanceof Function; + management = management && gapi.client.analytics.management.customMetrics.list instanceof Function; + management = management && gapi.client.analytics.management.experiments.list instanceof Function; + management = management && gapi.client.analytics.management.filters.list instanceof Function; + management = management && gapi.client.analytics.management.goals.list instanceof Function; + management = management && gapi.client.analytics.management.profileFilterLinks.list instanceof Function; + management = management && gapi.client.analytics.management.profileUserLinks.list instanceof Function; + management = management && gapi.client.analytics.management.profiles.list instanceof Function; + management = management && gapi.client.analytics.management.remarketingAudience.list instanceof Function; + management = management && gapi.client.analytics.management.segments.list instanceof Function; + management = management && gapi.client.analytics.management.unsampledReports.list instanceof Function; + management = management && gapi.client.analytics.management.uploads.list instanceof Function; + management = management && gapi.client.analytics.management.webPropertyAdWordsLinks.list instanceof Function; + management = management && gapi.client.analytics.management.webproperties.list instanceof Function; + management = management && gapi.client.analytics.management.webpropertyUserLinks.list instanceof Function; + analytics = analytics && management; + + var metadata : boolean = gapi.client.analytics.metadata.column.list instanceof Function; + analytics = analytics && metadata; + + return analytics; +} diff --git a/gapi.analytics/index.d.ts b/gapi.analytics/index.d.ts new file mode 100644 index 00000000000000..31bbd1a83b0295 --- /dev/null +++ b/gapi.analytics/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for Google Analytics API +// Project: https://developers.google.com/analytics/devguides/reporting/core/v4/ +// Definitions by: César Costas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace gapi.client.analytics {} +declare namespace gapi.client.analytics.provisioning { + export function createAccountTicket() : Promise; +} + +interface DataQuery { + "ids" ?: string; + "start-date" ?: string; + "30daysAgo" ?: string; + "end-date" ?: string; + "yesterday" ?: string; + "metrics" ?: string; + "dimensions" ?: string; + "sort" ?: string; + "filters" ?: string; + "segment" ?: string; + "samplingLevel" ?: string; + "include-empty-rows" ?: string; + "start-index" ?: string; + "max-results" ?: string; +} +declare namespace gapi.client.analytics.data {} +declare namespace gapi.client.analytics.data.ga { + export function get(data ?: DataQuery) : Promise; +} +declare namespace gapi.client.analytics.data.mcf { + export function get(data ?: DataQuery) : Promise; +} +declare namespace gapi.client.analytics.data.realtime { + export function get(data ?: DataQuery) : Promise; +} + +declare namespace gapi.client.analytics.kB {} +declare namespace gapi.client.analytics.kB.parameters { + export interface AnalyticsParameter { + "type" ?: string; + "description" ?: string; + "default" ?: string; + "enum" ?: string[]; + "enumDescriptions" ?: string[]; + "location" ?: string; + } + export class alt implements AnalyticsParameter {} + export class fields implements AnalyticsParameter {} + export class key implements AnalyticsParameter {} + export class oauth_token implements AnalyticsParameter {} + export class prettyPrint implements AnalyticsParameter {} + export class quotaUser implements AnalyticsParameter {} + export class userIP implements AnalyticsParameter {} +} + +interface View { + accountId ?: string; + webPropertyId ?: string; + webViewId ?: string; +} +declare namespace gapi.client.analytics.management {} +declare namespace gapi.client.analytics.management.accountSummaries { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.accountUserLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.accounts { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.customDataSources { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.customDimensions { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.customMetrics { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.experiments { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.filters { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.goals { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.profileFilterLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.profileUserLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.profiles { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.remarketingAudience { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.segments { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.unsampledReports { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.uploads { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.webPropertyAdWordsLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.webproperties { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.webpropertyUserLinks { + export function list(view ?: View) : Promise; +} + +declare namespace gapi.client.analytics.metadata {} +declare namespace gapi.client.analytics.metadata.column { + export function list() : Promise; +} diff --git a/gapi.analytics/tsconfig.json b/gapi.analytics/tsconfig.json new file mode 100644 index 00000000000000..73c4caf42d470f --- /dev/null +++ b/gapi.analytics/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gapi.analytics-tests.ts" + ] +} \ No newline at end of file diff --git a/highcharts/index.d.ts b/highcharts/index.d.ts index 4c71b46e730b48..626ff59482aed2 100644 --- a/highcharts/index.d.ts +++ b/highcharts/index.d.ts @@ -5946,6 +5946,19 @@ declare namespace Highcharts { * @since 2.0.5 */ showLoading(str?: string): void; + /** + * A generic function to update any element of the chart. Elements can be enabled and disabled, moved, re-styled, + * re-formatted etc. + * A special case is configuration objects that take arrays, for example xAxis, yAxis or series. For these collections, + * an id option is used to map the new option set to an existing object. If an existing object of the same id is not + * found, the first item is updated. So for example, running chart.update with a series item without an id, will cause + * the existing chart's first series to be updated. + * See also the responsive option set. Switching between responsive.rules basically runs chart.update under the hood. + * @param {ChartOptions} option A configuration object for the new chart options as defined in the options section of the API. + * @param [boolean] redraw Whether to redraw the chart. Defaults to true. + * @since 5.0.0 + */ + update(options: ChartOptions, redraw?: boolean): void; /** * This method is deprecated as of 2.0.1. Updating the chart position after a move operation is no longer necessary. * @since 1.2.5 diff --git a/immutable/index.d.ts b/immutable/index.d.ts index cbc27ab300f571..9cadb3c29e28f1 100644 --- a/immutable/index.d.ts +++ b/immutable/index.d.ts @@ -260,11 +260,11 @@ declare namespace Immutable { * @see `Map#mergeWith` */ mergeWith( - merger: (previous?: T, next?: T, key?: number) => T, + merger: (previous: T, next: T, key: number) => T, ...iterables: Iterable.Indexed[] ): List; mergeWith( - merger: (previous?: T, next?: T, key?: number) => T, + merger: (previous: T, next: T, key: number) => T, ...iterables: Array[] ): List; @@ -278,11 +278,11 @@ declare namespace Immutable { * @see `Map#mergeDeepWith` */ mergeDeepWith( - merger: (previous?: T, next?: T, key?: number) => T, + merger: (previous: T, next: T, key: number) => T, ...iterables: Iterable.Indexed[] ): List; mergeDeepWith( - merger: (previous?: T, next?: T, key?: number) => T, + merger: (previous: T, next: T, key: number) => T, ...iterables: Array[] ): List; @@ -541,11 +541,11 @@ declare namespace Immutable { * */ mergeWith( - merger: (previous?: V, next?: V, key?: K) => V, + merger: (previous: V, next: V, key: K) => V, ...iterables: Iterable[] ): Map; mergeWith( - merger: (previous?: V, next?: V, key?: K) => V, + merger: (previous: V, next: V, key: K) => V, ...iterables: {[key: string]: V}[] ): Map; @@ -572,11 +572,11 @@ declare namespace Immutable { * */ mergeDeepWith( - merger: (previous?: V, next?: V, key?: K) => V, + merger: (previous: V, next: V, key: K) => V, ...iterables: Iterable[] ): Map; mergeDeepWith( - merger: (previous?: V, next?: V, key?: K) => V, + merger: (previous: V, next: V, key: K) => V, ...iterables: {[key: string]: V}[] ): Map; @@ -1459,7 +1459,7 @@ declare namespace Immutable { * */ mapKeys( - mapper: (key?: K, value?: V, iter?: this) => M, + mapper: (key: K, value: V, iter: this) => M, context?: any ): /*this*/Iterable.Keyed; @@ -1474,9 +1474,9 @@ declare namespace Immutable { */ mapEntries( mapper: ( - entry?: [K, V], - index?: number, - iter?: this + entry: [K, V], + index: number, + iter: this ) => [KM, VM], context?: any ): /*this*/Iterable.Keyed; @@ -1641,7 +1641,7 @@ declare namespace Immutable { * provided predicate function. Otherwise -1 is returned. */ findIndex( - predicate: (value?: T, index?: number, iter?: this) => boolean, + predicate: (value: T, index: number, iter: this) => boolean, context?: any ): number; @@ -1650,7 +1650,7 @@ declare namespace Immutable { * provided predicate function. Otherwise -1 is returned. */ findLastIndex( - predicate: (value?: T, index?: number, iter?: this) => boolean, + predicate: (value: T, index: number, iter: this) => boolean, context?: any ): number; } @@ -1971,7 +1971,7 @@ declare namespace Immutable { * */ map( - mapper: (value?: V, key?: K, iter?: this) => M, + mapper: (value: V, key: K, iter: this) => M, context?: any ): /*this*/Iterable; @@ -1984,7 +1984,7 @@ declare namespace Immutable { * */ filter( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -1997,7 +1997,7 @@ declare namespace Immutable { * */ filterNot( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2033,7 +2033,7 @@ declare namespace Immutable { * */ sortBy( - comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: (valueA: C, valueB: C) => number ): this; @@ -2044,7 +2044,7 @@ declare namespace Immutable { * Note: This is always an eager operation. */ groupBy( - grouper: (value?: V, key?: K, iter?: this) => G, + grouper: (value: V, key: K, iter: this) => G, context?: any ): Seq.Keyed; @@ -2059,7 +2059,7 @@ declare namespace Immutable { * (including the last iteration which returned false). */ forEach( - sideEffect: (value?: V, key?: K, iter?: this) => any, + sideEffect: (value: V, key: K, iter: this) => any, context?: any ): number; @@ -2118,7 +2118,7 @@ declare namespace Immutable { * */ skipWhile( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2132,7 +2132,7 @@ declare namespace Immutable { * */ skipUntil( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2158,7 +2158,7 @@ declare namespace Immutable { * */ takeWhile( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2171,7 +2171,7 @@ declare namespace Immutable { * */ takeUntil( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2209,11 +2209,11 @@ declare namespace Immutable { * Similar to `iter.map(...).flatten(true)`. */ flatMap( - mapper: (value?: V, key?: K, iter?: this) => Iterable, + mapper: (value: V, key: K, iter: this) => Iterable, context?: any ): /*this*/Iterable; flatMap( - mapper: (value?: V, key?: K, iter?: this) => /*iterable-like*/any, + mapper: (value: V, key: K, iter: this) => /*iterable-like*/any, context?: any ): /*this*/Iterable; @@ -2230,7 +2230,7 @@ declare namespace Immutable { * @see `Array#reduce`. */ reduce( - reducer: (reduction?: R, value?: V, key?: K, iter?: this) => R, + reducer: (reduction: R, value: V, key: K, iter: this) => R, initialReduction?: R, context?: any ): R; @@ -2242,7 +2242,7 @@ declare namespace Immutable { * with `Array#reduceRight`. */ reduceRight( - reducer: (reduction?: R, value?: V, key?: K, iter?: this) => R, + reducer: (reduction: R, value: V, key: K, iter: this) => R, initialReduction?: R, context?: any ): R; @@ -2251,7 +2251,7 @@ declare namespace Immutable { * True if `predicate` returns true for all entries in the Iterable. */ every( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): boolean; @@ -2259,7 +2259,7 @@ declare namespace Immutable { * True if `predicate` returns true for any entry in the Iterable. */ some( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): boolean; @@ -2289,7 +2289,7 @@ declare namespace Immutable { */ count(): number; count( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): number; @@ -2300,7 +2300,7 @@ declare namespace Immutable { * Note: This is not a lazy operation. */ countBy( - grouper: (value?: V, key?: K, iter?: this) => G, + grouper: (value: V, key: K, iter: this) => G, context?: any ): Seq.Keyed; @@ -2311,7 +2311,7 @@ declare namespace Immutable { * Returns the first value for which the `predicate` returns true. */ find( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any, notSetValue?: V ): V; @@ -2322,7 +2322,7 @@ declare namespace Immutable { * Note: `predicate` will be called for each entry in reverse. */ findLast( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any, notSetValue?: V ): V; @@ -2331,7 +2331,7 @@ declare namespace Immutable { * Returns the first [key, value] entry for which the `predicate` returns true. */ findEntry( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any, notSetValue?: V ): [K, V]; @@ -2343,7 +2343,7 @@ declare namespace Immutable { * Note: `predicate` will be called for each entry in reverse. */ findLastEntry( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any, notSetValue?: V ): [K, V]; @@ -2352,7 +2352,7 @@ declare namespace Immutable { * Returns the key for which the `predicate` returns true. */ findKey( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): K; @@ -2362,7 +2362,7 @@ declare namespace Immutable { * Note: `predicate` will be called for each entry in reverse. */ findLastKey( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): K; @@ -2401,7 +2401,7 @@ declare namespace Immutable { * */ maxBy( - comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: (valueA: C, valueB: C) => number ): V; @@ -2430,7 +2430,7 @@ declare namespace Immutable { * */ minBy( - comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: (valueA: C, valueB: C) => number ): V; diff --git a/inquirer/index.d.ts b/inquirer/index.d.ts index 244b1ee003a8f4..b60dfef00df8f5 100644 --- a/inquirer/index.d.ts +++ b/inquirer/index.d.ts @@ -30,7 +30,8 @@ declare namespace inquirer { * @param cb Callback being passed the user answers * @return */ - prompt(questions: Questions, cb?: (answers: Answers) => any): ui.Prompt; + prompt(questions: Questions, cb: (answers: Answers) => any): ui.Prompt; + prompt(questions: Questions): Promise; prompts: Prompts; Separator: objects.SeparatorStatic; ui: { diff --git a/jasmine/index.d.ts b/jasmine/index.d.ts index 180b3ef5ba21ec..abf8ed4f82c6f8 100644 --- a/jasmine/index.d.ts +++ b/jasmine/index.d.ts @@ -155,6 +155,7 @@ declare namespace jasmine { versionString(): string; nextSpecId(): number; addReporter(reporter: Reporter): void; + addReporter(reporter: CustomReporter): void; execute(): void; describe(description: string, specDefinitions: () => void): Suite; // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these @@ -347,6 +348,45 @@ declare namespace jasmine { addReporter(reporter: Reporter): void; } + interface SuiteInfo { + totalSpecsDefined: number; + } + + interface CustomReportExpectation { + matcherName: string; + message: string; + passed: boolean; + stack: string; + } + + interface FailedExpectation extends CustomReportExpectation { + actual: string; + expected: string; + } + + interface PassedExpectation extends CustomReportExpectation { + + } + + interface CustomReporterResult { + description: string, + failedExpectations?: FailedExpectation[], + fullName: string, + id: string; + passedExpectations?: PassedExpectation[], + pendingReason?: string; + status?: string; + } + + interface CustomReporter { + jasmineStarted?(suiteInfo: SuiteInfo): void; + suiteStarted?(result: CustomReporterResult): void; + specStarted?(result: CustomReporterResult): void; + specDone?(result: CustomReporterResult): void; + suiteDone?(result: CustomReporterResult): void; + jasmineDone?(): any; + } + interface Runner { new (env: Env): any; diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index ca2b2808cc3b05..87497e90c2322b 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -902,6 +902,62 @@ describe("Custom matcher: 'toBeGoofy'", function () { }); }); +// test based on http://jasmine.github.io/2.5/custom_reporter.html +var myReporter: jasmine.CustomReporter = { + jasmineStarted: function (suiteInfo: jasmine.SuiteInfo ) { + console.log("Running suite with " + suiteInfo.totalSpecsDefined); + }, + + suiteStarted: function (result: jasmine.CustomReporterResult) { + console.log("Suite started: " + result.description + " whose full description is: " + result.fullName); + }, + + specStarted: function (result: jasmine.CustomReporterResult) { + console.log("Spec started: " + result.description + " whose full description is: " + result.fullName); + }, + + specDone: function (result: jasmine.CustomReporterResult) { + console.log("Spec: " + result.description + " was " + result.status); + for (var i = 0; i < result.failedExpectations.length; i++) { + console.log("Failure: " + result.failedExpectations[i].message); + console.log("Actual: " + result.failedExpectations[i].actual); + console.log("Expected: " + result.failedExpectations[i].expected); + console.log(result.failedExpectations[i].stack); + } + console.log(result.passedExpectations.length); + }, + + suiteDone: function (result: jasmine.CustomReporterResult) { + console.log('Suite: ' + result.description + ' was ' + result.status); + for (var i = 0; i < result.failedExpectations.length; i++) { + console.log('AfterAll ' + result.failedExpectations[i].message); + console.log(result.failedExpectations[i].stack); + } + }, + + jasmineDone: function() { + console.log('Finished suite'); + } +}; + +jasmine.getEnv().addReporter(myReporter); + +// test for custom reporter which return ES6 Promise in jasmineDone(): +var myShortReporter: jasmine.CustomReporter = { + jasmineDone: function() { + return new Promise(function(resolve, reject) { + setTimeout(() => resolve(), 10000); + }); + } +} + +var jasmineDoneResolved: Promise = myShortReporter.jasmineDone(); +jasmineDoneResolved.then(() => { + console.log("[ShortReporter] : jasmineDone Resolved"); +}); + +jasmine.getEnv().addReporter(myShortReporter); + describe("Randomize Tests", function() { it("should allow randomization of the order of tests", function() { expect(function() { diff --git a/jest/index.d.ts b/jest/index.d.ts index d0660193f66dd5..dc0260cebb6b0c 100644 --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jest 15.1.1 +// Type definitions for Jest 16.0.0 // Project: http://facebook.github.io/jest/ // Definitions by: Asana , Ivo Stratev , jwbay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,23 +26,25 @@ interface NodeRequire { } declare namespace jest { - function addMatchers(matchers: jasmine.CustomMatcherFactories): void; + function addMatchers(matchers: jasmine.CustomMatcherFactories): typeof jest; /** Disables automatic mocking in the module loader. */ - function autoMockOff(): void; + function autoMockOff(): typeof jest; /** Enables automatic mocking in the module loader. */ - function autoMockOn(): void; + function autoMockOn(): typeof jest; + /** Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function. */ + function clearAllMocks(): typeof jest; /** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */ - function clearAllTimers(): void; + function clearAllTimers(): typeof jest; /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ - function deepUnmock(moduleName: string): void; + function deepUnmock(moduleName: string): typeof jest; /** Disables automatic mocking in the module loader. */ - function disableAutomock(): void; + function disableAutomock(): typeof jest; /** Mocks a module with an auto-mocked version when it is being required. */ - function doMock(moduleName: string): void; + function doMock(moduleName: string): typeof jest; /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ - function dontMock(moduleName: string): void; + function dontMock(moduleName: string): typeof jest; /** Enables automatic mocking in the module loader. */ - function enableAutomock(): void; + function enableAutomock(): typeof jest; /** Creates a mock function. Optionally takes a mock implementation. */ function fn(implementation?: Function): Mock; /** Use the automatic mocking system to generate a mocked version of the given module. */ @@ -50,28 +52,30 @@ declare namespace jest { /** Returns whether the given function is a mock function. */ function isMockFunction(fn: any): fn is Mock; /** Mocks a module with an auto-mocked version when it is being required. */ - function mock(moduleName: string, factory?: any, options?: MockOptions): void; + function mock(moduleName: string, factory?: any, options?: MockOptions): typeof jest; /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ - function resetModuleRegistry(): void; + function resetModuleRegistry(): typeof jest; /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ - function resetModules(): void; + function resetModules(): typeof jest; /** Exhausts tasks queued by setImmediate(). */ - function runAllImmediates(): void; + function runAllImmediates(): typeof jest; /** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */ - function runAllTicks(): void; + function runAllTicks(): typeof jest; /** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */ - function runAllTimers(): void; + function runAllTimers(): typeof jest; /** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). * If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */ - function runOnlyPendingTimers(): void; + function runOnlyPendingTimers(): typeof jest; + /** Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()). */ + function runTimersToTime(msToRun: number): typeof jest; /** Explicitly supplies the mock object that the module system should return for the specified module. */ - function setMock(moduleName: string, moduleExports: T): void; + function setMock(moduleName: string, moduleExports: T): typeof jest; /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ - function unmock(moduleName: string): void; + function unmock(moduleName: string): typeof jest; /** Instructs Jest to use fake versions of the standard timer functions. */ - function useFakeTimers(): void; + function useFakeTimers(): typeof jest; /** Instructs Jest to use the real versions of the standard timer functions. */ - function useRealTimers(): void; + function useRealTimers(): typeof jest; interface MockOptions { virtual?: boolean; @@ -98,6 +102,7 @@ declare namespace jest { (name: string, fn: ProvidesCallback): void; only: It; skip: It; + concurrent: It; } interface Describe { @@ -124,6 +129,7 @@ declare namespace jest { toBeTruthy(): void; toBeUndefined(): void; toContain(expected: any): void; + toContainEqual(expected: any): void; toEqual(expected: any): void; toHaveBeenCalled(): boolean; toHaveBeenCalledTimes(expected: number): boolean; @@ -132,6 +138,7 @@ declare namespace jest { toMatchSnapshot(): void; toThrow(): void; toThrowError(error?: string | Constructable | RegExp): void; + toThrowErrorMatchingSnapshot(): void; } interface Constructable { diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index e774ad1fb54dcc..4b81f6282cd4e0 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -208,6 +208,8 @@ describe('missing tests', function () { expect(getFruits()).toContain('Orange'); mock.mockReturnValueOnce(['Apple', 'Plum']); expect(mock()).not.toContain('Orange'); + const myBeverage: any = {delicious: true, sour: false}; + expect(myBeverage).toContainEqual({delicious: true, sour: false}); mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. mock.mockClear(); let thisMock: jest.Mock = jest.fn().mockReturnThis(); @@ -215,8 +217,7 @@ describe('missing tests', function () { }); it('creates snapshoter', function () { - jest.disableAutomock(); - jest.mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); + jest.disableAutomock().mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); const render: () => string = require('./render'); expect(render()).toMatch(/Link/); jest.enableAutomock(); @@ -225,7 +226,7 @@ describe('missing tests', function () { it('runs only pending timers', function () { jest.useRealTimers(); setTimeout(() => expect(1).not.toEqual(0), 3000); - jest.runOnlyPendingTimers(); + jest.runOnlyPendingTimers().runTimersToTime(300); }); it('runs all timers', function () { @@ -249,6 +250,12 @@ describe('toMatchSnapshot', function () { }); }); +describe('toThrowErrorMatchingSnapshot', function () { + it('compares snapshots', function () { + expect(() => { throw new Error('descriptiton') }).toThrowErrorMatchingSnapshot(); + }); +}); + function testInstances() { var mockFn = jest.fn(); var a = new mockFn(); diff --git a/joi/index.d.ts b/joi/index.d.ts index c192f49dd1a08c..2f803cdf7d9dbb 100644 --- a/joi/index.d.ts +++ b/joi/index.d.ts @@ -40,6 +40,10 @@ export interface ValidationOptions { * provides an external data set to be used in references */ context?: Object; + /** + * when true, do not apply default values. Defaults to false. + */ + noDefaults?: boolean; } export interface RenameOptions { @@ -288,6 +292,16 @@ export interface AnySchema> { * @param schema - any object or joi schema to match. An undefined schema unsets that rule. */ empty(schema?: any): T; + /** + * Overrides the default joi error with a custom error if the rule fails where: + * @param err - the override error. + * + * Note that the provided error will be returned as-is, unmodified and undecorated + * with any of the normal joi error properties. If validation fails and another + * error is found before the error override, that error will be returned and the + * override will be ignored (unless the abortEarly option has been set to false). + */ + error?(err: Error): T; } export interface BooleanSchema extends AnySchema { @@ -828,10 +842,18 @@ export declare function lazy(cb: () => Schema): Schema; /** * Validates a value using the given schema and options. */ -export declare function validate(value: T, schema: Schema, callback: (err: ValidationError, value: T) => void): void; -export declare function validate(value: T, schema: Object, callback: (err: ValidationError, value: T) => void): void; -export declare function validate(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): ValidationResult; - +export function validate(value: T): ValidationResult; +export function validate(value: T, callback: (err: ValidationError, value: T) => R): R; + +export function validate(value: T, schema: Schema): ValidationResult; +export function validate(value: T, schema: Object): ValidationResult; +export function validate(value: T, schema: Schema, callback: (err: ValidationError, value: T) => R): R; +export function validate(value: T, schema: Object, callback: (err: ValidationError, value: T) => R): R; + +export function validate(value: T, schema: Schema, options: ValidationOptions): ValidationResult; +export function validate(value: T, schema: Object, options: ValidationOptions): ValidationResult; +export function validate(value: T, schema: Schema, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; +export function validate(value: T, schema: Object, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; /** * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object). */ @@ -879,3 +901,118 @@ export function reach(schema: Schema, path: string): Schema; * Creates a new Joi instance customized with the extension(s) you provide included. */ export function extend(extention: Extension): any; + +/** + * Whitelists a value + */ +export function allow(value: any, ...values: any[]): Schema; +export function allow(values: any[]): Schema; + +/** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ +export function valid(value: any, ...values: any[]): Schema; +export function valid(values: any[]): Schema; +export function only(value: any, ...values : any[]): Schema; +export function only(values: any[]): Schema; +export function equal(value: any, ...values : any[]): Schema; +export function equal(values: any[]): Schema; + +/** + * Blacklists a value + */ +export function invalid(value: any, ...values: any[]): Schema; +export function invalid(values: any[]): Schema; +export function disallow(value: any, ...values : any[]): Schema; +export function disallow(values: any[]): Schema; +export function not(value: any, ...values : any[]): Schema; +export function not(values: any[]): Schema; + +/** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ +export function required(): Schema; + +/** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ +export function optional(): Schema; + +/** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ +export function forbidden(): Schema; + +/** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ +export function strip(): Schema; + +/** + * Annotates the key + */ +export function description(desc: string): Schema; + +/** + * Annotates the key + */ +export function notes(notes: string): Schema; +export function notes(notes: string[]): Schema; + +/** + * Annotates the key + */ +export function tags(notes: string): Schema; +export function tags(notes: string[]): Schema; + +/** + * Attaches metadata to the key. + */ +export function meta(meta: Object): Schema; + +/** + * Annotates the key with an example value, must be valid. + */ +export function example(value: any): Schema; + +/** + * Annotates the key with an unit name. + */ +export function unit(name: string): Schema; + +/** + * Overrides the global validate() options for the current key and any sub-key. + */ +export function options(options: ValidationOptions): Schema; + +/** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ +export function strict(isStrict?: boolean): Schema; + +/** + * Returns a new type that is the result of adding the rules of one type to another. + */ +export function concat(schema: T): T; + +/** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ +export function when(ref: string, options: WhenOptions): AlternativesSchema; +export function when(ref: Reference, options: WhenOptions): AlternativesSchema; + +/** + * Overrides the key name in error messages. + */ +export function label(name: string): Schema; + +/** + * Outputs the original untouched value instead of the casted value. + */ +export function raw(isRaw?: boolean): Schema; + +/** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ +export function empty(schema?: any) : Schema; diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 759be529ad03c4..d50db6eedd7d77 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -58,6 +58,7 @@ validOpts = {stripUnknown: bool}; validOpts = {language: bool}; validOpts = {presence: str}; validOpts = {context: obj}; +validOpts = {noDefaults: bool}; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -222,6 +223,8 @@ namespace common { anySchema = anySchema.empty(); anySchema = anySchema.empty(str); anySchema = anySchema.empty(anySchema); + + anySchema = anySchema.error(err); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -757,30 +760,57 @@ schema = Joi.lazy(() => schema) // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -Joi.validate(value, obj); -Joi.validate(value, schema); -Joi.validate(value, schema, validOpts); -Joi.validate(value, schema, validOpts, (err, value) => { +namespace validate_tests { + { + Joi.validate(value, obj); + Joi.validate(value, schema); + Joi.validate(value, schema, validOpts); + Joi.validate(value, schema, validOpts, (err, value) => { x = value; str = err.message; str = err.details[0].path; str = err.details[0].message; str = err.details[0].type; -}); -Joi.validate(value, schema, (err, value) => { + }); + Joi.validate(value, schema, (err, value) => { x = value; str = err.message; str = err.details[0].path; str = err.details[0].message; str = err.details[0].type; -}); -// variant -Joi.validate(num, schema, validOpts, (err, value) => { + }); + // variant + Joi.validate(num, schema, validOpts, (err, value) => { num = value; -}); + }); + + // plain opts + Joi.validate(value, {}); + } + + { + let value = { username: 'example', password: 'example' }; + let schema = Joi.object().keys({ + username: Joi.string().max(255).required(), + password: Joi.string().regex(/^[a-zA-Z0-9]{3,255}$/).required(), + }); + let returnValue: Joi.ValidationResult; + + returnValue = Joi.validate(value); + value = Joi.validate(value, (err, value) => value); + + returnValue = Joi.validate(value, schema); + returnValue = Joi.validate(value, obj); + value = Joi.validate(value, obj, (err, value) => value); + value = Joi.validate(value, schema, (err, value) => value); + + returnValue = Joi.validate(value, schema, validOpts); + returnValue = Joi.validate(value, obj, validOpts); + value = Joi.validate(value, obj, validOpts, (err, value) => value); + value = Joi.validate(value, schema, validOpts, (err, value) => value); + } +} -// plain opts -Joi.validate(value, {}); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -802,3 +832,56 @@ Joi.isRef(ref); schema = Joi.reach(schema, ''); const Joi2 = Joi.extend({ name: '', base: schema }); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); diff --git a/jquery.datatables/index.d.ts b/jquery.datatables/index.d.ts index b331352ce366fc..81c50276193015 100644 --- a/jquery.datatables/index.d.ts +++ b/jquery.datatables/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for JQuery DataTables 1.10.7 +// Type definitions for JQuery DataTables 1.10.8 // Project: http://www.datatables.net // Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -182,11 +182,11 @@ declare namespace DataTables { destroy(remove?: boolean): DataTable; /** - * Redraw the table. + * Redraw the DataTables in the current context, optionally updating ordering, searching and paging as required. * - * @param reset Reset (default) or hold the current paging position. A full re-sort and re-filter is performed when this method is called, which is why the pagination reset is the default action. + * @param paging This parameter is used to determine what kind of draw DataTables will perform. */ - draw(reset?: boolean): DataTable; + draw(paging?: boolean | string): DataTable; /* * Look up a language token that was defined in the DataTables' language initialisation object. @@ -374,6 +374,7 @@ declare namespace DataTables { length: number; recordsTotal: number; recordsDisplay: number; + serverSide: boolean } //#endregion "page-methods" @@ -436,6 +437,11 @@ declare namespace DataTables { */ concat(a: Object, ...b: Object[]): DataTable; + /** + * Get the number of entries in an API instance's result set, regardless of multi-table grouping (e.g. any data, selected rows, etc). Since: 1.10.8 + */ + count(): number; + /** * Iterate over the contents of the API result set. * @@ -910,6 +916,15 @@ declare namespace DataTables { */ id(hash?: boolean): string; + /** + * Get the id of the selected row. Since: 1.10.8 + * + * @param hash true - Append a hash (#) to the start of the row id. This can be useful for then using the id as a selector + * false - Do not modify the id value. + * @returns Row id. If the row does not have an id available 'undefined' will be returned. + */ + id(hash?: boolean): string; + /** * Get the row index of the row column. */ @@ -970,6 +985,15 @@ declare namespace DataTables { */ every(fn: (rowIdx: number, tableLoop: number, rowLoop: number) => void): DataTable; + /** + * Get the ids of the selected rows. Since: 1.10.8 + * + * @param hash true - Append a hash (#) to the start of each row id. This can be useful for then using the ids as selectors + * false - Do not modify the id value. + * @returns Api instance with the selected rows in its result set. If a row does not have an id available 'undefined' will be returned as the value. + */ + ids(hash?: boolean): DataTable; + /** * Get the row indexes of the selected rows. */ @@ -1057,11 +1081,12 @@ declare namespace DataTables { isDataTable(table: string): boolean; /** - * Get all DataTables on the page + * Get all DataTable tables that have been initialised - optionally you can select to get only currently visible tables and / or retrieve the tables as API instances. * - * @param visible Get only visible tables + * @param visible As a boolean value this options is used to indicate if you want all tables on the page should be returned (false), or visible tables only (true). + * Since 1.10.8 this option can also be given as an object. */ - tables(visible?: boolean): DataTables.DataTable[]; + tables(visible?: boolean | ObjectTablesStatic): DataTables.DataTable[] | DataTables.DataTable; /** * Version number compatibility check function @@ -1100,6 +1125,18 @@ declare namespace DataTables { throttle(fn: Function, period?: number): Function; } + interface ObjectTablesStatic { + /** + * Get only visible tables (true) or all tables regardless of visibility (false). + */ + visible: boolean + + /** + * Return a DataTables API instance for the selected tables (true) or an array (false). + */ + api: boolean + } + //#endregion "Static-Methods" //#region "Settings" @@ -1257,7 +1294,7 @@ declare namespace DataTables { pageLength?: number; /** - * Pagination button display options. Basic Types: simple, simple_numbers, full, full_numbers + * Pagination button display options. Basic Types: numbers (1.10.8) simple, simple_numbers, full, full_numbers */ pagingType?: string; @@ -1271,6 +1308,11 @@ declare namespace DataTables { */ renderer?: string | RendererSettings; + /** + * Data property name that DataTables will use to set element DOM IDs. Since: 1.10.8 + */ + rowId?: string; + /** * Allow the table to reduce in height when a limited number of rows are shown. Since: 1.10 */ diff --git a/jquery.datatables/jquery.dataTables-tests.ts b/jquery.datatables/jquery.dataTables-tests.ts index 28d957ec50da2d..fae4892c5588fe 100644 --- a/jquery.datatables/jquery.dataTables-tests.ts +++ b/jquery.datatables/jquery.dataTables-tests.ts @@ -219,6 +219,7 @@ $(document).ready(function () { pagingType: "simple", retrieve: true, renderer: "bootstrap", + rowId: "custId", scrollCollapse: true, search: true, searchCols: [{ "search": "", "smart": true, "regex": false, "caseInsensitive": true }], @@ -261,7 +262,7 @@ $(document).ready(function () { { ajax: { data: ajaxDataFunc, - dataSrc: function (data) { }, + dataSrc: function (data: any) { }, }, }; @@ -305,8 +306,9 @@ $(document).ready(function () { destroy = dt.destroy(true); destroy.$(""); - var draw = dt.draw(); + var draw: DataTables.DataTable = dt.draw(); draw = dt.draw(true); + draw = dt.draw("page"); draw.$(""); var initSettings = dt.init(); @@ -343,7 +345,8 @@ $(document).ready(function () { "end": 20, "length": 10, "recordsTotal": 57, - "recordsDisplay": 57 + "recordsDisplay": 57, + "serverSide": false }; var page_len_get = dt.page.len(); @@ -401,7 +404,7 @@ $(document).ready(function () { .cache('search') .sort() .unique() - .each(function (d) { + .each(function (d: any) { select.append($('')); }); @@ -520,7 +523,7 @@ $(document).ready(function () { columns = dt.columns("selector", modifier); var columns_cache = columns.cache("order"); - dt.columns('.select-filter').eq(0).each(function (colIdx) { + dt.columns('.select-filter').eq(0).each(function (colIdx: any) { // Create the select list and search operation var select = $('') .appendTo( @@ -707,7 +710,7 @@ $(document).ready(function () { .cache('search') .sort() .unique() - .each(function (d) { + .each(function (d: any) { select.append($('')); }); }); @@ -751,6 +754,8 @@ $(document).ready(function () { var row_19 = dt.row("selector").index(); var row_20 = dt.row("selector").node(); var row_21 = dt.row("selector").remove(); + var row_22: string = dt.row("selector").id(); + var row_23: string = dt.row("selector").id(false); var rows_1 = dt.rows(); var rows_2 = dt.rows().remove(); @@ -767,6 +772,8 @@ $(document).ready(function () { var rows_13 = dt.rows.add([{}, {}]); dt.rows().every(function () { }); dt.rows().every(function (rowIdx, tableLoop, rowLoop) { }); + var rows_14: DataTables.DataTable = dt.rows("selector").ids(); + var rows_15: DataTables.DataTable = dt.rows("selector").ids(false); var table3 = $('#example').DataTable(); table3.row.add({ @@ -831,7 +838,7 @@ $(document).ready(function () { ]) .show(); - dt.rows().eq(0).each(function (rowIdx) { + dt.rows().eq(0).each(function (rowIdx: any) { dt .row(rowIdx) .child( @@ -881,6 +888,20 @@ $(document).ready(function () { //#endregion "Methods-Row" + //#region "Methods-Static" + + // Variable is a stand-in for $.fn.dataTable. See extension of JQueryStatic at the top of jquery.dataTables.d.ts. + var staticFn: DataTables.StaticFunctions; + + // With boolean parameter type, always returns DataTables.DataTable[]. + var static_1: DataTables.DataTable[] = staticFn.tables(true); + // With object parameter type, returns DataTables.DataTable[] when "api" property is false. + static_1 = staticFn.tables({ "visible": true, "api": false }); + // With object parameter type, returns DataTables.DataTable when "api" property is true. + var static_2: DataTables.DataTable = staticFn.tables({ "visible": true, "api": true }); + + //#endregion "Methods-Static" + //#region "Methods-Table" var tables = dt.tables(); @@ -905,6 +926,7 @@ $(document).ready(function () { //#region "Methods-Util" var util_1: boolean = dt.any(); + var util_2: number = dt.count(); //#endregion "Methods-Util" }); diff --git a/jquery.rateit/index.d.ts b/jquery.rateit/index.d.ts new file mode 100644 index 00000000000000..be62f3b3da33bf --- /dev/null +++ b/jquery.rateit/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for jquery.rateit.js 1.1.1 +// Project: https://github.com/gjunge/rateit.js +// Definitions by: Gidon Junge +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +type RateItMode = "bg" | "font"; +interface RateItOptions { + value? : number; + min?: number; + max?: number; + step?:number; + backingfld?:string; + readonly?:boolean; + ispreset? : boolean; + resetable? : boolean; + starwidth?: number; + starheight?: number; + mode?: RateItMode; + icon?: string; +} + +interface JQuery { + rateit() : JQuery; + rateit(options: RateItOptions) : JQuery; + + rateit(method: 'value') : number; + rateit(method: 'value', param: number) : JQuery; + + rateit(method: 'max') : number; + rateit(method: 'max', param: number) : JQuery; + + rateit(method: 'min') : number; + rateit(method: 'min', param: number) : JQuery; + + rateit(method: 'readonly') : boolean; + rateit(method: 'readonly', param: boolean) : JQuery; + + rateit(method: 'ispreset') : boolean; + rateit(method: 'ispreset', param: boolean) : JQuery; + + rateit(method: 'reset') : JQuery; + + rateit(method: string, param: any) : any; +} diff --git a/jquery.rateit/jquery.rateit-tests.ts b/jquery.rateit/jquery.rateit-tests.ts new file mode 100644 index 00000000000000..d2127cbaa02e36 --- /dev/null +++ b/jquery.rateit/jquery.rateit-tests.ts @@ -0,0 +1,46 @@ +var rateit_simple = $('.rateit').rateit(); + +var rateit_properties_font = $('.rateit').rateit({ + backingfld: '#backingfield', + icon: '@', + mode: 'font', + ispreset: false, + max: 5, + min: 0, + readonly: false, + resetable: false, + step: 0.5, + value: 2 +}); + +var rateit_properties_bg = $('.rateit').rateit({ + backingfld: '#backingfield', + mode: 'bg', + ispreset: false, + max: 5, + min: 0, + readonly: false, + resetable: false, + step: 0.5, + value: 2, + starheight: 16, + starwidth: 16 +}); + +//getters +var val : number = rateit_properties_bg.rateit('value'); +var min : number = rateit_properties_bg.rateit('min'); +var max : number = rateit_properties_bg.rateit('max'); +var readonly :boolean = rateit_properties_bg.rateit('readonly'); +var ispreset :boolean = rateit_properties_bg.rateit('ispreset'); + + +//setters +rateit_properties_bg.rateit('value',4); +rateit_properties_bg.rateit('min',0); +rateit_properties_bg.rateit('max',6); +rateit_properties_bg.rateit('readonly',true); +rateit_properties_bg.rateit('ispreset',false); + +//reset it +rateit_properties_bg.rateit('reset'); \ No newline at end of file diff --git a/jquery.rateit/tsconfig.json b/jquery.rateit/tsconfig.json new file mode 100644 index 00000000000000..0f7906596e1975 --- /dev/null +++ b/jquery.rateit/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery.rateit-tests.ts" + ] +} \ No newline at end of file diff --git a/jsonstream/JSONStream-tests.ts b/jsonstream/jsonstream-tests.ts similarity index 100% rename from jsonstream/JSONStream-tests.ts rename to jsonstream/jsonstream-tests.ts diff --git a/jsonstream/tsconfig.json b/jsonstream/tsconfig.json index 2be61cf00ed07b..bdaba2cde83bfe 100644 --- a/jsonstream/tsconfig.json +++ b/jsonstream/tsconfig.json @@ -14,6 +14,6 @@ }, "files": [ "index.d.ts", - "JSONStream-tests.ts" + "jsonstream-tests.ts" ] -} \ No newline at end of file +} diff --git a/kafka-node/index.d.ts b/kafka-node/index.d.ts index 89d68de63e4cce..347cc066f0c810 100644 --- a/kafka-node/index.d.ts +++ b/kafka-node/index.d.ts @@ -9,6 +9,7 @@ export declare class Client { constructor(connectionString: string, clientId: string, options?: ZKOptions); close(callback?: Function): void; + topicExists(topics: Array, callback: Function): void; } export declare class Producer { diff --git a/kefir/index.d.ts b/kefir/index.d.ts index 12afaad5e28a1d..d445be74add1e7 100644 --- a/kefir/index.d.ts +++ b/kefir/index.d.ts @@ -1,11 +1,20 @@ -// Type definitions for Kefir 3.2.0 +// Type definitions for Kefir 3.3.0 // Project: http://rpominov.github.io/kefir/ // Definitions by: Aya Morisawa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +export interface Subscription { + unsubscribe(): void; + closed: boolean; // Actually, `readonly` but it's avaiable in tsc starting with 2.0.0 +} +export interface Observer { + value?: (value: T) => void; + error?: (error: S) => void; + end?: () => void; +} export interface Observable { // Subscribe / add side effects @@ -22,6 +31,13 @@ export interface Observable { flatten(transformer?: (value: T) => U[]): Stream; toPromise(PromiseConstructor?: any): any; toESObservable(): any; + // This method is designed to replace all other methods for subscribing + observe(params: Observer): Subscription; + observe( + onValue?: (value: T) => void, + onError?: (error: S) => void, + onEnd?: () => void + ): Subscription; } export interface Stream extends Observable { diff --git a/kefir/kefir-tests.ts b/kefir/kefir-tests.ts index 56055d0a228324..acd0f5ae16fbee 100644 --- a/kefir/kefir-tests.ts +++ b/kefir/kefir-tests.ts @@ -69,6 +69,19 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke Kefir.sequentially(1000, [1, 2]).log('my stream'); Kefir.sequentially(1000, [1, 2]).offLog('my stream'); Kefir.sequentially(1000, [1, 2]).toPromise().then((x: number) => console.log('fulfilled with:', x)); + Kefir.sequentially(1000, [1, 2]).observe({}); + Kefir.sequentially(1000, [1, 2]).observe({ + value: _ => {}, + error: _ => {}, + end: () => {}, + }); + Kefir.sequentially(1000, [1, 2]).observe(); + const subscription = Kefir.sequentially(1000, [1, 2]).observe( + _ => {}, + _ => {}, + () => {} + ); + if (!subscription.closed) subscription.unsubscribe(); } // Modify an observable diff --git a/koa/index.d.ts b/koa/index.d.ts index 6cdb0cbcd1bc0d..7fa9dd1cc9ae5c 100644 --- a/koa/index.d.ts +++ b/koa/index.d.ts @@ -159,6 +159,7 @@ declare class Koa extends EventEmitter { constructor(); // From node.d.ts + listen(): http.Server; listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): http.Server; listen(port: number, hostname?: string, listeningListener?: Function): http.Server; listen(port: number, backlog?: number, listeningListener?: Function): http.Server; diff --git a/koa/koa-tests.ts b/koa/koa-tests.ts index b3bf036df756d1..1b261fdf448bf8 100644 --- a/koa/koa-tests.ts +++ b/koa/koa-tests.ts @@ -19,3 +19,5 @@ app.use(ctx => { }); app.listen(3000); + +const server = app.listen(); diff --git a/leaflet/index.d.ts b/leaflet/index.d.ts index d43a2303da6180..d16be0bc1f60e8 100644 --- a/leaflet/index.d.ts +++ b/leaflet/index.d.ts @@ -5,7 +5,43 @@ /// +type NativeMouseEvent = MouseEvent; + declare namespace L { + export class Class { + static extend(props:any):any/* how to return constructor of self extended type ? */; + static include(props:any):any /* how to return self extended type ? */; + static mergeOptions(props:any): any /* how to return self extended type ? */; + static addInitHook(initHookFn: ()=> void): any/* how to return self extended type ? */; + } + + export class DomUtil { + static get(id: string): HTMLElement; + static get(id: HTMLElement): HTMLElement; + static getStyle(el: HTMLElement, styleAttrib: string): string; + static create(tagName: String, className?: String, container?: HTMLElement): HTMLElement; + static remove(el: HTMLElement):void; + static empty(el: HTMLElement):void; + static toFront(el: HTMLElement):void; + static toBack(el: HTMLElement):void; + static hasClass(el: HTMLElement, name: String): Boolean; + static addClass(el: HTMLElement, name: String):void; + static removeClass(el: HTMLElement, name: String):void; + static setClass(el: HTMLElement, name: String):void; + static getClass(el: HTMLElement): String; + static setOpacity(el: HTMLElement, opacity: Number):void; + static testProp(props: String[]): String|boolean/*=false*/; + static setTransform(el: HTMLElement, offset: Point, scale?: Number):void; + static setPosition(el: HTMLElement, position: Point):void; + static getPosition(el: HTMLElement): Point + static disableTextSelection(): void + static enableTextSelection(): void + static disableImageDrag(): void + static enableImageDrag(): void + static preventOutline(el: HTMLElement): void + static restoreOutline(): void + } + export interface CRS { latLngToPoint(latlng: LatLng, zoom: number): Point; latLngToPoint(latlng: LatLngLiteral, zoom: number): Point; @@ -211,7 +247,7 @@ declare namespace L { * with an object (e.g. the user clicks on the map, causing the map to fire * 'click' event). */ - export interface Evented { + export interface Evented extends Class { /** * Adds a listener function (fn) to a particular event type of the object. * You can optionally specify the context of the listener (object the this @@ -1125,7 +1161,7 @@ declare namespace L { latlng: LatLng; layerPoint: Point; containerPoint: Point; - originalEvent: MouseEvent; // how can I reference the global MouseEvent? + originalEvent: NativeMouseEvent; } export interface LocationEvent extends Event { diff --git a/lowlight/index.d.ts b/lowlight/index.d.ts new file mode 100644 index 00000000000000..589c9b50fda342 --- /dev/null +++ b/lowlight/index.d.ts @@ -0,0 +1,99 @@ +// Type definitions for lowlight +// Project: https://github.com/wooorm/lowlight +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'lowlight' { + export { highlight, highlightAuto, registerLanguage } from 'lowlight/lib/core'; +} + +declare module 'lowlight/lib/core' { + export function highlight(language: string, value: string, options?: lowlight.HighlightOptions): lowlight.HighlightResult; + export function highlightAuto(value: string, options?: lowlight.HighlightAutoOptions): lowlight.HighlightAutoResult; + export function registerLanguage(name: string, syntax: Function): void; +} + +declare namespace lowlight { + namespace AST { + namespace Unist { + interface Data { + [index: string]: any; + } + + interface Position { + line: number; + column: number; + offset?: number; + } + + interface Location { + start: Position; + end: Position; + indent?: Array; + } + + export interface Node { + type: string; + data?: Data; + position?: Location; + } + + export interface Parent extends Node { + children: Array; + } + + export interface Text extends Node { + value: string; + } + } + + interface Properties { + [index: string]: any; + } + + export interface Root extends Unist.Parent { + type: 'root'; + } + + export interface Element extends Unist.Parent { + type: 'element'; + tagName: string; + properties: Properties; + } + + export interface Doctype extends Unist.Node { + type: 'doctype'; + name: string; + public?: string; + system?: string; + } + + export interface Comment extends Unist.Text { + type: 'comment'; + } + + export interface Text extends Unist.Text { + type: 'text'; + } + } + + type HastNode = AST.Root | AST.Element | AST.Doctype | AST.Comment | AST.Text; + + interface HighlightOptions { + prefix?: string; + } + + interface HighlightAutoOptions extends HighlightOptions { + subset?: Array; + } + + interface HighlightResult { + relevance: number; + language: string; + value: Array; + } + + interface HighlightAutoResult extends HighlightResult { + secondBest?: HighlightAutoResult; + } +} \ No newline at end of file diff --git a/lowlight/lowlight-tests.ts b/lowlight/lowlight-tests.ts new file mode 100644 index 00000000000000..b9bc0122ae556d --- /dev/null +++ b/lowlight/lowlight-tests.ts @@ -0,0 +1,80 @@ +import { highlight, highlightAuto, registerLanguage } from 'lowlight'; +import * as core from 'lowlight/lib/core'; + +function highlighter(hljs: any): any { + return { + aliases: ['cmake.in'], + case_insensitive: true, + keywords: { + keyword: + 'forall all exists exist only m M i e 1 2 3 4 5 6 7 8 9 0 - + * / \ % ! . , ; : | lim limsup liminf infinity not' + }, + contains: [ + { + className: 'variable', + begin: '(', end: ')' + }, + ] + }; +} + +registerLanguage('math', highlighter); + +console.log(highlight('typescript', +`class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + + public version(): string { + return this.version; + } +} +` +)); + +console.info(highlightAuto( +`class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + + public version(): string { + return this.version; + } +} +` +)); + +core.registerLanguage('math', highlighter); + +console.log(core.highlight('javascript', +`class CPP { + constructor(version) { + this.version = version; + this.year = Number(version.match(/.+\d+$/)); + } + + version(){ + return this.version; + } +} +` +, { prefix: 'core-' })); + + +console.info(core.highlightAuto( +`class CPP { + constructor(version) { + this.version = version; + this.year = Number(version.match(/.+\d+$/)); + } + + version(){ + return this.version; + } +} +` +, { prefix: 'core-', subset: ['purescript', 'javascript', 'typescript', 'coffeescript'] })); \ No newline at end of file diff --git a/lowlight/tsconfig.json b/lowlight/tsconfig.json new file mode 100644 index 00000000000000..6aa905fcab2051 --- /dev/null +++ b/lowlight/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lowlight-tests.ts" + ] +} \ No newline at end of file diff --git a/mapbox-gl/index.d.ts b/mapbox-gl/index.d.ts index 654d3b2439a91a..f8fb9d9b605c46 100644 --- a/mapbox-gl/index.d.ts +++ b/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.24.0 +// Type definitions for Mapbox GL JS v0.26.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -343,28 +343,28 @@ declare namespace mapboxgl { /** * Navigation */ - export class Navigation extends Control { + export class NavigationControl extends Control { constructor(options?: mapboxgl.ControlOptions); } /** * Geolocate */ - export class Geolocate extends Control { + export class GeolocateControl extends Control { constructor(options?: mapboxgl.ControlOptions); } /** * Attribution */ - export class Attribution extends Control { + export class AttributionControl extends Control { constructor(options?: mapboxgl.ControlOptions); } /** * Scale */ - export class Scale extends Control { + export class ScaleControl extends Control { constructor(options?: {position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left', maxWidth?: number, unit?: string}) } @@ -697,6 +697,11 @@ declare namespace mapboxgl { boxZoomBounds: LngLatBounds; } + export class MapDataEvent { + type: string; + dataType: "source" | "style" | "tile"; + } + /** * AnimationOptions */ @@ -741,8 +746,12 @@ declare namespace mapboxgl { * MapEvent */ export interface MapEvent { + resize?: void; webglcontextlost?: {originalEvent: WebGLContextEvent}; webglcontextrestored?: {originalEvent: WebGLContextEvent}; + remove?: void; + dataloading?: {data: mapboxgl.MapDataEvent}; + data?: {data: mapboxgl.MapDataEvent}; render?: void; contextmenu?: {data: mapboxgl.MapMouseEvent}; dblclick?: {data: mapboxgl.MapMouseEvent}; @@ -798,7 +807,8 @@ declare namespace mapboxgl { stops: any[][]; property?: string; base?: number; - type?: "continuous" | "interval" | "categorical"; + type?: "identity" | "exponential" | "interval" | "categorical"; + "colorSpace"?: "rgb" | "lab" | "interval"; } export interface BackgroundLayout { @@ -821,6 +831,8 @@ declare namespace mapboxgl { "fill-translate"?: number[]; "fill-translate-anchor"?: "map" | "viewport"; "fill-pattern"?: "string"; + "fill-extrude-height"?: number; + "fill-extrude-base"?: number; } export interface LineLayout { diff --git a/mapbox-gl/mapbox-gl-0.25.1.d.ts b/mapbox-gl/mapbox-gl-0.25.1.d.ts new file mode 100644 index 00000000000000..2ee8d309498d1b --- /dev/null +++ b/mapbox-gl/mapbox-gl-0.25.1.d.ts @@ -0,0 +1,936 @@ +// Type definitions for Mapbox GL JS v0.24.0 +// Project: https://github.com/mapbox/mapbox-gl-js +// Definitions by: Dominik Bruderer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace mapboxgl { + let accessToken: string; + let version: string; + export function supported(options?: {failIfMajorPerformanceCaveat?: boolean}): boolean; + + /** + * Map + */ + export class Map extends Evented { + constructor(options?: MapboxOptions); + + addControl(control: Control): this; + + addClass(klass: string, options?: mapboxgl.StyleOptions): this; + + removeClass(klass: string, options?: mapboxgl.StyleOptions): this; + + setClasses(klasses: string[], options?: mapboxgl.StyleOptions): this; + + hasClass(klass: string): boolean; + + getClasses(): string[]; + + resize(): this; + + getBounds(): mapboxgl.LngLatBounds; + + setMaxBounds(lnglatbounds?: mapboxgl.LngLatBounds | number[][]): this; + + setMinZoom(minZoom?: number): this; + + setMaxZoom(maxZoom?: number): this; + + project(lnglat: mapboxgl.LngLat | number[]): mapboxgl.Point; + + unproject(point: mapboxgl.Point | number[]): mapboxgl.LngLat; + + queryRenderedFeatures(pointOrBox?: mapboxgl.Point|number[]|mapboxgl.Point[]|number[][], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; + + querySourceFeatures(sourceID: string, parameters: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; + + setStyle(style: mapboxgl.Style | string): this; + + getStyle(): mapboxgl.Style; + + addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + + removeSource(id: string): this; + + getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + + addLayer(layer: mapboxgl.Layer, before?: string): this; + + removeLayer(id: string): this; + + getLayer(id: string): mapboxgl.Layer; + + setFilter(layer: string, filter: any[]): this; + + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; + + getFilter(layer: string): any[]; + + setPaintProperty(layer: string, name: string, value: any, klass?: string): this; + + getPaintProperty(layer: string, name: string, klass?: string): any; + + setLayoutProperty(layer: string, name: string, value: any): this; + + getLayoutProperty(layer: string, name: string, klass?: string): any; + + getContainer(): HTMLElement; + + getCanvasContainer(): HTMLElement; + + getCanvas(): HTMLCanvasElement; + + loaded(): boolean; + + remove(): void; + + onError(): void; + + showTileBoundaries: boolean; + + showCollisionBoxes: boolean; + + repaint: boolean; + + getCenter(): mapboxgl.LngLat; + + setCenter(center: LngLat|number[], eventData?: mapboxgl.EventData): this; + + panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + panTo(lnglat: mapboxgl.LngLat, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; + + getZoom(): number; + + setZoom(zoom: number, eventData?: mapboxgl.EventData): this; + + zoomTo(zoom: number, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + zoomIn(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + zoomOut(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + getBearing(): number; + + setBearing(bearing: number, eventData?: mapboxgl.EventData): this; + + rotateTo(bearing: number, options?: mapboxgl.AnimationOptions, eventData?: EventData): this; + + resetNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + snapToNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + getPitch(): number; + + setPitch(pitch: number, eventData?: EventData): this; + + fitBounds(bounds: mapboxgl.LngLatBounds | number[][], options?: { linear?: boolean, easing?: Function, padding?: number, offset?: Point|number[],maxZoom?: number }): this; + + jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; + + easeTo(options: mapboxgl.CameraOptions | mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; + + stop(): this; + + scrollZoom: ScrollZoomHandler; + + boxZoom: BoxZoomHandler; + + dragRotate: DragRotateHandler; + + dragPan: DragPanHandler; + + keyboard: KeyboardHandler; + + doublClickZoom: DoubleClickZoomHandler; + + touchZoomRotate: TouchZoomRotateHandler; + } + + export interface MapboxOptions { + /** If true, an attribution control will be added to the map. */ + attributionControl?: boolean; + + bearing?: number; + + /** Snap to north threshold in degrees. */ + bearingSnap?: number; + + /** If true, enable the "box zoom" interaction (see BoxZoomHandler) */ + boxZoom?: boolean; + + /** initial map center */ + center?: mapboxgl.LngLat | number[]; + + /** Style class names with which to initialize the map */ + classes?: string[]; + + /** ID of the container element */ + container?: string | Element; + + /** If true, enable the "drag to pan" interaction (see DragPanHandler). */ + dragPan?: boolean; + + /** If true, enable the "drag to rotate" interaction (see DragRotateHandler). */ + dragRotate?: boolean; + + /** If true, enable the "double click to zoom" interaction (see DoubleClickZoomHandler). */ + doubleClickZoom?: boolean; + + /** If true, the map will track and update the page URL according to map position */ + hash?: boolean; + + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ + failIfMayorPerformanceCaveat?: boolean; + + /** If false, no mouse, touch, or keyboard listeners are attached to the map, so it will not respond to input */ + interactive?: boolean; + + /** If true, enable keyboard shortcuts (see KeyboardHandler). */ + keyboard?: boolean; + + /** If set, the map is constrained to the given bounds. */ + maxBounds?: mapboxgl.LngLatBounds | number[][]; + + /** Maximum zoom of the map */ + maxZoom?: number; + + /** Minimum zoom of the map */ + minZoom?: number; + + /** If true, The maps canvas can be exported to a PNG using map.getCanvas().toDataURL();. This is false by default as a performance optimization. */ + preserveDrawingBuffer?: boolean; + + pitch?: number; + + /** If true, enable the "scroll to zoom" interaction */ + scrollZoom?: boolean; + + /** stylesheet location */ + style?: mapboxgl.Style | string; + + /** If true, the map will automatically resize when the browser window resizes */ + trackResize?: boolean; + + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ + touchZoomRotate?: boolean; + + /** Initial zoom level */ + zoom?: number; + } + + /** + * BoxZoomHandler + */ + export class BoxZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * ScrollZoomHandler + */ + export class ScrollZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DragPenHandler + */ + export class DragPanHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DragRotateHandler + */ + export class DragRotateHandler { + constructor(map: mapboxgl.Map, options?: {bearingSnap?: number, pitchWithRotate?: boolean}); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * KeyboardHandler + */ + export class KeyboardHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DoubleClickZoomHandler + */ + export class DoubleClickZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * TouchZoomRotateHandler + */ + export class TouchZoomRotateHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + + disableRotation(): void; + + enableRotation(): void; + } + + /** + * Control + */ + export class Control extends Evented { + addTo(map: mapboxgl.Map): this; + + remove(): this; + } + + /** + * ControlOptions + */ + export interface ControlOptions { + position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; + } + + /** + * Navigation + */ + export class Navigation extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Geolocate + */ + export class Geolocate extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Attribution + */ + export class Attribution extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Scale + */ + export class Scale extends Control { + constructor(options?: {position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left', maxWidth?: number, unit?: string}) + } + + /** + * Popup + */ + export class Popup extends Evented { + constructor(options?: mapboxgl.PopupOptions); + + addTo(map: mapboxgl.Map): this; + + isOpen(): boolean; + + remove(): this; + + getLngLat(): mapboxgl.LngLat; + + setLngLat(lnglat: mapboxgl.LngLat | number[]): this; + + setText(text: string): this; + + setHTML(html: string): this; + + setDOMContent(htmlNode: Node): this; + } + + export interface PopupOptions { + closeButton?: boolean; + + closeOnClick?: boolean; + + anchor?: 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + + offset?: number | Point | number[] | { [key:string]: Point | number[];}; + } + + export interface Style { + bearing?: number; + center?: number[]; + glyphs?: string; + layers?: Layer[]; + metadata?: any; + name?: string; + pitch?: number; + sources?: any; + sprite?: string; + transition?: Transition; + version: number; + zoom?: number; + } + + export interface Transition { + delay?: number; + duration?: number; + } + + export interface Source { + type: "vector" | "raster" | "geojson" | "image" | "video"; + } + + /** + * GeoJSONSource + */ + + export interface GeoJSONSourceRaw extends Source, GeoJSONSourceOptions { + type: "geojson"; + } + + export class GeoJSONSource implements GeoJSONSourceRaw { + type: "geojson"; + + constructor(options?: mapboxgl.GeoJSONSourceOptions); + + setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + } + + export interface GeoJSONSourceOptions { + data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; + + maxzoom?: number; + + buffer?: number; + + tolerance?: number; + + cluster?: number | boolean; + + clusterRadius?: number; + + clusterMaxZoom?: number; + } + + /** + * VideoSource + */ + export class VideoSource implements Source, VideoSourceOptions { + type: "video"; + + constructor(options?: mapboxgl.VideoSourceOptions); + + getVideo(): HTMLVideoElement; + + setCoordinates(coordinates: number[][]): this; + } + + export interface VideoSourceOptions { + urls?: string[]; + + coordinates?: number[][]; + } + + /** + * ImageSource + */ + export class ImageSource implements Source, ImageSourceOptions { + type: "image"; + + constructor(options?: mapboxgl.ImageSourceOptions); + + setCoordinates(coordinates: number[][]): this; + } + + export interface ImageSourceOptions { + url?: string; + + coordinates?: number[][]; + } + + interface VectorSource extends Source { + type: "vector"; + url?: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + } + + interface RasterSource extends Source { + type: "raster"; + url: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + } + + /** + * LngLat + */ + export class LngLat { + lng: number; + lat: number; + + constructor(lng: number, lat: number); + + /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ + wrap(): mapboxgl.LngLat; + + /** Return a LngLat as an array */ + toArray(): number[]; + + /** Return a LngLat as a string */ + toString(): string; + + static convert(input: number[]|mapboxgl.LngLat): mapboxgl.LngLat; + } + + /** + * LngLatBounds + */ + export class LngLatBounds { + sw: LngLat | number[]; + ne: LngLat | number[]; + constructor(sw?: LngLat, ne?: LngLat); + + /** Extend the bounds to include a given LngLat or LngLatBounds. */ + extend(obj: mapboxgl.LngLat | mapboxgl.LngLatBounds): this; + + /** Get the point equidistant from this box's corners */ + getCenter(): mapboxgl.LngLat; + + /** Get southwest corner */ + getSouthWest(): mapboxgl.LngLat; + + /** Get northeast corner */ + getNorthEast(): mapboxgl.LngLat; + + /** Get northwest corner */ + getNorthWest(): mapboxgl.LngLat; + + /** Get southeast corner */ + getSouthEast(): mapboxgl.LngLat; + + /** Get west edge longitude */ + getWest(): number; + + /** Get south edge latitude */ + getSouth(): number; + + /** Get east edge longitude */ + getEast(): number; + + /** Get north edge latitude */ + getNorth(): number; + + /** Returns a LngLatBounds as an array */ + toArray(): number[][]; + + /** Return a LngLatBounds as a string */ + toString(): string; + + /** Convert an array to a LngLatBounds object, or return an existing LngLatBounds object unchanged. */ + static convert(input: mapboxgl.LngLatBounds | number[] | number[][]): mapboxgl.LngLatBounds; + } + + /** + * Point + */ + // Todo: Pull out class to seperate definition for Module "point-geometry" + export class Point { + constructor(options?: Object); + + clone(): Point; + + add(p: number): Point; + + sub(p: number): Point; + + mult(k: number): Point; + + div(k: number): Point; + + rotate(a: number): Point; + + matMult(m: number): Point; + + unit(): Point; + + perp(): Point; + + round(): Point; + + mag(): number; + + equals(): boolean; + + dist(): number; + + distSqr(): number; + + angle(): number; + + angleTo(): number; + + angleWidth(): number; + + angleWidthSep(): number; + } + + export class Marker { + constructor(element?: HTMLElement, options?: { offset?: Point | number[] }); + + addTo(map: Map): this; + + remove(): this; + + getLngLat(): LngLat; + + setLngLat(lngLat: LngLat | number[]): this; + + setPopup(popup?: Popup): this; + + getPopup(): Popup; + + togglePopup(): this; + } + + /** + * Evented + */ + export class Evented { + on(type: string, listener: Function): this; + + off(type?: string | any, listener?: Function): this; + + once(type: string, listener: Function): this; + + fire(type: string, data?: mapboxgl.EventData | Object): this; + + listens(type: string): boolean; + } + + /** + * StyleOptions + */ + export interface StyleOptions { + transition?: boolean; + } + + /** + * EventData + */ + export class EventData { + type: string; + target: Map; + originalEvent: Event; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapMouseEvent { + type: string; + target: Map; + originalEvent: MouseEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapTouchEvent { + type: string; + target: Map; + originalEvent: TouchEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + points: Point[]; + lngLats: LngLat[]; + } + + export class MapBoxZoomEvent { + originalEvent: MouseEvent; + boxZoomBounds: LngLatBounds; + } + + /** + * AnimationOptions + */ + export interface AnimationOptions { + /** Number in milliseconds */ + duration?: number; + easing?: Function; + /** point, origin of movement relative to map center */ + offset?: Point | number[]; + /** When set to false, no animation happens */ + animate?: boolean; + } + + /** + * CameraOptions + */ + export interface CameraOptions { + /** Map center */ + center?: mapboxgl.LngLat | number[]; + /** Map zoom level */ + zoom?: number; + /** Map rotation bearing in degrees counter-clockwise from north */ + bearing?: number; + /** Map angle in degrees at which the camera is looking at the ground */ + pitch?: number; + /** If zooming, the zoom center (defaults to map center) */ + around?: mapboxgl.LngLat | number[]; + } + + /** + * FlyToOptions + */ + export interface FlyToOptions extends AnimationOptions, CameraOptions { + curve?: number; + minZoom?: number; + speed?: number; + screenSpeed?: number; + easing?: Function; + } + + /** + * MapEvent + */ + export interface MapEvent { + webglcontextlost?: {originalEvent: WebGLContextEvent}; + webglcontextrestored?: {originalEvent: WebGLContextEvent}; + render?: void; + contextmenu?: {data: mapboxgl.MapMouseEvent}; + dblclick?: {data: mapboxgl.MapMouseEvent}; + click?: {data: mapboxgl.MapMouseEvent}; + touchcancel?: {data: mapboxgl.MapTouchEvent}; + touchmove?: {data: mapboxgl.MapTouchEvent}; + touchend?: {data: mapboxgl.MapTouchEvent}; + touchstart?: {data: mapboxgl.MapTouchEvent}; + mousemove?: {data: mapboxgl.MapMouseEvent}; + mouseup?: {data: mapboxgl.MapMouseEvent}; + mousedown?: {data: mapboxgl.MapMouseEvent}; + moveend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + move?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + movestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + mouseout?:{data: mapboxgl.MapMouseEvent}; + load?: void; + zoomend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + zoom?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + zoomstart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + boxzoomcancel?: {data: mapboxgl.MapBoxZoomEvent}; + boxzoomstart?: {data: mapboxgl.MapBoxZoomEvent}; + boxzoomend?: {data: mapboxgl.MapBoxZoomEvent}; + rotate?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + rotatestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + rotateend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + drag?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + dragend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + pitch?: {data: mapboxgl.EventData}; + } + + export interface Layer { + id: string; + type?: "fill" | "line" | "symbol" | "circle" | "raster" | "background" | string; //TODO: Ideally we wouldn't accept string here, just these specific strings + + metadata?: any; + ref?: string; + + source?: string; + + "source-layer"?: string; + + minzoom?: number; + maxzoom?: number; + + interactive?: boolean; + + filter?: any[]; + layout?: BackgroundLayout | FillLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout; + paint?: BackgroundPaint | FillPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint; + } + + export interface StyleFunction { + stops: any[][]; + property?: string; + base?: number; + type?: "continuous" | "interval" | "categorical"; + } + + export interface BackgroundLayout { + visibility?: "visible" | "none"; + } + export interface BackgroundPaint { + "background-color"?: string; + "background-pattern"?: string; + "background-opacity"?: number; + } + + export interface FillLayout { + visibility?: "visible" | "none"; + } + export interface FillPaint { + "fill-antialias"?: boolean; + "fill-opacity"?: number | StyleFunction; + "fill-color"?: string | StyleFunction; + "fill-outline-color": string | StyleFunction; + "fill-translate"?: number[]; + "fill-translate-anchor"?: "map" | "viewport"; + "fill-pattern"?: "string"; + } + + export interface LineLayout { + visibility?: "visible" | "none"; + + "line-cap"?: "butt" | "round" | "square"; + "line-join"?: "bevel" | "round" | "miter"; + "line-miter-limit"?: number; + "line-round-limit"?: number; + } + export interface LinePaint { + "line-opacity"?: number; + "line-color"?: string| StyleFunction; + "line-translate"?: number[]; + "line-translate-anchor"?: "map" | "viewport"; + "line-width"?: number; + "line-gap-width"?: number; + "line-offset"?: number; + "line-blur"?: number; + "line-dasharray"?: number[]; + "line-dasharray-transition"?: Transition; + "line-pattern"?: string; + } + + export interface SymbolLayout { + visibility?: "visible" | "none"; + + "symbol-placement"?: "point" | "line"; + "symbol-spacing"?: number; + "symbol-avoid-edges"?: boolean; + "icon-allow-overlap"?: boolean; + "icon-ignore-placement"?: boolean; + "icon-optional"?: boolean; + "icon-rotation-alignment"?: "map" | "viewport" | "auto"; + "icon-size"?: number; + "icon-text-fit"?: "none" | "both" | "width" | "height"; + "icon-text-fit-padding"?: number[]; + "icon-image"?: string; + "icon-rotate"?: number | StyleFunction; + "icon-padding"?: number; + "icon-keep-upright"?: boolean; + "icon-offset"?: number[]; + "text-pitch-alignment"?: "map" | "viewport" | "auto"; + "text-rotation-alignment"?: "map" | "viewport" | "auto"; + "text-field"?: string; + "text-font"?: string | string[]; + "text-size"?: number; + "text-max-width"?: number; + "text-line-height"?: number; + "text-letter-spacing"?: number; + "text-justify"?: "left" | "center" | "right"; + "text-anchor"?: "center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right"; + "text-max-angle"?: number; + "text-rotate"?: number; + "text-padding"?: number; + "text-keep-upright"?: boolean; + "text-transform"?: "none" | "uppercase" | "lowercase"; + "text-offset"?: number[]; + "text-allow-overlap"?: boolean; + "text-ignore-placement"?: boolean; + "text-optional"?: boolean; + + } + export interface SymbolPaint { + "icon-opacity"?: number; + "icon-color"?: string; + "icon-halo-color"?: string; + "icon-halo-width"?: number; + "icon-halo-blur"?: number; + "icon-translate"?: number[]; + "icon-translate-anchor"?: "map" | "viewport"; + "text-opacity"?: number; + "text-color"?: "string"; + "text-halo-color"?: "string"; + "text-halo-width"?: number; + "text-halo-blur"?: number; + "text-translate"?: number[]; + "text-translate-anchor"?: "map" | "viewport"; + } + + export interface RasterLayout { + visibility?: "visible" | "none"; + } + + export interface RasterPaint { + "raster-opacity"?: number; + "raster-hue-rotate"?: number; + "raster-brightness-min"?: number; + "raster-brightness-max"?: number; + "raster-saturation"?: number; + "raster-contrast"?: number; + "raster-fade-duration"?: number; + } + + export interface CircleLayout { + visibility?: "visible" | "none"; + } + + export interface CirclePaint { + "circle-radius"?: number | StyleFunction; + "circle-radius-transition"?: Transition; + "circle-color"?: number | StyleFunction; + "circle-blur"?: number | StyleFunction; + "circle-opacity"?: number | StyleFunction; + "circle-translate"?: number[]; + "circle-translate-anchor"?: "map" | "viewport"; + "circle-pitch-scale"?: "map" | "viewport"; + } +} + +declare module 'mapbox-gl' { + export = mapboxgl; +} diff --git a/mocha/index.d.ts b/mocha/index.d.ts index 5304f9333a3010..e512984ba4d124 100644 --- a/mocha/index.d.ts +++ b/mocha/index.d.ts @@ -42,6 +42,9 @@ declare var xit: Mocha.ITestDefinition; declare var test: Mocha.ITestDefinition; declare var specify: Mocha.ITestDefinition; +// Used with the --delay flag; see https://mochajs.org/#hooks +declare function run(): void; + interface MochaDone { (error?: any): any; } diff --git a/nes/nes.d.ts b/nes/nes.d.ts index f6159be9b0bae2..6ebc9ee1c08aa4 100644 --- a/nes/nes.d.ts +++ b/nes/nes.d.ts @@ -61,7 +61,7 @@ declare module 'nes' { user?: any; } - export interface ServerEachSokcetOptions { + export interface ServerEachSocketOptions { subscription?: string; user?: any; } @@ -70,7 +70,7 @@ declare module 'nes' { broadcast(message: any, options?: ServerBroadcastOptions): void; subscription(path: string, options?: ServerSubscriptionOptions): void; publish(path: string, message: any, options?: ServerPublishOptions): void; - eachSocket(each: (socket: Socket) => void, options?: ServerEachSokcetOptions): void; + eachSocket(each: (socket: Socket) => void, options?: ServerEachSocketOptions): void; } export class Request extends Hapi.Request { @@ -82,7 +82,7 @@ declare module 'nes' { timeout?: number | boolean; } - export interface ClientConnnectOptions { + export interface ClientConnectOptions { auth?: any; delay?: number; maxDelay?: number; @@ -107,7 +107,7 @@ declare module 'nes' { onConnect: () => void; onDisconnect: () => void; onUpdate: (message: any) => void; - connect(options: ClientConnnectOptions, callback: (err?: any) => void): void; + connect(options: ClientConnectOptions, callback: (err?: any) => void): void; connect(callback: (err?: any) => void): void; disconnect(): void; id: any; @@ -123,7 +123,7 @@ declare module 'nes' { declare module 'nes/client' { export { Client, - ClientConnnectOptions, + ClientConnectOptions, ClientRequestOptions, ClientSubscribeFlags } from 'nes'; diff --git a/noble/index.d.ts b/noble/index.d.ts index 4a9720ba5e482f..4e293993f70867 100644 --- a/noble/index.d.ts +++ b/noble/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for noble // Project: https://github.com/sandeepmistry/noble -// Definitions by: Seon-Wook Park , Hans Bakker +// Definitions by: Seon-Wook Park , Hans Bakker , Shantanu Bhadoria // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -20,11 +20,15 @@ export declare function on(event: "scanStop", listener: () => void): events.Even export declare function on(event: "discover", listener: (peripheral: Peripheral) => void): events.EventEmitter; export declare class Peripheral extends events.EventEmitter { - uuid: string; + id: string; + uuid: string; + address: string; + addressType: string; + connectable: boolean; advertisement: Advertisement; - rssi: number; - services: Service[]; - state: string; + rssi: number; + services: Service[]; + state: string; connect(callback?: (error: string) => void): void; disconnect(callback?: () => void): void; diff --git a/node/index.d.ts b/node/index.d.ts index c9f672ec9fa212..9bb33c55c8229d 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -67,7 +67,7 @@ interface NodeRequire extends NodeRequireFunction { resolve(id: string): string; cache: any; extensions: any; - main: any; + main: NodeModule; } declare var require: NodeRequire; @@ -78,8 +78,8 @@ interface NodeModule { id: string; filename: string; loaded: boolean; - parent: any; - children: any[]; + parent: NodeModule; + children: NodeModule[]; } declare var module: NodeModule; @@ -253,7 +253,7 @@ declare namespace NodeJS { } export interface ErrnoException extends Error { - errno?: string; + errno?: number; code?: string; path?: string; syscall?: string; @@ -392,6 +392,7 @@ declare namespace NodeJS { title: string; arch: string; platform: string; + mainModule?: NodeModule; memoryUsage(): MemoryUsage; nextTick(callback: Function, ...args: any[]): void; umask(mask?: number): number; @@ -1342,7 +1343,37 @@ declare module "repl" { export interface REPLServer extends readline.ReadLine { defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; - displayPrompt(preserveCursor?: boolean): void + displayPrompt(preserveCursor?: boolean): void; + + /** + * events.EventEmitter + * 1. exit + * 2. reset + **/ + + addListener(event: string, listener: Function): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: Function): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: any): boolean; + + on(event: string, listener: Function): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: Function): this; + + once(event: string, listener: Function): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: Function): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: Function): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: Function): this; } export function start(options: ReplOptions): REPLServer; @@ -1368,6 +1399,71 @@ declare module "readline" { resume(): ReadLine; close(): void; write(data: string | Buffer, key?: Key): void; + + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + **/ + + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: any) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: any): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: any) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: any) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: any) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: any) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; } export interface Completer { @@ -1429,6 +1525,7 @@ declare module "vm" { declare module "child_process" { import * as events from "events"; import * as stream from "stream"; + import * as net from "net"; export interface ChildProcess extends events.EventEmitter { stdin: stream.Writable; @@ -1442,6 +1539,57 @@ declare module "child_process" { disconnect(): void; unref(): void; ref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. disconnet + * 3. error + * 4. exit + * 5. message + **/ + + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnet", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnet"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnet", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnet", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnet", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnet", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; } export interface SpawnOptions { @@ -1802,9 +1950,9 @@ declare module "net" { listen(port: number, listeningListener?: Function): Server; listen(path: string, backlog?: number, listeningListener?: Function): Server; listen(path: string, listeningListener?: Function): Server; + listen(options: ListenOptions, listeningListener?: Function): Server; listen(handle: any, backlog?: number, listeningListener?: Function): Server; listen(handle: any, listeningListener?: Function): Server; - listen(options: ListenOptions, listeningListener?: Function): Server; close(callback?: Function): Server; address(): { port: number; family: string; address: string; }; getConnections(cb: (error: Error, count: number) => void): void; diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 4040173e4176b5..5f229fc3f6d4e2 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -24,6 +24,19 @@ import * as string_decoder from "string_decoder"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; +////////////////////////////////////////////////////////// +/// Global Tests : https://nodejs.org/api/global.html /// +////////////////////////////////////////////////////////// +namespace global_tests { + { + let x: NodeModule; + let y: NodeModule; + x.children.push(y); + x.parent = require.main; + require.main = y; + } +} + ////////////////////////////////////////////////////////// /// Assert Tests : https://nodejs.org/api/assert.html /// ////////////////////////////////////////////////////////// @@ -928,6 +941,10 @@ namespace process_tests { var _p: NodeJS.Process = process; _p = p; } + { + var module: NodeModule; + module = process.mainModule; + } } /////////////////////////////////////////////////////////// diff --git a/node/node-4.d.ts b/node/node-4.d.ts index 663d6ea59c4aed..0d6bbe0159725e 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -52,7 +52,7 @@ interface NodeRequire extends NodeRequireFunction { resolve(id:string): string; cache: any; extensions: any; - main: any; + main: NodeModule; } declare var require: NodeRequire; @@ -63,8 +63,8 @@ interface NodeModule { id: string; filename: string; loaded: boolean; - parent: any; - children: any[]; + parent: NodeModule; + children: NodeModule[]; } declare var module: NodeModule; @@ -339,6 +339,7 @@ declare namespace NodeJS { title: string; arch: string; platform: string; + mainModule?: NodeModule; memoryUsage(): MemoryUsage; nextTick(callback: Function): void; umask(mask?: number): number; diff --git a/node/node-tests.ts b/node/node-tests.ts index 4083c826ae0526..0f85716c6c2a1c 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -22,10 +22,24 @@ import * as console2 from "console"; import * as string_decoder from "string_decoder"; import * as stream from "stream"; import * as timers from "timers"; +import * as repl from "repl"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; +////////////////////////////////////////////////////////// +/// Global Tests : https://nodejs.org/api/global.html /// +////////////////////////////////////////////////////////// +namespace global_tests { + { + let x: NodeModule; + let y: NodeModule; + x.children.push(y); + x.parent = require.main; + require.main = y; + } +} + ////////////////////////////////////////////////////////// /// Assert Tests : https://nodejs.org/api/assert.html /// ////////////////////////////////////////////////////////// @@ -165,7 +179,7 @@ namespace fs_tests { } { - var errno: string; + var errno: number; fs.readFile('testfile', (err, data) => { if (err && err.errno) { errno = err.errno; @@ -1206,6 +1220,69 @@ namespace readline_tests { readline.clearScreenDown(stream); } + + { + let _rl: readline.ReadLine; + let _boolean: boolean; + + _rl = _rl.addListener("close", () => { }); + _rl = _rl.addListener("line", (input) => { + let _input: any = input; + }) + _rl = _rl.addListener("pause", () => { }); + _rl = _rl.addListener("resume", () => { }); + _rl = _rl.addListener("SIGCONT", () => { }); + _rl = _rl.addListener("SIGINT", () => { }); + _rl = _rl.addListener("SIGTSTP", () => { }); + + _boolean = _rl.emit("close", () => { }); + _boolean = _rl.emit("line", () => { }); + _boolean = _rl.emit("pause", () => { }); + _boolean = _rl.emit("resume", () => { }); + _boolean = _rl.emit("SIGCONT", () => { }); + _boolean = _rl.emit("SIGINT", () => { }); + _boolean = _rl.emit("SIGTSTP", () => { }); + + _rl = _rl.on("close", () => { }); + _rl = _rl.on("line", (input) => { + let _input: any = input; + }) + _rl = _rl.on("pause", () => { }); + _rl = _rl.on("resume", () => { }); + _rl = _rl.on("SIGCONT", () => { }); + _rl = _rl.on("SIGINT", () => { }); + _rl = _rl.on("SIGTSTP", () => { }); + + _rl = _rl.once("close", () => { }); + _rl = _rl.once("line", (input) => { + let _input: any = input; + }) + _rl = _rl.once("pause", () => { }); + _rl = _rl.once("resume", () => { }); + _rl = _rl.once("SIGCONT", () => { }); + _rl = _rl.once("SIGINT", () => { }); + _rl = _rl.once("SIGTSTP", () => { }); + + _rl = _rl.prependListener("close", () => { }); + _rl = _rl.prependListener("line", (input) => { + let _input: any = input; + }) + _rl = _rl.prependListener("pause", () => { }); + _rl = _rl.prependListener("resume", () => { }); + _rl = _rl.prependListener("SIGCONT", () => { }); + _rl = _rl.prependListener("SIGINT", () => { }); + _rl = _rl.prependListener("SIGTSTP", () => { }); + + _rl = _rl.prependOnceListener("close", () => { }); + _rl = _rl.prependOnceListener("line", (input) => { + let _input: any = input; + }) + _rl = _rl.prependOnceListener("pause", () => { }); + _rl = _rl.prependOnceListener("resume", () => { }); + _rl = _rl.prependOnceListener("SIGCONT", () => { }); + _rl = _rl.prependOnceListener("SIGINT", () => { }); + _rl = _rl.prependOnceListener("SIGTSTP", () => { }); + } } //////////////////////////////////////////////////// @@ -1232,6 +1309,102 @@ namespace child_process_tests { childProcess.exec("echo test"); childProcess.spawnSync("echo test"); } + + { + let _cp: childProcess.ChildProcess; + let _boolean: boolean; + + _cp = _cp.addListener("close", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.addListener("disconnet", () => { }); + _cp = _cp.addListener("error", (err) => { + let _err: Error = err; + }) + _cp = _cp.addListener("exit", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.addListener("message", (message, sendHandle) => { + let _message: any = message; + let _sendHandle: net.Socket | net.Server = sendHandle; + }) + + _boolean = _cp.emit("close", () => { }); + _boolean = _cp.emit("disconnet", () => { }); + _boolean = _cp.emit("error", () => { }); + _boolean = _cp.emit("exit", () => { }); + _boolean = _cp.emit("message", () => { }); + + _cp = _cp.on("close", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.on("disconnet", () => { }); + _cp = _cp.on("error", (err) => { + let _err: Error = err; + }) + _cp = _cp.on("exit", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.on("message", (message, sendHandle) => { + let _message: any = message; + let _sendHandle: net.Socket | net.Server = sendHandle; + }) + + _cp = _cp.once("close", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.once("disconnet", () => { }); + _cp = _cp.once("error", (err) => { + let _err: Error = err; + }) + _cp = _cp.once("exit", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.once("message", (message, sendHandle) => { + let _message: any = message; + let _sendHandle: net.Socket | net.Server = sendHandle; + }) + + _cp = _cp.prependListener("close", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.prependListener("disconnet", () => { }); + _cp = _cp.prependListener("error", (err) => { + let _err: Error = err; + }) + _cp = _cp.prependListener("exit", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.prependListener("message", (message, sendHandle) => { + let _message: any = message; + let _sendHandle: net.Socket | net.Server = sendHandle; + }) + + _cp = _cp.prependOnceListener("close", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.prependOnceListener("disconnet", () => { }); + _cp = _cp.prependOnceListener("error", (err) => { + let _err: Error = err; + }) + _cp = _cp.prependOnceListener("exit", (code, signal) => { + let _code: number = code; + let _signal: string = signal; + }) + _cp = _cp.prependOnceListener("message", (message, sendHandle) => { + let _message: any = message; + let _sendHandle: net.Socket | net.Server = sendHandle; + }) + } } ////////////////////////////////////////////////////////////////////// @@ -1400,6 +1573,10 @@ namespace process_tests { { assert(process.argv[0] === process.argv0); } + { + var module: NodeModule; + module = process.mainModule; + } } /////////////////////////////////////////////////////////// @@ -1651,6 +1828,36 @@ namespace net_tests { } +///////////////////////////////////////////////////// +/// repl Tests : https://nodejs.org/api/repl.html /// +///////////////////////////////////////////////////// + +namespace repl_tests { + { + let _server: repl.REPLServer; + let _boolean: boolean; + let _ctx: any; + + _server = _server.addListener("exit", () => { }); + _server = _server.addListener("reset", () => { }); + + _boolean = _server.emit("exit", () => { }); + _boolean = _server.emit("reset", _ctx); + + _server = _server.on("exit", () => { }); + _server = _server.on("reset", () => { }); + + _server = _server.once("exit", () => { }); + _server = _server.once("reset", () => { }); + + _server = _server.prependListener("exit", () => { }); + _server = _server.prependListener("reset", () => { }); + + _server = _server.prependOnceListener("exit", () => { }); + _server = _server.prependOnceListener("reset", () => { }); + } +} + /***************************************************************************** * * * The following tests are the modules not mentioned in document but existed * diff --git a/npm-debug.log.3539137130 b/npm-debug.log.3539137130 new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/paper/index.d.ts b/paper/index.d.ts new file mode 100644 index 00000000000000..e463d730c02875 --- /dev/null +++ b/paper/index.d.ts @@ -0,0 +1,4008 @@ +// Type definitions for Paper.js v0.9.22 +// Project: http://paperjs.org/ +// Definitions by: Clark Stevenson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'paper' { + + /** + * The version of Paper.js, as a string. + */ + export var version: string; + + /** + * Gives access to paper's configurable settings. + */ + export var settings: { + + applyMatrix: boolean; + handleSize: number; + hitTolerance: number; + + }; + + /** + * The currently active project. + */ + export var project: Project; + + /** + * The list of all open projects within the current Paper.js context. + */ + export var projects: Project[]; + + /** + * The reference to the active project's view. + * Read Only. + */ + export var view: View; + + /** + * The reference to the active tool. + */ + export var tool: Tool; + + /** + * The list of available tools. + */ + export var tools: Tool[]; + + /** + * Injects the paper scope into any other given scope. Can be used for examle to inject the currently active PaperScope into the window's global scope, to emulate PaperScript-style globally accessible Paper classes and objects + * Please note: Using this method may override native constructors (e.g. Path, RGBColor). This may cause problems when using Paper.js in conjunction with other libraries that rely on these constructors. Keep the library scoped if you encounter issues caused by this. + * @param scope - + */ + export function install(scope: any): void; + + /** + * Sets up an empty project for us. If a canvas is provided, it also creates a View for it, both linked to this scope. + * @param element - the HTML canvas element this scope should be associated with, or an ID string by which to find the element. + */ + export function setup(canvas: HTMLCanvasElement | string): void; + + /** + * Activates this PaperScope, so all newly created items will be placed in its active project. + */ + export function activate(): void; + + /** + * An affine transform performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines. + * Such a coordinate transformation can be represented by a 3 row by 3 column matrix with an implied last row of [ 0 0 1 ]. This matrix transforms source coordinates (x,y) into destination coordinates (x',y') by considering them to be a column vector and multiplying the coordinate vector by the matrix according to the following process: + * This class is optimized for speed and minimizes calculations based on its knowledge of the underlying matrix (as opposed to say simply performing matrix multiplication). + */ + export class Matrix { + + /** + * Creates a 2D affine transform. + * @param a - the a property of the transform + * @param c - the c property of the transform + * @param b - the b property of the transform + * @param d - the d property of the transform + * @param tx - the tx property of the transform + * @param ty - the ty property of the transform + */ + constructor(a: number, c: number, b: number, d: number, tx: number, ty: number); + + /** + * The value that affects the transformation along the x axis when scaling or rotating, positioned at (0, 0) in the transformation matrix. + */ + a: number; + + /** + * The value that affects the transformation along the y axis when rotating or skewing, positioned at (1, 0) in the transformation matrix. + */ + c: number; + + /** + * The value that affects the transformation along the x axis when rotating or skewing, positioned at (0, 1) in the transformation matrix. + */ + b: number; + + /** + * The value that affects the transformation along the y axis when scaling or rotating, positioned at (1, 1) in the transformation matrix. + */ + d: number; + + /** + * The distance by which to translate along the x axis, positioned at (2, 0) in the transformation matrix. + */ + tx: number; + + /** + * The distance by which to translate along the y axis, positioned at (2, 1) in the transformation matrix. + */ + ty: number; + + /** + * The transform values as an array, in the same sequence as they are passed to initialize(a, c,b,d,tx,ty). + * Read only. + */ + values: number; + + /** + * The translation of the matrix as a vector. + * Read only. + */ + translation: Point; + + /** + * The scaling values of the matrix, if it can be decomposed. + * Read only. + */ + scaling: Point; + + /** + * The rotation angle of the matrix, if it can be decomposed. + * Read only. + */ + rotation: number; + + /** + * Sets this transform to the matrix specified by the 6 values. + * @param a - the a property of the transform + * @param c - the c property of the transform + * @param b - the b property of the transform + * @param d - the d property of the transform + * @param tx - the tx property of the transform + * @param ty - the ty property of the transform + */ + set(a: number, c: number, b: number, d: number, tx: number, ty: number): Matrix; + + /** + * Returns a copy of this transform + */ + clone(): Matrix; + + /** + * Checks whether the two matrices describe the same transformation. + * @param matrix - the matrix to compare this matrix to + */ + equals(matrix: Matrix): boolean; + + /** + * returns a string representation of this transform + */ + toString(): string; + + /** + * Resets the matrix by setting its values to the ones of the identity matrix that results in no transformation. + */ + reset(): void; + + /** + * Attempts to apply the matrix to the content of item that it belongs to, meaning its transformation is baked into the item's content or children. + * @param recursively - controls whether to apply transformations recursively on children + */ + apply(): boolean; + + /** + * Concatenates this transform with a translate transformation. + * @param point - the vector to translate by + */ + translate(point: Point): Matrix; + + /** + * Concatenates this transform with a translate transformation. + * @param dx - the distance to translate in the x direction + * @param dy - the distance to translate in the y direction + */ + translate(dx: number, dy: number): Matrix; + + /** + * Concatenates this transform with a scaling transformation. + * @param scale - the scaling factor + * @param center [optional] - the center for the scaling transformation + */ + scale(scale: number, center?: Point): Matrix; + + /** + * Concatenates this transform with a scaling transformation. + * @param hor - the horizontal scaling factor + * @param ver - the vertical scaling factor + * @param center [optional] - the center for the scaling transformation + */ + scale(hor: number, ver: number, center?: Point): Matrix; + + /** + * Concatenates this transform with a rotation transformation around an anchor point. + * @param angle - the angle of rotation measured in degrees + * @param center - the anchor point to rotate around + */ + rotate(angle: number, center: Point): Matrix; + + /** + * Concatenates this transform with a rotation transformation around an anchor point. + * @param angle - the angle of rotation measured in degrees + * @param x - the x coordinate of the anchor point + * @param y - the y coordinate of the anchor point + */ + rotate(angle: number, x: number, y: number): Matrix; + + /** + * Concatenates this transform with a shear transformation. + * @param shear - the shear factor in x and y direction + * @param center [optional] - the center for the shear transformation + */ + shear(shear: Point, center?: Point): Matrix; + + /** + * Concatenates this transform with a shear transformation. + * @param hor - the horizontal shear factor + * @param ver - the vertical shear factor + * @param center [optional] - the center for the shear transformation + */ + shear(hor: number, ver: number, center?: Point): Matrix; + + /** + * Concatenates this transform with a skew transformation. + * @param skew - the skew angles in x and y direction in degrees + * @param center [optional] - the center for the skew transformation + */ + skew(skew: Point, center?: Point): Matrix; + + /** + * Concatenates this transform with a skew transformation. + * @param hor - the horizontal skew angle in degrees + * @param ver - the vertical skew angle in degrees + * @param center [optional] - the center for the skew transformation + */ + skew(hor: number, ver: number, center?: Point): Matrix; + + /** + * Concatenates the given affine transform to this transform. + * @param mx - the transform to concatenate + */ + concatenate(mx: Matrix): Matrix; + + /** + * Pre-concatenates the given affine transform to this transform. + * @param mx - the transform to preconcatenate + */ + preConcatenate(mx: Matrix): Matrix; + + /** + * Returns a new instance of the result of the concatenation of the given affine transform with this transform. + * @param mx - the transform to concatenate + */ + chain(mx: Matrix): Matrix; + + /** + * Returns whether this transform is the identity transform + */ + isIdentity(): boolean; + + /** + * Returns whether the transform is invertible. A transform is not invertible if the determinant is 0 or any value is non-finite or NaN. + */ + isInvertible(): boolean; + + /** + * Checks whether the matrix is singular or not. Singular matrices cannot be inverted. + */ + isSingular(): boolean; + + /** + * Transforms a point and returns the result. + * @param point - the point to be transformed + */ + transform(point: Point): Matrix; + + /** + * Transforms an array of coordinates by this matrix and stores the results into the destination array, which is also returned. + * @param src - the array containing the source points as x, y value pairs + * @param dst - the array into which to store the transformed point pairs + * @param count - the number of points to transform + */ + transform(src: number[], dst: number[], count: number): number[]; + + /** + * Inverse transforms a point and returns the result. + * @param point - the point to be transformed + */ + inverseTransform(point: Point): Matrix; + + /** + * Attempts to decompose the affine transformation described by this matrix into scaling, rotation and shearing, and returns an object with these properties if it succeeded, null otherwise. + */ + decompose(): any; + + /** + * Creates the inversion of the transformation of the matrix and returns it as a new insteance. If the matrix is not invertible (in which case isSingular() returns true), null is returned. + */ + inverted(): Matrix; + + /** + * Applies this matrix to the specified Canvas Context. + * @param ctx - + */ + applyToContext(ctx: CanvasRenderingContext2D): void; + + } + /** + * The Point object represents a point in the two dimensional space of the Paper.js project. It is also used to represent two dimensional vector objects. + */ + export class Point { + + /** + * Returns a new point object with the smallest x and y of the supplied points. + * @param point1 - + * @param point2 - + */ + static min(point1: Point, point2: Point): Point; + + /** + * Returns a new point object with the largest x and y of the supplied points. + * @param point1 - + * @param point2 - + */ + static max(point1: Point, point2: Point): Point; + + /** + * Returns a point object with random x and y values between 0 and 1. + */ + static random(): Point; + + /** + * Creates a Point object with the given x and y coordinates. + * @param x - the x coordinate + * @param y - the y coordinate + */ + constructor(x: number, y: number); + + /** + * Creates a Point object using the numbers in the given array as coordinates. + * @param array - an array of numbers to use as coordinates + */ + constructor(values: number[]); + + /** + * Creates a Point object using the properties in the given object. + * @param object - the object describing the point's properties + */ + constructor(object: any); + + /** + * Creates a Point object using the width and height values of the given Size object. + * @param size - the size width and height to use + */ + constructor(size: Size); + + /** + * Creates a Point object using the coordinates of the given Point object. + * @param point - the point to copy + */ + constructor(point: Point); + + /** + * The x coordinate of the point + */ + x: number; + + /** + * The y coordinate of the point + */ + y: number; + + /** + * The length of the vector that is represented by this point's coordinates. + * Each point can be interpreted as a vector that points from the origin (x = 0, y = 0) to the point's location. + * Setting the length changes the location but keeps the vector's angle. + */ + length: number; + + /** + * The vector's angle in degrees, measured from the x-axis to the vector. + */ + angle: number; + + /** + * The vector's angle in radians, measured from the x-axis to the vector. + */ + angleInRadians: number; + + /** + * The quadrant of the angle of the point. + * Angles between 0 and 90 degrees are in quadrant 1. Angles between 90 and 180 degrees are in quadrant 2, angles between 180 and 270 degrees are in quadrant 3 and angles between 270 and 360 degrees are in quadrant 4. + * Read only. + */ + quadrant: number; + + /** + * This property is only present if the point is an anchor or control point of a Segment or a Curve. In this case, it returns true it is selected, false otherwise + */ + selected: boolean; + + /** + * Checks whether the coordinates of the point are equal to that of the supplied point. + * @param point - the point to check against + */ + equals(point: Point): boolean; + + /** + * Returns a copy of the point. + */ + clone(): Point; + + /** + * a string representation of the point + */ + toString(): string; + + /** + * Returns the smaller angle between two vectors. The angle is unsigned, no information about rotational direction is given. + * @param point - + */ + getAngle(Point: Point): number; + + /** + * Returns the smaller angle between two vectors in radians. The angle is unsigned, no information about rotational direction is given. + * @param point: Point + */ + getAngleInRadians(point: Point): number; + + /** + * Returns the angle between two vectors. The angle is directional and signed, giving information about the rotational direction. + * Read more about angle units and orientation in the description of the angle property. + * @param point - + */ + getDirectedAngle(point: Point): number; + + /** + * Returns the distance between the point and another point. + * @param point - + * @param squared [optional] - Controls whether the distance should remain squared, or its square root should be calculated. default: false + */ + getDistance(point: Point, squared?: boolean): number; + + /** + * Normalize modifies the length of the vector to 1 without changing its angle and returns it as a new point. The optional length parameter defines the length to normalize to. + * The object itself is not modified! + * @param length [optional] - The length of the normalized vector, default: 1 + */ + normalize(length?: number): Point; + + /** + * Rotates the point by the given angle around an optional center point. + * The object itself is not modified. + * Read more about angle units and orientation in the description of the angle property. + * @param angle - the rotation angle + * @param center - the center point of the rotation + */ + rotate(angle: number, center: Point): Point; + + /** + * Transforms the point by the matrix as a new point. The object itself is not modified! + * @param matrix - + */ + transform(matrix: Matrix): Point; + + /** + * Checks whether the point is inside the boundaries of the rectangle. + * @param rect - the rectangle to check against + */ + isInside(rect: Rectangle): boolean; + + /** + * Checks if the point is within a given distance of another point. + * @param point - the point to check against + * @param tolerance - the maximum distance allowed + */ + isClose(point: Point, tolerance: number): boolean; + + /** + * Checks if the vector represented by this point is colinear (parallel) to another vector. + * @param point - the vector to check against + */ + isColinear(point: Point): boolean; + + /** + * Checks if the vector represented by this point is orthogonal (perpendicular) to another vector. + * @param point - the vector to check against + */ + isOrthogonal(point: Point): boolean; + + /** + * Checks if this point has both the x and y coordinate set to 0. + */ + isZero(): boolean; + + /** + * Checks if this point has an undefined value for at least one of its coordinates. + */ + isNan(): boolean; + + /** + * Returns the dot product of the point and another point. + * @param point - + */ + dot(point: Point): number; + + /** + * Returns the cross product of the point and another point. + * @param point - + */ + cross(point: Point): number; + + /** + * Returns the projection of the point on another point. + * Both points are interpreted as vectors. + * @param point - + */ + project(point: Point): Point; + + /** + * Returns a new point with rounded x and y values. The object itself is not modified! + */ + round(): Point; + + /** + * Returns a new point with the nearest greater non-fractional values to the specified x and y values. The object itself is not modified! + */ + ceil(): Point; + + /** + * Returns a new point with the nearest smaller non-fractional values to the specified x and y values. The object itself is not modified! + */ + floor(): Point; + + /** + * Returns a new point with the absolute values of the specified x and y values. The object itself is not modified! + */ + abs(): Point; + + } + /** + * A Rectangle specifies an area that is enclosed by it's top-left point (x, y), its width, and its height. It should not be confused with a rectangular path, it is not an item. + */ + export class Rectangle { + + /** + * Creates a Rectangle object. + * @param point - the top-left point of the rectangle + * @param size - the size of the rectangle + */ + constructor(point: Point, size: Size); + + /** + * Creates a rectangle object. + * @param x - the left coordinate + * @param y - the top coordinate + * @param width - the width + * @param height - the height + */ + constructor(x: number, y: number, width: number, height: number); + + /** + * Creates a Rectangle object. + * @param object - an object containing properties to be set on the rectangle. + */ + constructor(object: any); + + /** + * Creates a rectangle object from the passed points. These do not necessarily need to be the top left and bottom right corners, the constructor figures out how to fit a rectangle between them. + * @param from - The first point defining the rectangle + * @param to - The second point defining the rectangle + */ + constructor(from: Point, to: Point); + + /** + * Creates a new rectangle object from the passed rectangle object. + * @param rt - the rectangle to copy from + */ + constructor(rt: Rectangle); + + /** + * The x position of the rectangle. + */ + x: number; + + /** + * The y position of the rectangle. + */ + y: number; + + /** + * The width of the rectangle. + */ + width: number; + + /** + * The height of the rectangle. + */ + height: number; + + /** + * The top-left point of the rectangle + */ + point: Point; + + /** + * The size of the rectangle + */ + size: Size; + + /** + * The position of the left hand side of the rectangle. Note that this doesn't move the whole rectangle; the right hand side stays where it was. + */ + left: number; + + /** + * The top coordinate of the rectangle. Note that this doesn't move the whole rectangle: the bottom won't move. + */ + top: number; + + /** + * The position of the right hand side of the rectangle. Note that this doesn't move the whole rectangle; the left hand side stays where it was. + */ + right: number; + + /** + * The bottom coordinate of the rectangle. Note that this doesn't move the whole rectangle: the top won't move. + */ + bottom: number; + + /** + * The center point of the rectangle. + */ + center: Point; + + /** + * The top-left point of the rectangle. + */ + topLeft: Point; + + /** + * The top-right point of the rectangle. + */ + topRight: Point; + + /** + * The bottom-left point of the rectangle. + */ + bottomLeft: Point; + + /** + * The bottom-right point of the rectangle. + */ + bottomRight: Point; + + /** + * The left-center point of the rectangle. + */ + leftCenter: Point; + + /** + * The top-center point of the rectangle. + */ + topCenter: Point; + + /** + * The right-center point of the rectangle. + */ + rightCenter: Point; + + /** + * The bottom-center point of the rectangle. + */ + bottomCenter: Point; + + /** + * The area of the rectangle in square points. + * Read only. + */ + area: number; + + /** + * Specifies whether an item's bounds are selected and will also mark the item as selected. + * Paper.js draws the visual bounds of selected items on top of your project. This can be useful for debugging. + */ + selected: boolean; + + /** + * Returns a copy of the rectangle. + */ + clone(): Rectangle; + + /** + * Checks whether the coordinates and size of the rectangle are equal to that of the supplied rectangle. + * @param rect - the rectangle to check against + */ + equals(rect: Rectangle): boolean; + + /** + * a string representation of this rectangle + */ + toString(): string; + + /** + * Returns true if the rectangle is empty, false otherwise + */ + isEmpty(): boolean; + + /** + * Tests if the specified point is inside the boundary of the rectangle. + * @param point - the specified point + */ + contains(point: Point): boolean; + + /** + * Tests if the interior of the rectangle entirely contains the specified rectangle. + * @param rect - The specified rectangle + */ + contains(rect: Rectangle): boolean; + + /** + * Tests if the interior of this rectangle intersects the interior of another rectangle. Rectangles just touching each other are considered as non-intersecting. + * @param rect - the specified rectangle + */ + intersects(rect: Rectangle): boolean; + + /** + * Returns a new rectangle representing the intersection of this rectangle with the specified rectangle. + * @param rect - The rectangle to be intersected with this rectangle + */ + intersect(rect: Rectangle): Rectangle; + + /** + * Returns a new rectangle representing the union of this rectangle with the specified rectangle. + * @param rect - the rectangle to be combined with this rectangle + */ + unite(rect: Rectangle): Rectangle; + + /** + * Adds a point to this rectangle. The resulting rectangle is the smallest rectangle that contains both the original rectangle and the specified point. + * After adding a point, a call to contains(point) with the added point as an argument does not necessarily return true. + * The rectangle.contains(point) method does not return true for points on the right or bottom edges of a rectangle. Therefore, if the added point falls on the left or bottom edge of the enlarged rectangle, rectangle.contains(point) returns false for that point. + * @param point - the point to add to the rectangle + */ + include(point: Point): Point; + + /** + * Expands the rectangle by the specified amount in horizontal and vertical directions. + * @param amount - the amount to expand the rectangle in both directions + */ + expand(amount: number | Size | Point): void; + + /** + * Expands the rectangle by the specified amounts in horizontal and vertical directions. + * @param hor - the amount to expand the rectangle in horizontal direction + * @param ver - the amount to expand the rectangle in vertical direction + */ + expand(hor: number, ver: number): void; + + /** + * Scales the rectangle by the specified amount from its center. + * @param amount - the amount to scale by + */ + scale(amount: number): void; + + /** + * Scales the rectangle in horizontal direction by the specified hor amount and in vertical direction by the specified ver amount from its center. + * @param hor - the amount to scale the rectangle in horizontal direction + * @param ver - the amount to scale the rectangle in vertical direction + */ + scale(hor: number, ver: number): void; + + } + /** + * The Size object is used to describe the size or dimensions of something, through its width and height properties. + */ + export class Size { + + /** + * Returns a new size object with the smallest width and height of the supplied sizes. + * @param size1 - the first size + * @param size2 - the second size + */ + static min(size1: Size, size2: Size): Size; + + /** + * Returns a new size object with the largest width and height of the supplied sizes. + * @param size1 - the first size + * @param size2 - the second size + */ + static max(size1: Size, size2: Size): Size; + + /** + * Returns a size object with random width and height values between 0 and 1. + */ + static random(): Size; + + /** + * Creates a Size object with the given width and height values. + * @param width - the width + * @param height - the height + */ + constructor(width: number, height: number); + + /** + * Creates a Size object using the numbers in the given array as dimensions. + * @param array - an array of numbers + */ + constructor(array: number[]); + + /** + * Creates a Size object using the properties in the given object. + * @param object - the object literal containing properies (width:10, height:10 etc) + */ + constructor(object: any); + + /** + * Creates a Size object using the coordinates of the given Size object. + * @param size - the size to duplicate from + */ + constructor(size: Size); + + /** + * Creates a Size object using the point.x and point.y values of the given Point object. + * @param point - the point from which to create a size + */ + constructor(point: Point); + + /** + * The width of the size + */ + width: number; + + /** + * The height of the size + */ + height: number; + + /** + * WARNING - This seems undocumented/incorrect + */ + equals(): boolean; + + /** + * Returns a copy of the size. + */ + clone(): Size; + + /** + * a string representation of the size + */ + toString(): string; + + /** + * Checks if this size has both the width and height set to 0. + */ + isZero(): boolean; + + /** + * Checks if the width or the height of the size are NaN. + */ + isNan(): boolean; + + /** + * Returns a new size with rounded width and height values. The object itself is not modified! + */ + round(): Size; + + /** + * Returns a new size with the nearest greater non-fractional values to the specified width and height values. The object itself is not modified! + */ + ceil(): Size; + + /** + * Returns a new size with the nearest smaller non-fractional values to the specified width and height values. The object itself is not modified! + */ + floor(): Size; + + /** + * Returns a new size with the absolute values of the specified width and height values. The object itself is not modified! + */ + abs(): Size; + + } + export interface IFrameEvent { + + /** + * the number of times the frame event was fired. + */ + count: number; + + /** + * the total amount of time passed since the first + */ + time: number; + + /** + * + */ + delta: number; + + } + /** + * The PaperScope class represents the scope associated with a Paper context. When working with PaperScript, these scopes are automatically created for us, and through clever scoping the properties and methods of the active scope seem to become part of the global scope. + * When working with normal JavaScript code, PaperScope objects need to be manually created and handled. + * Paper classes can only be accessed through PaperScope objects. Thus in PaperScript they are global, while in JavaScript, they are available on the global paper object. For JavaScript you can use paperScope.install(scope) to install the Paper classes and objects on the global scope. Note that when working with more than one scope, this still works for classes, but not for objects like paperScope.project, since they are not updated in the injected scope if scopes are switched. + * The global paper object is simply a reference to the currently active PaperScope. + */ + export class PaperScope { + + /** + * The version of Paper.js, as a string. + */ + version: string; + + /** + * Gives access to paper's configurable settings. + */ + settings: { + + applyMatrix: boolean; + handleSize: number; + hitTolerance: number; + + }; + + /** + * The currently active project. + */ + project: Project; + + /** + * The list of all open projects within the current Paper.js context. + */ + projects: Project[]; + + /** + * The reference to the active project's view. + * Read Only. + */ + view: View; + + /** + * The reference to the active tool. + */ + tool: Tool; + + /** + * The list of available tools. + */ + tools: Tool[]; + + /** + * Injects the paper scope into any other given scope. Can be used for examle to inject the currently active PaperScope into the window's global scope, to emulate PaperScript-style globally accessible Paper classes and objects + * Please note: Using this method may override native constructors (e.g. Path, RGBColor). This may cause problems when using Paper.js in conjunction with other libraries that rely on these constructors. Keep the library scoped if you encounter issues caused by this. + * @param scope - + */ + install(scope: any): void; + + /** + * Sets up an empty project for us. If a canvas is provided, it also creates a View for it, both linked to this scope. + * @param element - the HTML canvas element this scope should be associated with, or an ID string by which to find the element. + */ + setup(canvas: HTMLCanvasElement | string): void; + + /** + * Activates this PaperScope, so all newly created items will be placed in its active project. + */ + activate(): void; + + /** + * Retrieves a PaperScope object with the given scope id. + * @param id - + */ + static get(id: string): PaperScope; + + } + /** + * The Item type allows you to access and modify the items in Paper.js projects. Its functionality is inherited by different project item types such as Path, CompoundPath, Group, Layer and Raster. They each add a layer of functionality that is unique to their type, but share the underlying properties and functions that they inherit from Item. + */ + export class Item { + + /** + * The tangential vector to the #curve at the given location. + */ + tangent: Point; + + /** + * The normal vector to the #curve at the given location. + */ + normal: Point; + + /** + * The curvature of the #curve at the given location. + */ + curvature: number; + + /** + * The unique id of the item. + * Read Only. + */ + id: number; + + /** + * The class name of the item as a string. + * String('Group', 'Layer', 'Path', 'CompoundPath', 'Shape', 'Raster', 'PlacedSymbol', 'PointText') + */ + className: string; + + /** + * The name of the item. If the item has a name, it can be accessed by name through its parent's children list. + */ + name: string; + + /** + * The path style of the item. + */ + style: Style; + + /** + * Specifies whether the item is visible. When set to false, the item won't be drawn. + */ + visible: boolean; + + /** + * The blend mode with which the item is composited onto the canvas. Both the standard canvas compositing modes, as well as the new CSS blend modes are supported. If blend-modes cannot be rendered natively, they are emulated. Be aware that emulation can have an impact on performance. + * String('normal', 'multiply', 'screen', 'overlay', 'soft-light', 'hard-light', 'color-dodge', 'color-burn', 'darken', 'lighten', 'difference', 'exclusion', 'hue', 'saturation', 'luminosity', 'color', 'add', 'subtract', 'average', 'pin-light', 'negation', 'source-over', 'source-in', 'source-out', 'source-atop', 'destination-over', 'destination-in', 'destination-out', 'destination-atop', 'lighter', 'darker', 'copy', 'xor') + */ + blendMode: string; + + /** + * The opacity of the item as a value between 0 and 1. + */ + opacity: number; + + /** + * Specifies whether the item is selected. This will also return true for Group items if they are partially selected, e.g. groups containing selected or partially selected paths. + * Paper.js draws the visual outlines of selected items on top of your project. This can be useful for debugging, as it allows you to see the construction of paths, position of path curves, individual segment points and bounding boxes of symbol and raster items. + */ + selected: boolean; + + /** + * Specifies whether the item defines a clip mask. This can only be set on paths, compound paths, and text frame objects, and only if the item is already contained within a clipping group. + */ + clipMask: boolean; + + /** + * A plain javascript object which can be used to store arbitrary data on the item. + */ + data: any; + + /** + * The item's position within the parent item's coordinate system. By default, this is the rectangle.center of the item's bounds rectangle. + */ + position: Point; + + /** + * The item's pivot point specified in the item coordinate system, defining the point around which all transformations are hinging. This is also the reference point for position. By default, it is set to null, meaning the rectangle.center of the item's bounds rectangle is used as pivot. + */ + pivot: Point; + + /** + * The bounding rectangle of the item excluding stroke width. + */ + bounds: Rectangle; + + /** + * The bounding rectangle of the item including stroke width. + */ + strokeBounds: Rectangle; + + /** + * The bounding rectangle of the item including handles. + */ + handleBounds: Rectangle; + + /** + * The current rotation angle of the item, as described by its matrix. + */ + rotation: number; + + /** + * The current scale factor of the item, as described by its matrix. + */ + scaling: Point; + + /** + * The item's transformation matrix, defining position and dimensions in relation to its parent item in which it is contained. + */ + matrix: Matrix; + + /** + * The item's global transformation matrix in relation to the global project coordinate space. Note that the view's transformations resulting from zooming and panning are not factored in. + * Read Only. + */ + globalMatrix: Matrix; + + /** + * Controls whether the transformations applied to the item (e.g. through transform(matrix), rotate(angle), scale(scale), etc.) are stored in its matrix property, or whether they are directly applied to its contents or children (passed on to the segments in Path items, the children of Group items, etc.). + */ + applyMatrix: boolean; + + /** + * The project that this item belongs to. + * Read only. + */ + project: Project; + + /** + * The view that this item belongs to. + * Read Only. + */ + view: View; + + /** + * The layer that this item is contained within. + * Read Only. + */ + layer: Layer; + + /** + * The item that this item is contained within. + */ + parent: Item; + + /** + * The children items contained within this item. Items that define a name can also be accessed by name. + * Please note: The children array should not be modified directly using array functions. To remove single items from the children list, use item.remove(), to remove all items from the children list, use item.removeChildren(). To add items to the children list, use item.addChild(item) or item.insertChild(index, item). + */ + children: Item[]; + + /** + * The first item contained within this item. This is a shortcut for accessing item.children[0]. + */ + firstChild: Item; + + /** + * The last item contained within this item.This is a shortcut for accessing item.children[item.children.length - 1]. + */ + lastChild: Item; + + /** + * The next item on the same level as this item. + * Read Only. + */ + nextSibling: Item; + + /** + * The previous item on the same level as this item. + * Read Only. + */ + previousSibling: Item; + + /** + * The index of this item within the list of its parent's children. + * Read only. + */ + index: number; + + /** + * The color of the stroke. + */ + strokeColor: Color | string; + + /** + * The width of the stroke. + */ + strokeWidth: number; + + /** + * The shape to be used at the beginning and end of open Path items, when they have a stroke. + * String('round', 'square', 'butt') + */ + strokeCap: string; + + /** + * The shape to be used at the segments and corners of Path items when they have a stroke. + * String('miter', 'round', 'bevel') + */ + strokeJoin: string; + + /** + * The dash offset of the stroke. + */ + dashOffset: number; + + /** + * Specifies whether the stroke is to be drawn taking the current affine transformation into account (the default behavior), or whether it should appear as a non-scaling stroke. + */ + strokeScaling: boolean; + + /** + * Specifies an array containing the dash and gap lengths of the stroke. + */ + dashArray: number[]; + + /** + * When two line segments meet at a sharp angle and miter joins have been specified for item.strokeJoin, it is possible for the miter to extend far beyond the item.strokeWidth of the path. The miterLimit imposes a limit on the ratio of the miter length to the item.strokeWidth. + */ + miterLimit: number; + + /** + * The winding-rule with which the shape gets filled. Please note that only modern browsers support winding-rules other than 'nonzero'. + * String('nonzero', 'evenodd') + */ + windingRule: string; + + /** + * The fill color of the item. + */ + fillColor: Color | string; + + /** + * The color the item is highlighted with when selected. If the item does not specify its own color, the color defined by its layer is used instead. + */ + selectedColor: Color | string; + + /** + * Item level handler function to be called on each frame of an animation. + * The function receives an event object which contains information about the frame event: + */ + onFrame: (event: IFrameEvent) => void; + + /** + * The function to be called when the mouse button is pushed down on the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseDown: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse button is released over the item. + * The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseUp: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse clicks on the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onClick: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse double clicks on the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onDoubleClick: (event: MouseEvent) => void; + + /** + * The function to be called repeatedly when the mouse moves on top of the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseMove: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse moves over the item. This function will only be called again, once the mouse moved outside of the item first. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseEnter: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse moves out of the item. + * The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseLeave: (event: MouseEvent) => void; + + /** + * Sets those properties of the passed object literal on this item to the values defined in the object literal, if the item has property of the given name (or a setter defined for it). + */ + set(props: any): Item; + + /** + * Clones the item within the same project and places the copy above the item. + * @param insert [optional] - specifies whether the copy should be inserted into the DOM. When set to true, it is inserted above the original. default: true + */ + clone(insert?: boolean): Item; + + /** + * When passed a project, copies the item to the project, or duplicates it within the same project. When passed an item, copies the item into the specified item. + * @param item - the item or project to copy the item to + */ + copyTo(item: Item): Item; + + /** + * Rasterizes the item into a newly created Raster object. The item itself is not removed after rasterization. + * @param resolution [optional] - the resolution of the raster in pixels per inch (DPI). If not specified, the value of view.resolution is used. default: view.resolution + */ + rasterize(resolution: number): Raster; + + /** + * Checks whether the item's geometry contains the given point. + * @param point - The point to check for. + */ + contains(point: Point): boolean; + + /** + * + * @param rect - the rectangle to check against + */ + isInside(rect: Rectangle): boolean; + + /** + * + * @param item - the item to check against + */ + intersects(item: Item): boolean; + + /** + * Perform a hit-test on the items contained within the project at the location of the specified point. + * The options object allows you to control the specifics of the hit-test and may contain a combination of the following values: + * @param point - the point where the hit-test should be performed + * @param options.tolerance -the tolerance of the hit-test in points. Can also be controlled through paperScope.settings.hitTolerance + * @param options.class - only hit-test again a certain item class and its sub-classes: Group, Layer, Path, CompoundPath, Shape, Raster, PlacedSymbol, PointText, etc. + * @param options.fill - hit-test the fill of items. + * @param options.stroke - hit-test the stroke of path items, taking into account the setting of stroke color and width. + * @param options.segments - hit-test for segment.point of Path items. + * @param options.curves - hit-test the curves of path items, without taking the stroke color or width into account. + * @param options.handles - hit-test for the handles. (segment.handleIn / segment.handleOut) of path segments. + * @param options.ends - only hit-test for the first or last segment points of open path items. + * @param options.bounds - hit-test the corners and side-centers of the bounding rectangle of items (item.bounds). + * @param options.center - hit-test the rectangle.center of the bounding rectangle of items (item.bounds). + * @param options.guides - hit-test items that have Item#guide set to true. + * @param options.selected - only hit selected items. + */ + hitTest(point: Point, options?: { tolerance?: number; class?: string; fill?: boolean; stroke?: boolean; segments?: boolean; curves?: boolean; handles?: boolean; ends?: boolean; bounds?: boolean; center?: boolean; guides?: boolean; selected?: boolean; }): HitResult; + + /** + * Checks whether the item matches the criteria described by the given object, by iterating over all of its properties and matching against their values through matches(name, compare). + * See project.getItems(match) for a selection of illustrated examples. + * @param match - the criteria to match against. + */ + matches(match: any): boolean; + + /** + * Checks whether the item matches the given criteria. Extended matching is possible by providing a compare function or a regular expression. + * Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x-coordinate to match all points with that x-value). Partial matching does work for item.data. + * @param name - the name of the state to match against. + * @param compare - the value, function or regular expression to compare against. + */ + matches(name: string, compare: any): boolean; + + /** + * Fetch the descendants (children or children of children) of this item that match the properties in the specified object. + * Extended matching is possible by providing a compare function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data. + * Matching items against a rectangular area is also possible, by setting either match.inside or match.overlapping to a rectangle describing the area in which the items either have to be fully or partly contained. + * @param match.inside - the rectangle in which the items need to be fully contained. + * @param match.overlapping - the rectangle with which the items need to at least partly overlap. + */ + getItems(match: any): Item[]; + + /** + * Fetch the first descendant (child or child of child) of this item that matches the properties in the specified object. + * Extended matching is possible by providing a compare function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data. + * @param match - the criteria to match against + */ + getItem(match: any): Item; + + /** + * Exports (serializes) the project with all its layers and child items to a JSON data string. + * @param options [optional] - default {asString: true, precision: 5} + * @param options.asString - whether the JSON is returned as a Object or a String. + * @param options.precision - the amount of fractional digits in numbers used in JSON data. + */ + exportJSON(options?: { asString?: boolean; precision?: number }): string; + + /** + * Imports (deserializes) the stored JSON data into the project. + * Note that the project is not cleared first. You can call project.clear() to do so. + */ + importJSON(json: string): void; + + /** + * Exports the project with all its layers and child items as an SVG DOM, all contained in one top level SVG group node. + * @param options [optional] the export options, default: { asString: false, precision: 5, matchShapes: false } + * @param options.asString - whether a SVG node or a String is to be returned. + * @param options.precision - the amount of fractional digits in numbers used in SVG data. + * @param options.matchShapes - whether path items should tried to be converted to shape items, if their geometries can be made to match + */ + exportSVG(options?: { asString?: boolean; precision?: number; matchShapes?: boolean }): SVGElement; + + /** + * Converts the provided SVG content into Paper.js items and adds them to the active layer of this project. + * Note that the project is not cleared first. You can call project.clear() to do so. + * @param svg - the SVG content to import + * @param options [optional] - the import options, default: { expandShapes: false } + * @param options.expandShapes - whether imported shape items should be expanded to path items. + */ + importSVG(svg: SVGElement | string, options?: any): Item; + + /** + * Adds the specified item as a child of this item at the end of the its children list. You can use this function for groups, compound paths and layers. + * @param item - the item to add as a child + */ + addChild(item: Item): Item; + + /** + * Inserts the specified item as a child of this item at the specified index in its children list. You can use this function for groups, compound paths and layers. + * @param index - the index + * @param item - the item to be inserted as a child + */ + insertChild(index: number, item: Item): Item; + + /** + * Adds the specified items as children of this item at the end of the its children list. You can use this function for groups, compound paths and layers. + * @param items - The items to be added as children + */ + addChildren(items: Item[]): Item[]; + + /** + * Inserts the specified items as children of this item at the specified index in its children list. You can use this function for groups, compound paths and layers. + * @param index - + * @param items - The items to be appended as children + */ + insertChildren(index: number, items: Item[]): Item[]; + + /** + * Inserts this item above the specified item. + * @param item - the item above which it should be inserted + */ + insertAbove(item: Item): Item; + + /** + * Inserts this item below the specified item. + * @param item - the item below which it should be inserted + */ + insertBelow(item: Item): Item; + + /** + * Sends this item to the back of all other items within the same parent. + */ + sendToBack(): void; + + /** + * Brings this item to the front of all other items within the same parent. + */ + bringToFront(): void; + + /** + * If this is a group, layer or compound-path with only one child-item, the child-item is moved outside and the parent is erased. Otherwise, the item itself is returned unmodified. + */ + reduce(): Item; + + /** + * Removes the item and all its children from the project. The item is not destroyed and can be inserted again after removal. + */ + remove(): boolean; + + /** + * Replaces this item with the provided new item which will takes its place in the project hierarchy instead. + * @param item - the item to replace this one with + */ + replaceWith(item: Item): boolean; + + /** + * Removes all of the item's children (if any). + */ + removeChildren(): Item[]; + + /** + * Removes the children from the specified from index to the to index from the parent's children array. + * @param from - the beginning index, inclusive + * @param to [optional] - the ending index, exclusive, default: children.length + */ + removeChildren(from: number, to?: number): Item[]; + + /** + * Reverses the order of the item's children + */ + reverseChildren(): void; + + /** + * Specifies whether the item has any content or not. The meaning of what content is differs from type to type. For example, a Group with no children, a TextItem with no text content and a Path with no segments all are considered empty. + */ + isEmpty(): boolean; + + /** + * Checks whether the item has a fill. + */ + hasFill(): boolean; + + /** + * Checks whether the item has a stroke. + */ + hasStroke(): boolean; + + /** + * Checks whether the item has a shadow. + */ + hasShadow(): boolean; + + /** + * Checks if the item contains any children items. + */ + hasChildren(): boolean; + + /** + * Checks whether the item and all its parents are inserted into the DOM or not. + */ + isInserted(): boolean; + + /** + * Checks if this item is above the specified item in the stacking order of the project. + * @param item - The item to check against + */ + isAbove(item: Item): boolean; + + /** + * Checks if the item is below the specified item in the stacking order of the project. + * @param item - The item to check against + */ + isBelow(item: Item): boolean; + + /** + * Checks whether the specified item is the parent of the item. + * @param item - The item to check against + */ + isParent(item: Item): boolean; + + /** + * Checks whether the specified item is a child of the item. + * @param item - The item to check against + */ + isChild(item: Item): boolean; + + /** + * Checks if the item is contained within the specified item. + * @param item - The item to check against + */ + isDescendant(item: Item): boolean; + + /** + * Checks if the item is an ancestor of the specified item. + * @param item - the item to check against + */ + isAncestor(item: Item): boolean; + + /** + * Checks whether the item is grouped with the specified item. + * @param item - + */ + isGroupedWith(item: Item): boolean; + + /** + * Translates (moves) the item by the given offset point. + * @param delta - the offset to translate the item by + */ + translate(delta: number): Point; + + /** + * Rotates the item by a given angle around the given point. + * Angles are oriented clockwise and measured in degrees. + * @param angle - the rotation angle + * @param center [optional] - default: item.position + */ + rotate(angle: number, center?: Point): void; + + /** + * Scales the item by the given value from its center point, or optionally from a supplied point. + * @param scale - the scale factor + * @param center [optional] - default: item.position + */ + scale(scale: number, center?: Point): void; + + /** + * Scales the item by the given values from its center point, or optionally from a supplied point. + * @param hor - the horizontal scale factor + * @param ver - the vertical scale factor + * @param center [optional] - default: item.position + */ + scale(hor: number, ver: number, center?: Point): void; + + /** + * Shears the item by the given value from its center point, or optionally by a supplied point. + * @param shear - the horziontal and vertical shear factors as a point + * @param center [optional] - default: item.position + */ + shear(shear: number, center?: Point): void; + + /** + * Shears the item by the given values from its center point, or optionally by a supplied point. + * @param hor - the horizontal shear factor + * @param ver - the vertical shear factor + * @param center [optional] - default: item.position + */ + shear(hor: number, ver: number, center?: Point): void; + + /** + * Skews the item by the given angles from its center point, or optionally by a supplied point. + * @param skew - the horziontal and vertical skew angles in degrees + * @param center [optional] - default: item.position + */ + skew(skew: Point, center?: Point): void; + + /** + * Skews the item by the given angles from its center point, or optionally by a supplied point. + * @param hor - the horizontal skew angle in degrees + * @param ver - the vertical sskew angle in degrees + * @param center [optional] - default: item.position + */ + skew(hor: number, ver: number, center?: Point): void; + + /** + * Transform the item. + * @param matrix - the matrix by which the item shall be transformed. + */ + transform(matrix: Matrix): void; + + /** + * Converts the specified point from global project coordinate space to the item's own local coordinate space. + * @param point - the point to be transformed + */ + globalToLocal(point: Point): Point; + + /** + * Converts the specified point from the item's own local coordinate space to the global project coordinate space. + * @param point - the point to be transformed + */ + localToGlobal(point: Point): Point; + + /** + * Converts the specified point from the parent's coordinate space to item's own local coordinate space. + * @param point - the point to be transformed + */ + parentToLocal(point: Point): Point; + + /** + * Converts the specified point from the item's own local coordinate space to the parent's coordinate space. + * @param point - the point to be transformed + */ + localToParent(point: Point): Point; + + /** + * Transform the item so that its bounds fit within the specified rectangle, without changing its aspect ratio. + * @param rectangle - + * @param fill [optiona;] - default = false + */ + fitBounds(rectangle: Rectangle, fill?: boolean): void; + + //I cannot use function: Function as it is a reserved keyword + + /** + * Attach an event handler to the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be called when the event occurs + */ + on(type: string, callback: (event: ToolEvent) => void): Tool; + + /** + * Attach one or more event handlers to the tool. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + on(param: any): Tool; + + /** + * Detach an event handler from the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be detached + */ + off(type: string, callback: (event: ToolEvent) => void): Tool; + + /** + * Detach one or more event handlers from the tool. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + off(param: any): Tool; + + /** + * Emit an event on the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param event - an object literal containing properties describing the event. + */ + emit(type: string, event: any): boolean; + + /** + * Check if the tool has one or more event handlers of the specified type. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + */ + responds(type: string): boolean;//I cannot use function: Function as it is a reserved keyword + + /** + * Attaches an event handler to the item. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be called when the event occurs + */ + on(type: string, callback: () => void): Item; + + /** + * Attaches one or more event handlers to the item. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + on(param: any): Item; + + /** + * Detach an event handler from the item. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be detached + */ + off(type: string, callback: (event: ToolEvent) => void): Item; + + /** + * Detach one or more event handlers to the item. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + off(param: any): Item; + + /** + * Emit an event on the item. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param event - an object literal containing properties describing the event. + */ + emit(type: string, event: any): boolean; + + /** + * Check if the item has one or more event handlers of the specified type.. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + */ + responds(type: string): boolean; + + /** + * Removes the item when the events specified in the passed object literal occur. + * @param object - The object literal can contain the following values + * @param object.move - Remove the item when the next tool.onMouseMove event is fired + * @param object.drag - Remove the item when the next tool.onMouseDrag event is fired + * @param object.down - Remove the item when the next tool.onMouseDown event is fired + * @param object.up - Remove the item when the next tool.onMouseUp event is fired + */ + removeOn(object: { move?: boolean; drag?: boolean; down?: boolean; up?: boolean; }): void; + + /** + * Removes the item when the next tool.onMouseMove event is fired. + */ + removeOnMove(): void; + + /** + * Removes the item when the next tool.onMouseDown event is fired. + */ + removeOnDown(): void; + + /** + * Removes the item when the next tool.onMouseDrag event is fired. + */ + removeOnDrag(): void; + + /** + * Removes the item when the next tool.onMouseUp event is fired. + */ + removeOnUp(): void; + + } + /** + * A Group is a collection of items. When you transform a Group, its children are treated as a single unit without changing their relative positions. + */ + export class Group extends Item { + + /** + * Creates a new Group item and places it at the top of the active layer. + * @param children [optional] - An array of Item Objects children that will be added to the newly created group. + */ + constructor(children?: Item[]); + + /** + * Creates a new Group item and places it at the top of the active layer. + * @param object [optional] - an object literal containing the properties to be set on the group. + */ + constructor(object?: any); + + /** + * Specifies whether the group item is to be clipped. + * When setting to true, the first child in the group is automatically defined as the clipping mask. + */ + clipped: boolean; + + } + /** + * The Layer item represents a layer in a Paper.js project. + * The layer which is currently active can be accessed through project.activeLayer. + * An array of all layers in a project can be accessed through project.layers. + */ + export class Layer extends Group { + + /** + * Creates a new Layer item and places it at the end of the project.layers array. The newly created layer will be activated, so all newly created items will be placed within it. + * @param children [optional] - An array of Items that will be added to the newly created layer. + */ + constructor(children?: Item[]); + /** + * Creates a new Layer item and places it at the end of the project.layers array. The newly created layer will be activated, so all newly created items will be placed within it. + * @param object [optional] - an object literal containing the properties to be set on the layer. + */ + constructor(object?: any); + + /** + * Activates the layer. + */ + activate(): void; + + } + export class Shape extends Item { + + /** + * Creates a circular shape item. + * @param center - the center point of the circle + * @param radius - the radius of the circle + */ + static Circle(center: Point, radius: number): Shape; + + /** + * Creates a circular shape item from the properties described by an object literal. + * @param object - an object literal containing properties descriving the shapes attributes + */ + static Circle(object: any): Shape; + + /** + * Creates a rectangular shape item, with optionally rounded corners. + * @param rectangle - the rectangle object describing the geometry of the rectangular shape to be created. + * @param radius [optional] - the size of the rounded corners, default: null + */ + static Rectangle(rectangle: Rectangle, radius?: number): Shape; + + /** + * Creates a rectangular shape item from a point and a size object. + * @param point - the rectangle's top-left corner + * @param size - the rectangle's size. + */ + static Rectangle(point: Point, size: Size): Shape; + + /** + * Creates a rectangular shape item from the passed points. These do not necessarily need to be the top left and bottom right corners, the constructor figures out how to fit a rectangle between them. + * @param from - the first point defining the rectangle + * @param to - the second point defining the rectangle + */ + static Rectangle(from: Point, to: Point): Shape; + + /** + * Creates a rectangular shape item from the properties described by an object literal. + * @param object - an object literal containing properties describing the shape's attributes + */ + static Rectangle(object: any): Shape; + + /** + * Creates an elliptical shape item. + * @param rectangle - the rectangle circumscribing the ellipse + */ + static Ellipse(rectangle: Rectangle): Shape; + + /** + * Creates an elliptical shape item from the properties described by an object literal. + * @param object - an object literal containing properties describing the shape's attributes + */ + static Ellipse(object: any): Shape; + + /** + * The type of shape of the item as a string. + */ + type: string; + + /** + * The size of the shape. + */ + size: Size; + + /** + * The radius of the shape, as a number if it is a circle, or a size object for ellipses and rounded rectangles. + */ + radius: number | Size; + + } + /** + * The Raster item represents an image in a Paper.js project. + */ + export class Raster extends Item { + + /** + * Creates a new raster item from the passed argument, and places it in the active layer. object can either be a DOM Image, a Canvas, or a string describing the URL to load the image from, or the ID of a DOM element to get the image from (either a DOM Image or a Canvas). + * @param source [optional] - the source of the raster + * @param position [optional] - the center position at which the raster item is placed + */ + constructor(source?: HTMLImageElement | HTMLCanvasElement | string, position?: Point); + + /** + * The size of the raster in pixels. + */ + size: Size; + + /** + * The width of the raster in pixels. + */ + width: number; + + /** + * The height of the raster in pixels. + */ + height: number; + + /** + * The resolution of the raster at its current size, in PPI (pixels per inch). + * Read Only. + */ + resolution: Size; + + /** + * The HTMLImageElement of the raster, if one is associated. + */ + image: HTMLImageElement | HTMLCanvasElement; + + /** + * The Canvas object of the raster. If the raster was created from an image, accessing its canvas causes the raster to try and create one and draw the image into it. Depending on security policies, this might fail, in which case null is returned instead. + */ + canvas: HTMLCanvasElement; + + /** + * The Canvas 2D drawing context of the raster. + */ + context: CanvasRenderingContext2D; + + /** + * The source of the raster, which can be set using a DOM Image, a Canvas, a data url, a string describing the URL to load the image from, or the ID of a DOM element to get the image from (either a DOM Image or a Canvas). Reading this property will return the url of the source image or a data-url. + */ + source: HTMLImageElement | HTMLCanvasElement | string; + + /** + * Extracts a part of the Raster's content as a sub image, and returns it as a Canvas object. + * @param rect - the boundaries of the sub image in pixel coordinates + */ + getSubCanvas(rect: Rectangle): HTMLCanvasElement; + + /** + * Extracts a part of the raster item's content as a new raster item, placed in exactly the same place as the original content. + * @param rect - the boundaries of the sub raster in pixel coordinates + */ + getSubRaster(rect: Rectangle): Raster; + + /** + * Returns a Base 64 encoded data: URL representation of the raster. + */ + toDataURL(): string; + + /** + * Draws an image on the raster. + * @param image - the image to draw + * @param point - the offset of the image as a point in pixel coordinates + */ + drawImage(image: HTMLImageElement | HTMLCanvasElement, point: Point): void; + + /** + * Calculates the average color of the image within the given path, rectangle or point. This can be used for creating raster image effects. + * @param object - the path, rectangle or point to get the average image color from + */ + getAverageColor(object: Path | Rectangle | Point): Color; + + /** + * Gets the color of a pixel in the raster. + * @param x - the x offset of the pixel in pixel coordinates + * @param y - the y offset of the pixel in pixel coordinates + */ + getPixel(x: number, y: number): Color; + + /** + * Gets the color of a pixel in the raster. + * @param point - the offset of the pixel as a point in pixel coordinates + */ + getPixel(point: Point): Color; + + /** + * Sets the color of the specified pixel to the specified color + * @param x - the x offset of the pixel in pixel coordinates + * @param y - the y offset of the pixel in pixel coordinates + * @param color - the color that the pixel will be set to + */ + setPixel(x: number, y: number, color: Color): void; + + /** + * Sets the color of the specified pixel to the specified color. + * @param point - the offset of the pixel as a point in pixel coordinates + * @param color - the color that the pixel will be set to + */ + setPixel(point: Point, color: Color): void; + + /** + * + * @param size + */ + createImageData(size: Size): ImageData; + + /** + * + * @param rect + */ + getImageData(rect: Rectangle): ImageData; + + /** + * + * + * @param data + * @param point + */ + getImageData(data: ImageData, point: Point): void; + + } + /** + * A PlacedSymbol represents an instance of a symbol which has been placed in a Paper.js project. + */ + export class PlacedSymbol extends Item { + + /** + * Creates a new PlacedSymbol Item. + * @param symbol - the symbol to place + * @param point [optional] - the center point of the placed symbol + */ + constructor(symbol: Symbol, point?: Point); + + /** + * The symbol that the placed symbol refers to. + */ + symbol: Symbol; + + } + /** + * A HitResult object contains information about the results of a hit test. It is returned by item.hitTest(point) and project.hitTest(point). + */ + export class HitResult { + + /** + * Describes the type of the hit result. For example, if you hit a segment point, the type would be 'segment'. + * type String('segment', 'handle-in', 'handle-out', 'curve', 'stroke', 'fill', 'bounds', 'center', 'pixel') + */ + type: string; + + /** + * If the HitResult has a hitResult.type of 'bounds', this property describes which corner of the bounding rectangle was hit. + * type String('top-left', 'top-right', 'bottom-left', 'bottom-right', 'left-center', 'top-center', 'right-center', 'bottom-center') + */ + name: string; + + /** + * The item that was hit. + */ + item: Item; + + /** + * If the HitResult has a type of 'curve' or 'stroke', this property gives more information about the exact position that was hit on the path. + */ + location: CurveLocation; + + /** + * If the HitResult has a type of 'pixel', this property refers to the color of the pixel on the Raster that was hit. + */ + color: Color; + + /** + * If the HitResult has a type of 'stroke', 'segment', 'handle-in' or 'handle-out', this property refers to the segment that was hit or that is closest to the hitResult.location on the curve. + */ + segment: Segment; + + /** + * Describes the actual coordinates of the segment, handle or bounding box corner that was hit + */ + point: Point; + + } + /** + * The PathItem class is the base for any items that describe paths and offer standardised methods for drawing and path manipulation, such as Path and CompoundPath. + */ + export class PathItem extends Item { + + /** + * The path's geometry, formatted as SVG style path data. + */ + pathData: string; + + /** + * Returns all intersections between two PathItem items as an array of CurveLocation objects. CompoundPath items are also supported. + * @param path - the other item to find the intersections with + * @param sorted [optional] - specifies whether the returned CurveLocation objects should be sorted by path and offset, default: false + */ + getIntersections(path: PathItem, sorted?: boolean): CurveLocation[]; + + /** + * Smooth bezier curves without changing the amount of segments or their points, by only smoothing and adjusting their handle points, for both open ended and closed paths. + */ + smooth(): void; + + /** + * On a normal empty Path, the point is simply added as the path's first segment. If called on a CompoundPath, a new Path is created as a child and the point is added as its first segment. + * @param point - the path's first segment + */ + moveTo(point: Point): void; + + /** + * Draw a line from the current point to the given point + * @param point - the end point of the line + */ + lineTo(point: Point): void; + + /** + * Adds a cubic bezier curve to the path, defined by two handles and a to point. + * @param handle1 - The first control point handle for the curve + * @param handle2 - The second control point handle for the curve + * @param to - The end control point of the curve + */ + cublicCurveTo(handle1: Point, handle2: Point, to: Point): void; + + /** + * Adds a quadratic bezier curve to the path, defined by a handle and a to point. + * @param handle - The control point for the curve + * @param to - The end control point of the curve + */ + quadraticCurveTo(handle: Point, to: Point): void; + + /** + * Draws a curve from the position of the last segment point in the path that goes through the specified through point, to the specified to point by adding one segment to the path. + * @param through - the point through which the curve should go + * @param to - the point where the curve should end + * @param parameter [optional] - default: 0.5 + */ + curveTo(through: Point, to: Point, parameter?: number): void; + + /** + * Draws an arc from the position of the last segment point in the path that goes through the specified through point, to the specified to point by adding one or more segments to the path. + * @param through - the point where the arc should pass through + * @param to - the point where the arc should end + */ + arcTo(through: Point, to: Point): void; + + /** + * Draws an arc from the position of the last segment point in the path to the specified point by adding one or more segments to the path. + * @param to - the point where the arc should end + * @param closewise [optional] - specifies whether the arc should be drawn in clockwise direction. optional, default: true + */ + arcTo(to: Point, clockwise?: boolean): void; + + /** + * Closes the path. When closed, Paper.js connects the first and last segment of the path with an additional curve. + * @param join - controls whether the method should attempt to merge the first segment with the last if they lie in the same location. + */ + closePath(join: boolean): void; + + /** + * If called on a CompoundPath, a new Path is created as a child and a point is added as its first segment relative to the position of the last segment of the current path. + * @param to - + */ + moveBy(to: Point): void; + + /** + * Adds a segment relative to the last segment point of the path. + * @param to - the vector which is added to the position of the last segment of the path, to get to the position of the new segment. + */ + lineBy(to: Point): void; + + /** + * + * @param through - + * @param to - + * @param parameter [optional] - default 0.5 + */ + curveBy(through: Point, to: Point, parameter?: number): void; + + /** + * + * @param handle1 - + * @param handle2 - + * @param to - + */ + cublicCurveBy(handle1: Point, handle2: Point, to: Point): void; + + /** + * + * @param handle - + * @param to - + */ + quadraticCurveBy(handle: Point, to: Point): void; + + /** + * + * @param through - + * @param to - + */ + arcBy(through: Point, to: Point): void; + + /** + * + * @param to - + * @param clockwise [optional] - default: true + */ + arcBy(to: Point, clockwise?: boolean): void; + + /** + * Merges the geometry of the specified path from this path's geometry and returns the result as a new path item. + * @param path - the path to unite with + */ + unite(path: PathItem): PathItem; + + /** + * Intersects the geometry of the specified path with this path's geometry and returns the result as a new path item. + * @param path - the path to intersect with + */ + intersect(path: PathItem): PathItem; + + /** + * Subtracts the geometry of the specified path from this path's geometry and returns the result as a new path item. + * @param - the path to subtract + */ + subtract(path: PathItem): PathItem; + + /** + * Excludes the intersection of the geometry of the specified path with this path's geometry and returns the result as a new group item. + * @param - the path to exclude the intersection of + */ + exclude(path: PathItem): PathItem; + + /** + * Splits the geometry of this path along the geometry of the specified path returns the result as a new group item. + * @param - the path to divide by + */ + divide(path: PathItem): PathItem; + + } + /** + * The path item represents a path in a Paper.js project. + */ + export class Path extends PathItem { + + /** + * Creates a linear path item from two points describing a line. + * @param from - the line's starting point + * @param to - the line's ending point + */ + static Line(from: Point, to: Point): Path; + + /** + * Creates a linear path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Line(object: any): Path; + + /** + * Creates a circular path item. + * @param center - the center point of the circle + * @param radius - the radius of the circle + */ + static Circle(center: Point, radius: number): Path; + + /** + * Creates a circular path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Circle(object: any): Path; + + /** + * Creates a rectangular path item, with optionally rounded corners. + * @param rectangle - the rectangle object describing the geometry of the rectangular path to be created. + * @param radius [optional] - the size of the rounded corners default: null + */ + static Rectangle(rectangle: Rectangle, radius?: number): Path; + + /** + * Creates a rectangular path item from a point and a size object. + * @param point - the rectangle's top-left corner. + * @param size - the rectangle's size. + */ + static Rectangle(point: Point, size: Size): Path; + + /** + * Creates a rectangular path item from the passed points. These do not necessarily need to be the top left and bottom right corners, the constructor figures out how to fit a rectangle between them. + * @param from - the first point defining the rectangle + * @param to - the second point defining the rectangle + */ + static Rectangle(from: Point, to: Point): Path; + + /** + * Creates a rectangular path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Rectangle(object: any): Path; + + /** + * Creates an elliptical path item. + * @param rectangle - the rectangle circumscribing the ellipse + */ + static Ellipse(rectangle: Rectangle): Path; + + /** + * Creates an elliptical path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Ellipse(object: any): Path; + /** + * Creates a circular arc path item + * @param from - the starting point of the circular arc + * @param through - the point the arc passes through + * @param to - the end point of the arc + */ + static Arc(from: Point, through: Point, to: Point): Path; + + /** + * Creates an circular arc path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Arc(object: any): Path; + + /** + * Creates a regular polygon shaped path item. + * @param center - the center point of the polygon + * @param sides - the number of sides of the polygon + * @param radius - the radius of the polygon + */ + static RegularPolygon(center: Point, sides: number, radius: number): Path; + + /** + * Creates a regular polygon shaped path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static RegularPolygon(object: any): Path; + + /** + * Creates a star shaped path item. The largest of radius1 and radius2 will be the outer radius of the star. The smallest of radius1 and radius2 will be the inner radius. + * @param center - the center point of the star + * @param points - the number of points of the star + * @param radius1 + * @param radius2 + */ + static Star(center: Point, points: number, radius1: number, radius2: number): Path; + + /** + * Creates a star shaped path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Star(object: any): Path; + + /** + * Creates a new path item and places it at the top of the active layer. + * @param segments [optional] - An array of segments (or points to be converted to segments) that will be added to the path + */ + constructor(segments?: Segment[]| Point[]); + + /** + * Creates a new path item from an object description and places it at the top of the active layer. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object?: any); + + /** + * Creates a new path item from SVG path-data and places it at the top of the active layer. + * @param pathData - the SVG path-data that describes the geometry of this path. + */ + constructor(pathData?: string); + + /** + * The segments contained within the path. + * Array of Segment objects + */ + segments: Segment[]; + + /** + * The first Segment contained within the path. + * Read only. + */ + firstSegment: Segment; + + /** + * The last Segment contained within the path + * Read only. + */ + lastSegment: Segment; + + /** + * The curves contained within the path. + * Array of Curve objects + */ + curves: Curve[]; + + /** + * The first Curve contained within the path. + * Read only. + */ + firstCurve: Curve; + + /** + * The last Curve contained within the path. + * Read only. + */ + lastCurve: Curve; + + /** + * Specifies whether the path is closed. If it is closed, Paper.js connects the first and last segments. + */ + closed: boolean; + + /** + * The approximate length of the path in points. + * Read only. + */ + length: number; + + /** + * The area of the path in square points. Self-intersecting paths can contain sub-areas that cancel each other out. + * Read only. + */ + area: number; + + /** + * Specifies whether the path and all its segments are selected. Cannot be true on an empty path. + */ + fullySelected: boolean; + + /** + * Specifies whether the path is oriented clock-wise. + */ + clockwise: boolean; + + /** + * Returns a point that is guaranteed to be inside the path. + * Read only. + */ + interiorPoint: Point; + + /** + * Adds one or more segments to the end of the segments array of this path. + * @param segment - the segment or point to be added. + * Returns the added segment. This is not necessarily the same object, e.g. if the segment to be added already belongs to another path. + */ + add(segment: Segment | Point): Segment; + + /** + * Inserts one or more segments at a given index in the list of this path's segments. + * @param index - the index at which to insert the segment. + * @param segment - the segment or point to be inserted. + * Returns the added segment. This is not necessarily the same object, e.g. if the segment to be added already belongs to another path. + */ + insert(index: number, segment: Segment | Point): Segment; + + /** + * Adds an array of segments (or types that can be converted to segments) to the end of the segments array. + * @param segments - Array of Segment objects + * Returns an array of the added segments. These segments are not necessarily the same objects, e.g. if the segment to be added already belongs to another path. + */ + addSegments(segments: Segment[]): Segment[]; + + /** + * Inserts an array of segments at a given index in the path's segments array. + * @param index - the index at which to insert the segments. + * @param segments - the segments to be inserted. + * Returns an array of the added segments. These segments are not necessarily the same objects, e.g. if the segment to be added already belongs to another path. + */ + insertSegments(index: number, segments: Segment[]): Segment[]; + + /** + * Removes the segment at the specified index of the path's segments array. + * @param index - the index of the segment to be removed + * Returns the removed segment + */ + removeSegment(index: number): Segment; + + /** + * Removes all segments from the path's segments array. + * Returns an array containing the removed segments + */ + removeSegments(): Segment[]; + + /** + * Removes the segments from the specified from index to the to index from the path's segments array. + * @param from - the beginning index, inclusive + * @param to [optional = segments.length] - the ending index + * Returns an array containing the removed segments + */ + removeSegments(from: number, to?: number): Segment[]; + + /** + * Converts the curves in a path to straight lines with an even distribution of points. The distance between the produced segments is as close as possible to the value specified by the maxDistance parameter. + * @param maxDistance - the maximum distance between the points + */ + flatten(maxDistance: number): void; + + /** + * Smooths a path by simplifying it. The path.segments array is analyzed and replaced by a more optimal set of segments, reducing memory usage and speeding up drawing. + * @param tolerance [optional = 2.5] - + */ + simplify(tolerance?: number): void; + + /** + * Splits the path at the given offset. After splitting, the path will be open. If the path was open already, splitting will result in two paths. + * @param offset - the offset at which to split the path as a number between 0 and path.length + * Returns the newly created path after splitting, if any + */ + split(offset: number): Path; + + /** + * Splits the path at the given curve location. After splitting, the path will be open. If the path was open already, splitting will result in two paths. + * @param location - the curve location at which to split the path + * Returns the newly created path after splitting, if any + */ + split(location: CurveLocation): Path; + + /** + * Splits the path at the given curve index and parameter. After splitting, the path will be open. If the path was open already, splitting will result in two paths. + * @param index - the index of the curve in the path.curves array at which to split + * @param parameter - the parameter at which the curve will be split + * Returns the newly created path after splitting, if any + */ + split(index: number, parameter: number): Path; + + /** + * Reverses the orientation of the path, by reversing all its segments. + */ + reverse(): void; + + /** + * Joins the path with the specified path, which will be removed in the process. + * @param path - the path to join this path with + * Returns the joined path + */ + join(path: Path): Path; + + /** + * Returns the curve location of the specified point if it lies on the path, null otherwise. + * @param point - the point on the path. + */ + getLocationOf(point: Point): CurveLocation; + + /** + * Returns the length of the path from its beginning up to up to the specified point if it lies on the path, null otherwise. + * @param point - the point on the path. + */ + getOffsetOf(point: Point): number; + + /** + * Returns the curve location of the specified offset on the path. + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + */ + getLocationAt(offset: number, isParameter?: boolean): CurveLocation; + + /** + * Calculates the point on the path at the given offset. Returns the point at the given offset + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + */ + getPointAt(offset: number, isPatameter?: boolean): Point; + + /** + * Calculates the tangent vector of the path at the given offset. Returns the tangent vector at the given offset + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + */ + getTangentAt(offset: number, isPatameter?: boolean): Point; + + /** + * Calculates the normal vector of the path at the given offset. Returns the normal vector at the given offset + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + */ + getNormalAt(offset: number, isParameter?: boolean): Point; + + /** + * Calculates the curvature of the path at the given offset. Curvatures indicate how sharply a path changes direction. A straight line has zero curvature, where as a circle has a constant curvature. The path's radius at the given offset is the reciprocal value of its curvature. + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + * @param point - the point for which we search the nearest location + */ + getCurvatureAt(offset: number, isParameter?: boolean, point?: Point): number; + + /** + * Returns the nearest point on the path to the specified point. + * @param point - the point for which we search the nearest point + */ + getNearestPoint(point: Point): Point; + + + } + /** + * A compound path contains two or more paths, holes are drawn where the paths overlap. All the paths in a compound path take on the style of the backmost path and can be accessed through its item.children list. + */ + export class CompoundPath extends PathItem { + + /** + * Creates a new compound path item from an object description and places it at the top of the active layer. + * @param object - an object literal containing properties to be set on the path + */ + constructor(object: any); + + /** + * Creates a new compound path item from SVG path-data and places it at the top of the active layer. + * @param pathData - the SVG path-data that describes the geometry of this path. + */ + constructor(pathData: string); + + /** + * Specifies whether the compound path is oriented clock-wise. + */ + clockwise: boolean; + + /** + * The first Segment contained within the path. + * Read Only + */ + firstSegment: Segment; + + /** + * The last Segment contained within the path. + * Read Only + */ + lastSegment: Segment; + + /** + * All the curves contained within the compound-path, from all its child Path items. + * Read Only + */ + curves: Curve[]; + + /** + * The first Curve contained within the path. + * Read Only + */ + firstCurve: Curve; + + /** + * The last Curve contained within the path. + * Read only. + */ + lastCurve: Curve; + + /** + * The area of the path in square points. Self-intersecting paths can contain sub-areas that cancel each other out. + * Read Only. + */ + area: number; + + /** + * Reverses the orientation of all nested paths. + */ + reverse(): void; + + } + /** + * The Segment object represents the points of a path through which its Curve objects pass. The segments of a path can be accessed through its path.segments array. + * Each segment consists of an anchor point (segment.point) and optionaly an incoming and an outgoing handle (segment.handleIn and segment.handleOut), describing the tangents of the two Curve objects that are connected by this segment. + */ + export class Segment { + + /** + * Creates a new Segment object. + * @param point [optional] - the anchor point of the segment default: {x: 0, y: 0} + * @param handleIn [optional] - the handle point relative to the anchor point of the segment that describes the in tangent of the segment default: {x: 0, y: 0} + * @param handleOut [optional] - the handle point relative to the anchor point of the segment that describes the out tangent of the segment default: {x: 0, y: 0} + */ + constructor(point?: Point, handleIn?: Point, handleOut?: Point); + + /** + * Creates a new Segment object. + * @param object - an object literal containing properties to be set on the segment. + */ + constructor(object?: any); + + /** + * The anchor point of the segment. + */ + point: Point; + + /** + * The handle point relative to the anchor point of the segment that describes the in tangent of the segment. + */ + handleIn: Point; + + /** + * The handle point relative to the anchor point of the segment that describes the out tangent of the segment. + */ + handleOut: Point; + + /** + * Specifies whether the segment has no handles defined, meaning it connects two straight lines. + */ + linear: boolean; + + /** + * Specifies whether the point of the segment is selected. + */ + selected: boolean; + + /** + * The index of the segment in the path.segments array that the segment belongs to. + * Read Only + */ + index: number; + + /** + * The path that the segment belongs to. + * Read Only + */ + path: Path; + + /** + * The curve that the segment belongs to. For the last segment of an open path, the previous segment is returned. + * Read only. + */ + curve: Curve; + + /** + * The curve location that describes this segment's position ont the path. + * Read Only. + */ + location: CurveLocation; + + /** + * The next segment in the path.segments array that the segment belongs to. If the segments belongs to a closed path, the first segment is returned for the last segment of the path. + * Read Only. + */ + next: Segment; + + /** + * The previous segment in the path.segments array that the segment belongs to. If the segments belongs to a closed path, the last segment is returned for the first segment of the path. + * Read Only. + */ + previous: Segment; + + /** + * Returns true if the the two segments are the beginning of two lines and if these two lines are running parallel. + * @param segment + */ + isColinear(segment: Segment): boolean; + + /** + * Returns true if the segment at the given index is the beginning of an orthogonal arc segment. The code looks at the length of the handles and their relation to the distance to the imaginary corner point. If the relation is kappa, then it's an arc. + */ + isArc(): boolean; + + /** + * Returns the reversed the segment, without modifying the segment itself. + */ + reverse(): Segment; + + /** + * Removes the segment from the path that it belongs to. + */ + remove(): boolean; + + /** + * A string representation of the segment + */ + toString(): string; + + /** + * Transform the segment by the specified matrix. + * @param matrix - the matrix to transform the segment by + */ + transform(matrix: Matrix): void; + + } + /** + * The Curve object represents the parts of a path that are connected by two following Segment objects. The curves of a path can be accessed through its path.curves array. + * While a segment describe the anchor point and its incoming and outgoing handles, a Curve object describes the curve passing between two such segments. Curves and segments represent two different ways of looking at the same thing, but focusing on different aspects. Curves for example offer many convenient ways to work with parts of the path, finding lengths, positions or tangents at given offsets. + */ + export class Curve { + + /** + * Creates a new curve object. + * @param segment1 - + * @param segment2 - + */ + constructor(segment1: Segment, segment2: Segment); + + /** + * Creates a new curve object. + * @param point1: Point + * @param handle1: Point + * @param handle2: Point + * @param point2: Point + */ + constructor(point1: Point, handle1: Point, handle2: Point, point2: Point); + + /** + * The first anchor point of the curve. + */ + point1: Point; + + /** + * The second anchor point of the curve. + */ + point2: Point; + + /** + * The handle point that describes the tangent in the first anchor point. + */ + handle1: Point; + + /** + * The handle point that describes the tangent in the second anchor point. + */ + handle2: Point; + + /** + * The first segment of the curve. + * Read Only. + */ + segment1: Segment; + + /** + * The second segment of the curve. + * Read only. + */ + segment2: Segment; + + /** + * The path that the curve belongs to. + * Read only. + */ + path: Path; + + /** + * The index of the curve in the path.curves array. + * Read Only. + */ + index: number; + + /** + * The next curve in the path.curves array that the curve belongs to. + * Read Only + */ + next: Curve; + + /** + * The previous curve in the path.curves array that the curve belongs to. + * Read Only. + */ + previous: Curve; + + /** + * Specifies whether the points and handles of the curve are selected. + */ + selected: boolean; + + /** + * The approximated length of the curve in points. + * Read Only. + */ + length: number; + + /** + * The bounding rectangle of the curve excluding stroke width. + */ + bounds: Rectangle; + + /** + * The bounding rectangle of the curve including stroke width. + */ + strokeBounds: Rectangle; + + /** + * The bounding rectangle of the curve including handles. + */ + handleBounds: Rectangle; + + /** + * Checks if this curve is linear, meaning it does not define any curve handle. + */ + isLinear(): boolean; + + /** + * TODO? + */ + //isHorizontal(): boolean; + + /** + * Divides the curve into two curves at the given offset. The curve itself is modified and becomes the first part, the second part is returned as a new curve. If the modified curve belongs to a path item, the second part is also added to the path. + * @param offset [optional] - the offset on the curve at which to split, or the curve time parameter if isParameter is true default: 0.5 + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + divide(offset?: number, isParameter?: boolean): Curve; + + /** + * Splits the path this curve belongs to at the given offset. After splitting, the path will be open. If the path was open already, splitting will result in two paths. + * @param offset [optional] - the offset on the curve at which to split, or the curve time parameter if isParameter is true default: 0.5 + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + split(offset?: number, isParameter?: boolean): Path; + + /** + * Returns a reversed version of the curve, without modifying the curve itself. + */ + reverse(): Curve; + + /** + * Removes the curve from the path that it belongs to, by merging its two path segments. + * returns true if the curve was removed, false otherwise + */ + remove(): boolean; + + /** + * Returns a copy of the curve. + */ + clone(): Curve; + + /** + * returns a string representation of the curve + */ + toString(): string; + + /** + * Calculates the curve time parameter of the specified offset on the path, relative to the provided start parameter. If offset is a negative value, the parameter is searched to the left of the start parameter. If no start parameter is provided, a default of 0 for positive values of offset and 1 for negative values of offset. + * @param offset - + * @param start [optional] - + */ + getParameterAt(offset: Point, start?: number): number; + + /** + * Returns the curve time parameter of the specified point if it lies on the curve, null otherwise. + * @param point - the point on the curve. + */ + getParameterOf(point: Point): number; + + /** + * Calculates the curve location at the specified offset or curve time parameter. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + getLocationAt(offset: Point, isParameter?: boolean): CurveLocation; + + /** + * Returns the curve location of the specified point if it lies on the curve, null otherwise. + * @param point - the point on the curve + */ + getLocationOf(point: Point): CurveLocation; + + /** + * Returns the length of the path from its beginning up to up to the specified point if it lies on the path, null otherwise. + * @param point - the point on the path. + */ + getOffsetOf(point: Point): number; + + /** + * Calculates the point on the curve at the given offset. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + getPointAt(offset: number, isParameter?: boolean): Point; + + /** + * Calculates the tangent vector of the curve at the given offset. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + getTangentAt(offset: number, isParameter?: boolean): Point; + + /** + * Calculates the normal vector of the curve at the given offset. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + getNormalAt(offset: number, isParameter?: boolean): Point; + + /** + * Calculates the curvature of the curve at the given offset. Curvatures indicate how sharply a curve changes direction. A straight line has zero curvature, where as a circle has a constant curvature. The curve's radius at the given offset is the reciprocal value of its curvature. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter - pass true if offset is a curve time parameter. default: false + */ + getCurvatureAt(offset: number, isParameter?: boolean): Point; + + } + /** + * CurveLocation objects describe a location on Curve objects, as defined by the curve parameter, a value between 0 (beginning of the curve) and 1 (end of the curve). If the curve is part of a Path item, its index inside the path.curves array is also provided. + * The class is in use in many places, such as path.getLocationAt(offset, isParameter), path.getLocationOf(point), Path#getNearestLocation(point),{@linkPathItem#getIntersections(path), etc. + */ + export class CurveLocation { + + /** + * Creates a new CurveLocation object. + * @param curve - + * @param parameter - + * @param point - + */ + constructor(curve: Curve, parameter: number, point: Point); + + /** + * The segment of the curve which is closer to the described location. + * Read Only + */ + segment: Segment; + + /** + * The curve that this location belongs to. + * Read Only + */ + curve: Curve; + + /** + * The curve location on the intersecting curve, if this location is the result of a call to pathItem.getIntersections(path) / Curve#getIntersections(curve). + * Read Only + */ + intersection: CurveLocation; + + /** + * The path this curve belongs to, if any. + * Read Only + */ + path: Path; + + /** + * The index of the curve within the path.curves list, if the curve is part of a Path item. + * Read Only. + */ + index: number; + + /** + * The length of the path from its beginning up to the location described by this object. If the curve is not part of a path, then the length within the curve is returned instead. + * Read only. + */ + offset: number; + + /** + * The length of the curve from its beginning up to the location described by this object. + * Read Only. + */ + curveOffset: number; + + /** + * The curve parameter, as used by various bezier curve calculations. It is value between 0 (beginning of the curve) and 1 (end of the curve). + * Read only. + */ + parameter: number; + + /** + * The point which is defined by the curve and parameter. + * Read only. + */ + point: Point; + + /** + * The distance from the queried point to the returned location. + * Read Only. + */ + distance: number; + + /** + * Checks whether tow CurveLocation objects are describing the same location on a path, by applying the same tolerances as elsewhere when dealing with curve time parameters. + * @param location CurveLocation + */ + equals(location: CurveLocation): boolean; + + /** + * Returns a string representation of the curve location + */ + toString(): string; + + } + /** + * A Project object in Paper.js is what usually is referred to as the document: The top level object that holds all the items contained in the scene graph. As the term document is already taken in the browser context, it is called Project. + * Projects allow the manipulation of the styles that are applied to all newly created items, give access to the selected items, and will in future versions offer ways to query for items in the scene graph defining specific requirements, and means to persist and load from different formats, such as SVG and PDF. + * The currently active project can be accessed through the paperScope.project variable. + * An array of all open projects is accessible through the paperScope.projects variable. + */ + export class Project { + + /** + * Creates a Paper.js project containing one empty Layer, referenced by project.activeLayer. + * @param element - the HTML canvas element that should be used as the element for the view, or an ID string by which to find the element. + */ + constructor(element: HTMLCanvasElement | string); + + /** + * The reference to the project's view. + * Read only. + */ + view: View; + + /** + * The currently active path style. All selected items and newly created items will be styled with this style. + */ + currentStyle: Style; + + /** + * The index of the project in the paperScope.projects list. + * Read Only + */ + index: number; + + /** + * The layers contained within the project. + */ + layers: Layer[]; + + /** + * The layer which is currently active. New items will be created on this layer by default. + * Read Only. + */ + activeLayer: Layer; + + /** + * The symbols contained within the project. + */ + symbols: Symbol[]; + + /** + * Activates this project, so all newly created items will be placed in it. + */ + activate(): void; + + /** + * Clears the project by removing all project.layers and project.symbols. + */ + clear(): void; + + /** + * Checks whether the project has any content or not. + */ + isEmpty(): boolean; + + /** + * Removes this project from the paperScope.projects list, and also removes its view, if one was defined. + */ + remove(): void; + + /** + * Selects all items in the project. + */ + selectAll(): void; + + /** + * Deselects all selected items in the project. + */ + deselectAll(): void; + + /** + * Perform a hit-test on the items contained within the project at the location of the specified point. + * The options object allows you to control the specifics of the hit-test and may contain a combination of the following values: + * @param point - the point where the hit-test should be performed + * @param options.tolerance -the tolerance of the hit-test in points. Can also be controlled through paperScope.settings.hitTolerance + * @param options.class - only hit-test again a certain item class and its sub-classes: Group, Layer, Path, CompoundPath, Shape, Raster, PlacedSymbol, PointText, etc. + * @param options.fill - hit-test the fill of items. + * @param options.stroke - hit-test the stroke of path items, taking into account the setting of stroke color and width. + * @param options.segments - hit-test for segment.point of Path items. + * @param options.curves - hit-test the curves of path items, without taking the stroke color or width into account. + * @param options.handles - hit-test for the handles. (segment.handleIn / segment.handleOut) of path segments. + * @param options.ends - only hit-test for the first or last segment points of open path items. + * @param options.bounds - hit-test the corners and side-centers of the bounding rectangle of items (item.bounds). + * @param options.center - hit-test the rectangle.center of the bounding rectangle of items (item.bounds). + * @param options.guides - hit-test items that have Item#guide set to true. + * @param options.selected - only hit selected items. + */ + hitTest(point: Point, options?: { tolerance?: number; class?: string; fill?: boolean; stroke?: boolean; segments?: boolean; curves?: boolean; handles?: boolean; ends?: boolean; bounds?: boolean; center?: boolean; guides?: boolean; selected?: boolean; }): HitResult; + + /** + * Fetch items contained within the project whose properties match the criteria in the specified object. + * Extended matching is possible by providing a compare function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data. + * Matching items against a rectangular area is also possible, by setting either match.inside or match.overlapping to a rectangle describing the area in which the items either have to be fully or partly contained. + */ + getItems(match: any): Item[]; + + /** + * Fetch the first item contained within the project whose properties match the criteria in the specified object. + * Extended matching is possible by providing a compare function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data. + */ + getItem(match: any): Item; + + /** + * Exports (serializes) the project with all its layers and child items to a JSON data string. + * @param options [optional] - default {asString: true, precision: 5} + * @param options.asString - whether the JSON is returned as a Object or a String. + * @param options.precision - the amount of fractional digits in numbers used in JSON data. + */ + exportJSON(options?: { asString?: boolean; precision?: number }): string; + + /** + * Imports (deserializes) the stored JSON data into the project. + * Note that the project is not cleared first. You can call project.clear() to do so. + */ + importJSON(json: string): void; + + /** + * Exports the project with all its layers and child items as an SVG DOM, all contained in one top level SVG group node. + * @param options [optional] the export options, default: { asString: false, precision: 5, matchShapes: false } + * @param options.asString - whether a SVG node or a String is to be returned. + * @param options.precision - the amount of fractional digits in numbers used in SVG data. + * @param options.matchShapes - whether path items should tried to be converted to shape items, if their geometries can be made to match + */ + exportSVG(options?: { asString?: boolean; precision?: number; matchShapes?: boolean }): SVGElement; + + /** + * Converts the provided SVG content into Paper.js items and adds them to the active layer of this project. + * Note that the project is not cleared first. You can call project.clear() to do so. + * @param svg - the SVG content to import + * @param options [optional] - the import options, default: { expandShapes: false } + * @param options.expandShapes - whether imported shape items should be expanded to path items. + */ + importSVG(svg: SVGElement | string, options?: any): Item; + + } + /** + * Symbols allow you to place multiple instances of an item in your project. This can save memory, since all instances of a symbol simply refer to the original item and it can speed up moving around complex objects, since internal properties such as segment lists and gradient positions don't need to be updated with every transformation. + */ + export class Symbol { + + /** + * Creates a Symbol item. + * @param item - the source item which is copied as the definition of the symbol + * @param dontCenter [optional] - default: false + */ + constructor(item: Item, dontCenter?: boolean); + + /** + * The project that this symbol belongs to. + * Read Only. + */ + project: Project; + + /** + * The symbol definition. + */ + definition: Item; + + /** + * Places in instance of the symbol in the project. + * @param position [optional] - The position of the placed symbol. + */ + place(position?: Point): PlacedSymbol; + + /** + * Returns a copy of the symbol. + */ + clone(): Symbol; + + } + /** + * Style is used for changing the visual styles of items contained within a Paper.js project and is returned by item.style and project.currentStyle. + * All properties of Style are also reflected directly in Item, i.e.: item.fillColor. + * To set multiple style properties in one go, you can pass an object to item.style. This is a convenient way to define a style once and apply it to a series of items: + */ + export class Style { + + /** + * The view that this style belongs to. + * Read only. + */ + view: View; + + /** + * The color of the stroke. + */ + strokeColor: Color | string; + + /** + * The width of the stroke. + */ + strokeWidth: number; + + /** + * The shape to be used at the beginning and end of open Path items, when they have a stroke. + * String('round', 'square', 'butt' + */ + strokeCap: string; + + /** + * The shape to be used at the segments and corners of Path items when they have a stroke. + * String('miter', 'round', 'bevel') + */ + strokeJoin: string; + + /** + * Specifies whether the stroke is to be drawn taking the current affine transformation into account (the default behavior), or whether it should appear as a non-scaling stroke. + */ + strokeScaling: boolean; + + /** + * The dash offset of the stroke. + */ + dashOffset: number; + + /** + * Specifies an array containing the dash and gap lengths of the stroke. + */ + dashArray: number[]; + + /** + * The miter limit of the stroke. When two line segments meet at a sharp angle and miter joins have been specified for strokeJoin, it is possible for the miter to extend far beyond the strokeWidth of the path. The miterLimit imposes a limit on the ratio of the miter length to the strokeWidth. + */ + miterLimit: number; + + /** + * The fill color. + */ + fillColor: Color | string; + + /** + * The shadow color. + */ + shadowColor: Color | string; + + /** + * The shadow's blur radius. + */ + shadowBlur: number; + + /** + * The shadow's offset. + */ + shadowOffset: Point; + + /** + * The color the item is highlighted with when selected. If the item does not specify its own color, the color defined by its layer is used instead. + */ + selectedColor: Color | string; + + /** + * The font-family to be used in text content. default 'sans-serif' + */ + fontFamily: string; + + /** + * The font-weight to be used in text content. + */ + fontWeight: string | number; + + /** + * The font size of text content, as {@Number} in pixels, or as {@String} with optional units 'px', 'pt' and 'em'. + */ + fontSize: string | number; + + /** + * The text leading of text content. + */ + leading: number | string; + + /** + * The justification of text paragraphs. default "left" + */ + justification: string; + + } + export interface IHSBColor { + + /** + * the hue of the color as a value in degrees between 0 and 360 + */ + hue?: number; + /** + * the saturation of the color as a value between 0 and 1 + */ + saturation?: number; + /** + * the brightness of the color as a value between 0 and 1 + */ + brightness?: number; + /** + * the alpha of the color as a value between 0 and 1 + */ + alpha?: number; + + } + export interface IHSLColor { + + /** + * the hue of the color as a value in degrees between 0 and 360 + */ + hue?: number; + /** + * the saturation of the color as a value between 0 and 1 + */ + saturation?: number; + /** + * the brightness of the color as a value between 0 and 1 + */ + lightness?: number; + /** + * the alpha of the color as a value between 0 and 1 + */ + alpha?: number; + + } + export interface IGradientColor { + /** + * the gradient object that describes the color stops and type of gradient to be used. + */ + gradient?: Gradient; + /** + * the origin point of the gradient + */ + origin?: Point; + /** + * the destination point of the gradient stops: Array of GradientStop - the gradient stops describing the gradient, as an alternative to providing a gradient object + */ + destination?: Point; + /** + * controls whether the gradient is radial, as an alternative to providing a gradient object + */ + radial?: boolean; + } + /** + * All properties and functions that expect color values in the form of instances of Color objects, also accept named colors and hex values as strings which are then converted to instances of Color internally. + */ + export class Color { + + /** + * Creates a RGB Color object. + * @param red - the amount of red in the color as a value between 0 and 1 + * @param green - the amount of green in the color as a value between 0 and 1 + * @param blue - the amount of blue in the color as a value between 0 and 1 + * @param alpha [optional] - the alpha of the color as a value between 0 and 1 + */ + constructor(red: number, green: number, blue: number, alpha?: number); + + /** + * Creates a gray Color object. + * @param gray - the amount of gray in the color as a value between 0 and 1 + * @param alpha [optional] - the alpha of the color as a value between 0 and 1 + */ + constructor(gray: number, alpha?: number); + + /** + * Creates a HSB, HSL or gradient Color object from the properties of the provided object: + * @param object - an object describing the components and properties of the color. + */ + constructor(object: IHSBColor | IHSLColor | IGradientColor); + + /** + * Creates a gradient Color object. + * @param gradient - + * @param origin - + * @param destination - + * @param highlight [optional] - + */ + constructor(color: Gradient, origin: Point, destination: Point, highlight?: Point); + + /** + * The type of the color as a string. + * String('rgb', 'gray', 'hsb', 'hsl') + */ + type: string; + + /** + * The color components that define the color, including the alpha value if defined. + * Read Only. + */ + components: number; + + /** + * The color's alpha value as a number between 0 and 1. + * All colors of the different subclasses support alpha values. + */ + alpha: number; + + /** + * The amount of red in the color as a value between 0 and 1. + */ + red: number; + + /** + * The amount of green in the color as a value between 0 and 1. + */ + green: number; + + /** + * The amount of blue in the color as a value between 0 and 1. + */ + blue: number; + + /** + * The amount of gray in the color as a value between 0 and 1. + */ + gray: number; + + /** + * The hue of the color as a value in degrees between 0 and 360. + */ + hue: number; + + /** + * The saturation of the color as a value between 0 and 1. + */ + saturation: number; + + /** + * The brightness of the color as a value between 0 and 1. + */ + brightness: number; + + /** + * The lightness of the color as a value between 0 and 1. + * Note that all other components are shared with HSB. + */ + lightness: number; + + /** + * The gradient object describing the type of gradient and the stops. + */ + gradient: Gradient; + + /** + * The highlight point of the gradient. + */ + highlight: Point; + + /** + * Converts the color another type. + * @param type - String('rgb'|'gray'|'hsb'|'hsl') the color type to convert to. + */ + convert(type: string): Color; + + /** + * Checks if the color has an alpha value. + */ + hasAlpha(): boolean; + + /** + * Checks if the component color values of the color are the same as those of the supplied one. + * @param color - the color to compare with + */ + equals(color: Color): boolean; + + /** + * a copy of the color object + */ + clone(): Color; + + /** + * a string representation of the color + */ + toString(): string; + + /** + * Returns the color as a CSS string. + * @param hex - whether to return the color in hexadecial representation or as a CSS RGB / RGBA string. + */ + toCSS(hex: boolean): string; + + /** + * Transform the gradient color by the specified matrix. + * @param matrix - the matrix to transform the gradient color by + */ + transform(matrix: Matrix): void; + + } + /** + * The Gradient object. + */ + export class Gradient { + + /** + * The gradient stops on the gradient ramp. + */ + stops: GradientStop[]; + + /** + * Specifies whether the gradient is radial or linear. + */ + radial: boolean; + + /** + * a copy of the gradient + */ + clone(): Gradient; + + /** + * Checks whether the gradient is equal to the supplied gradient. + * @param gradient - the gradient to check against + */ + equals(gradient: Gradient): boolean; + + } + /** + * The GradientStop object. + */ + export class GradientStop { + + /** + * Creates a GradientStop object. + * @param color [optional] - the color of the stop, default: new Color(0, 0, 0) + * @param rampPoint [optional] - the position of the stop on the gradient ramp as a value between 0 and 1, default: 0 + */ + constructor(color?: Color, rampPoint?: number); + + /** + * The ramp-point of the gradient stop as a value between 0 and 1. + */ + rampPoint: number; + + /** + * The color of the gradient stop. + */ + color: Color; + + /** + * Returns a copy of the gradient-stop + */ + clone(): GradientStop; + + } + /** + * The View object wraps an HTML element and handles drawing and user interaction through mouse and keyboard for it. It offer means to scroll the view, find the currently visible bounds in project coordinates, or the center, both useful for constructing artwork that should appear centered on screen. + */ + export class View { + + /** + * The underlying native element. + * Read Only. + */ + element: HTMLCanvasElement; + + /** + * The ratio between physical pixels and device-independent pixels (DIPs) of the underlying canvas / device. + * It is 1 for normal displays, and 2 or more for high-resolution displays. + * Read only. + */ + pixelRatio: number; + + /** + * The resoltuion of the underlying canvas / device in pixel per inch (DPI). + * It is 72 for normal displays, and 144 for high-resolution displays with a pixel-ratio of 2. + * Read only. + */ + resolution: number; + + /** + * The size of the view. Changing the view's size will resize it's underlying element. + */ + viewSize: Size; + + /** + * The bounds of the currently visible area in project coordinates. + * Read only. + */ + bounds: Rectangle; + + /** + * The size of the visible area in project coordinates. + * Read only. + */ + size: Size; + + /** + * The center of the visible area in project coordinates. + */ + center: Point; + + /** + * The zoom factor by which the project coordinates are magnified. + */ + zoom: number; + + /** + * Handler function to be called on each frame of an animation. + * The function receives an event object which contains information about the frame event: + */ + onFrame: (event: IFrameEvent) => void; + + /** + * Handler function that is called whenever a view is resized. + */ + onResize: (event: Event) => void; + + /** + * Removes this view from the project and frees the associated element. + */ + remove(): void; + + /** + * Checks whether the view is currently visible within the current browser viewport. + */ + isVisible(): boolean; + + /** + * Scrolls the view by the given vector. + * @param point - the vector to scroll by + */ + scrollBy(point: Point): void; + + /** + * Makes all animation play by adding the view to the request animation loop. + */ + play(): void; + + /** + * Makes all animation pause by removing the view to the request animation loop. + */ + pause(): void; + + /** + * Updates the view if there are changes. Note that when using built-in event hanlders for interaction, animation and load events, this method is invoked for you automatically at the end. + */ + update(): void; + + /** + * + * @param point - + */ + projectToView(point: Point): Point; + + /** + * + * @param point - + */ + viewToProject(point: Point): Point; + + //I cannot use function: Function as it is a reserved keyword + + /** + * Attach an event handler to the view. + * @param type - String('frame'|'resize') the event type + * @param function - The function to be called when the event occurs + */ + on(type: string, callback: (event: Event) => void): Item; + + /** + * Attach one or more event handlers to the view. + */ + on(param: any): Item; + + /** + * Detach an event handler from the view. + * @param type - String('frame'|'resize') the event type + * @param function - The function to be detached + */ + off(type: string, callback: (event: Event) => void): Item; + + /** + * Detach one or more event handlers from the view. + * @param param - an object literal containing one or more of the following properties: frame, resize + */ + off(param: any): Item; + + /** + * Emit an event on the view. + * @param type - String('frame'|'resize') the event type + * @param event - an object literal containing properties describing the event. + */ + emit(type: string, event: any): boolean; + + /** + * Check if the view has one or more event handlers of the specified type. + * @param type - String('frame'|'resize') the event type + */ + responds(type: string): boolean; + + /** + * Draws the view when using paper.js directly in JavaScript + */ + draw(): void; + + } + /** + * The Tool object refers to a script that the user can interact with by using the mouse and keyboard and can be accessed through the global tool variable. All its properties are also available in the paper scope. + * The global tool variable only exists in scripts that contain mouse handler functions (onMouseMove, onMouseDown, onMouseDrag, onMouseUp) or a keyboard handler function (onKeyDown, onKeyUp). + */ + export class Tool { + + /** + * The minimum distance the mouse has to drag before firing the onMouseDrag event, since the last onMouseDrag event. + */ + minDistance: number; + + /** + * The maximum distance the mouse has to drag before firing the onMouseDrag event, since the last onMouseDrag event. + */ + maxDistance: number; + + /** + * + */ + fixedDistance: number; + + /** + * The function to be called when the mouse button is pushed down. The function receives a ToolEvent object which contains information about the mouse event. + */ + onMouseDown: (event: ToolEvent) => void; + + /** + * The function to be called when the mouse position changes while the mouse is being dragged. The function receives a ToolEvent object which contains information about the mouse event. + */ + onMouseDrag: (event: ToolEvent) => void; + + /** + * The function to be called the mouse moves within the project view. The function receives a ToolEvent object which contains information about the mouse event. + */ + onMouseMove: (event: ToolEvent) => void; + + /** + * The function to be called when the mouse button is released. The function receives a ToolEvent object which contains information about the mouse event. + */ + onMouseUp: (event: ToolEvent) => void; + + /** + * The function to be called when the user presses a key on the keyboard. + * The function receives a KeyEvent object which contains information about the keyboard event. + * If the function returns false, the keyboard event will be prevented from bubbling up. This can be used for example to stop the window from scrolling, when you need the user to interact with arrow keys. + */ + onKeyDown: (event: KeyEvent) => void; + + /** + * The function to be called when the user releases a key on the keyboard. + * The function receives a KeyEvent object which contains information about the keyboard event. + * If the function returns false, the keyboard event will be prevented from bubbling up. This can be used for example to stop the window from scrolling, when you need the user to interact with arrow keys. + */ + onKeyUp: (event: KeyEvent) => void; + + /** + * Activates this tool, meaning paperScope.tool will point to it and it will be the one that recieves mouse events. + */ + activate(): void; + + /** + * Removes this tool from the paperScope.tools list. + */ + remove(): void; + + //I cannot use function: Function as it is a reserved keyword + + /** + * Attach an event handler to the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be called when the event occurs + */ + on(type: string, callback: (event: ToolEvent) => void): Tool; + + /** + * Attach one or more event handlers to the tool. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + on(param: any): Tool; + + /** + * Detach an event handler from the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be detached + */ + off(type: string, callback: (event: ToolEvent) => void): Tool; + + /** + * Detach one or more event handlers from the tool. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + off(param: any): Tool; + + /** + * Emit an event on the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param event - an object literal containing properties describing the event. + */ + emit(type: string, event: any): boolean; + + /** + * Check if the tool has one or more event handlers of the specified type. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + */ + responds(type: string): boolean; + + } + export class Event { + + /** + * Read Only + */ + modifiers: any; + + } + /** + * ToolEvent The ToolEvent object is received by the Tool's mouse event handlers tool.onMouseDown, tool.onMouseDrag, tool.onMouseMove and tool.onMouseUp. The ToolEvent object is the only parameter passed to these functions and contains information about the mouse event. + */ + export class ToolEvent extends Event { + + /** + * The type of tool event. + * String('mousedown', 'mouseup', 'mousemove', 'mousedrag') + */ + type: string; + + /** + * The position of the mouse in project coordinates when the event was fired. + */ + point: Point; + + /** + * The position of the mouse in project coordinates when the previous event was fired. + */ + lastPoint: Point; + + /** + * The position of the mouse in project coordinates when the mouse button was last clicked. + */ + downPoint: Point; + + /** + * The point in the middle between lastPoint and point. This is a useful position to use when creating artwork based on the moving direction of the mouse, as returned by delta. + */ + middlePoint: Point; + + /** + * The difference between the current position and the last position of the mouse when the event was fired. In case of the mouseup event, the difference to the mousedown position is returned. + */ + delta: Point; + + /** + * The number of times the mouse event was fired. + */ + count: number; + + /** + * The item at the position of the mouse (if any). If the item is contained within one or more Group or CompoundPath items, the most top level group or compound path that it is contained within is returned. + */ + item: Item; + + /** + * a string representation of the tool event + */ + toString(): string; + + } + export class Key { + + /** + * Checks whether the specified key is pressed. + * @param key - One of: 'backspace', 'enter', 'shift', 'control', 'option', 'pause', 'caps-lock', 'escape', 'space', 'end', 'home', 'left', 'up', 'right', 'down', 'delete', 'command' + */ + static isDown(key: string): boolean; + + } + /** + * The KeyEvent object is received by the Tool's keyboard handlers tool.onKeyDown, tool.onKeyUp. The KeyEvent object is the only parameter passed to these functions and contains information about the keyboard event. + */ + export class KeyEvent extends Event { + + /** + * The type of key event. + * String('keydown', 'keyup') + */ + type: string; + + /** + * The string character of the key that caused this key event. + */ + character: string; + + /** + * The key that caused this key event. + */ + key: string; + + /** + * a string representation of the key event + */ + toString(): string; + + } + /** + * The TextItem type allows you to create typography. Its functionality is inherited by different text item types such as PointText, and AreaText (coming soon). They each add a layer of functionality that is unique to their type, but share the underlying properties and functions that they inherit from TextItem. + */ + export class TextItem extends Item { + + /** + * The text contents of the text item. + */ + content: string; + + /** + * The font-family to be used in text content. + */ + fontFamily: string; + + /** + * The font-weight to be used in text content. + */ + fontWeight: string | number; + + /** + * The font size of text content, as {@Number} in pixels, or as {@String} with optional units 'px', 'pt' and 'em'. + */ + fontSize: string | number; + + /** + * The text leading of text content. + */ + leading: string | number; + + /** + * The justification of text paragraphs. + * String('left', 'right', 'center') + */ + justification: string; + + } + /** + * A PointText item represents a piece of typography in your Paper.js project which starts from a certain point and extends by the amount of characters contained in it. + */ + export class PointText extends TextItem { + + /** + * Creates a point text item + * @param point - the position where the text will start + */ + constructor(point: Point); + + /** + * Creates a point text item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object: any); + + /** + * The PointText's anchor point + */ + point: Point; + + } + +} diff --git a/paper/paper-tests.ts b/paper/paper-tests.ts new file mode 100644 index 00000000000000..39d015db87b4e2 --- /dev/null +++ b/paper/paper-tests.ts @@ -0,0 +1,36 @@ +import paper = require('paper'); + +var canvas = document.createElement('canvas') + +paper.setup(canvas); + +// Circle +var path = paper.Path.Circle({ + center: [80, 50], + radius: 35, + fillColor: 'red' +}); + +// Dotted Line Tool +var dottedLinePath: paper.Path; +var dottedLineTool = new paper.Tool(); + +dottedLineTool.onMouseDown = function(event: any) { + new paper.Layer().activate(); + dottedLinePath = new paper.Path(); + dottedLinePath.strokeColor = '#00'; + dottedLinePath.strokeWidth = 2; + dottedLinePath.dashArray = [5, 8]; + dottedLinePath.strokeCap = 'round'; + dottedLinePath.strokeJoin = 'round'; + dottedLinePath.add(event.point); +}; + +dottedLineTool.onMouseDrag = function(event: any) { + dottedLinePath.add(event.point); +}; + +dottedLineTool.onMouseUp = function(event: any) { + dottedLinePath.smooth(); + dottedLinePath.simplify(); +}; diff --git a/paper/tsconfig.json b/paper/tsconfig.json new file mode 100644 index 00000000000000..f6f1f92fb074d8 --- /dev/null +++ b/paper/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "paper-tests.ts" + ] +} \ No newline at end of file diff --git a/pegjs/index.d.ts b/pegjs/index.d.ts index cf375cd32cf97f..722153038b0c01 100644 --- a/pegjs/index.d.ts +++ b/pegjs/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for PEG.js +// Type definitions for PEG.js v0.10.0 // Project: http://pegjs.org/ -// Definitions by: vvakame , Tobias Kahlert +// Definitions by: vvakame , Tobias Kahlert , C.J. Bell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace PEG { @@ -61,19 +61,70 @@ export interface Parser { SyntaxError: any; } -export interface BuildOptions { - cache?: boolean; +export interface BuildOptionsBase { + /** rules the parser will be allowed to start parsing from (default: the first rule in the grammar) */ allowedStartRules?: string[]; - optimize?: string; + /** if `true`, makes the parser cache results, avoiding exponential parsing time in pathological cases but making the parser slower (default: `false`) */ + cache?: boolean; + /** selects between optimizing the generated parser for parsing speed (`"speed"`) or code size (`"size"`) (default: `"speed"`) */ + optimize?: "speed" | "size"; + /** plugins to use */ plugins?: any[]; + /** makes the parser trace its progress (default: `false`) */ + trace?: boolean +} + +export interface ParserBuildOptions extends BuildOptionsBase { + /** if set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ + output?: "parser" +} + +export interface OutputFormatAmdCommonjs extends BuildOptionsBase { + /** if set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ + output: "source"; + /** format of the genreated parser (`"amd"`, `"bare"`, `"commonjs"`, `"globals"`, or `"umd"`); valid only when `output` is set to `"source"` (default: `"bare"`) */ + format: "amd" | "commonjs"; + /** parser dependencies, the value is an object which maps variables used to access the dependencies in the parser to module IDs used to load them; valid only when `format` is set to `"amd"`, `"commonjs"`, or `"umd"` (default: `{}`) */ + dependencies?: any +} + +export interface OutputFormatUmd extends BuildOptionsBase { + /** if set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ + output: "source"; + /** format of the genreated parser (`"amd"`, `"bare"`, `"commonjs"`, `"globals"`, or `"umd"`); valid only when `output` is set to `"source"` (default: `"bare"`) */ + format: "umd"; + /** parser dependencies, the value is an object which maps variables used to access the dependencies in the parser to module IDs used to load them; valid only when `format` is set to `"amd"`, `"commonjs"`, or `"umd"` (default: `{}`) */ + dependencies?: any + /** name of a global variable into which the parser object is assigned to when no module loader is detected; valid only when `format` is set to `"globals"` or `"umd"` (default: `null`) */ + exportVar?: any +} + +export interface OutputFormatGlobals extends BuildOptionsBase { + /** if set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ + output: "source"; + /** format of the genreated parser (`"amd"`, `"bare"`, `"commonjs"`, `"globals"`, or `"umd"`); valid only when `output` is set to `"source"` (default: `"bare"`) */ + format: "globals"; + /** name of a global variable into which the parser object is assigned to when no module loader is detected; valid only when `format` is set to `"globals"` or `"umd"` (default: `null`) */ + exportVar?: any } -export interface OutputBuildOptions extends BuildOptions { - output?: string; +export interface OutputFormatBare extends BuildOptionsBase { + /** if set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ + output: "source"; + /** format of the genreated parser (`"amd"`, `"bare"`, `"commonjs"`, `"globals"`, or `"umd"`); valid only when `output` is set to `"source"` (default: `"bare"`) */ + format?: "bare" } -export function buildParser(grammar: string, options?: BuildOptions): Parser; -export function buildParser(grammar: string, options?: OutputBuildOptions): Parser | string; +/** Returns a generated parser object. It will throw an exception if the grammar is invalid. The exception will contain `message` property with more details about the error. */ +export function generate(grammar: string, options?: ParserBuildOptions): Parser; +/** Returns the generated source code as a `string`. It will throw an exception if the grammar is invalid. The exception will contain `message` property with more details about the error. */ +export function generate(grammar: string, options: OutputFormatAmdCommonjs): string; +/** Returns the generated source code as a `string`. It will throw an exception if the grammar is invalid. The exception will contain `message` property with more details about the error. */ +export function generate(grammar: string, options: OutputFormatUmd): string; +/** Returns the generated source code as a `string`. It will throw an exception if the grammar is invalid. The exception will contain `message` property with more details about the error. */ +export function generate(grammar: string, options: OutputFormatGlobals): string; +/** Returns the generated source code as a `string`. It will throw an exception if the grammar is invalid. The exception will contain `message` property with more details about the error. */ +export function generate(grammar: string, options: OutputFormatBare): string; export namespace parser { type SyntaxError = PegjsError; diff --git a/pegjs/pegjs-tests.ts b/pegjs/pegjs-tests.ts index 74f74ae80ffae6..267a64b060f713 100644 --- a/pegjs/pegjs-tests.ts +++ b/pegjs/pegjs-tests.ts @@ -6,7 +6,7 @@ import * as pegjs from 'pegjs'; } { - let pegparser: pegjs.Parser = pegjs.buildParser("start = ('a' / 'b')+"); + let pegparser: pegjs.Parser = pegjs.generate("start = ('a' / 'b')+"); try { let result: string = pegparser.parse("abba"); @@ -18,7 +18,7 @@ import * as pegjs from 'pegjs'; } { - let parser = pegjs.buildParser("A = 'test'", { + let parser = pegjs.generate("A = 'test'", { cache: true, allowedStartRules: ["A"], optimize: "speed", @@ -27,7 +27,7 @@ import * as pegjs from 'pegjs'; } try { - let parserOrSource: pegjs.Parser | string = pegjs.buildParser("A = 'test'", {output: "source"}); + let source: string = pegjs.generate("A = 'test'", {output: "source"}); } catch (error) { if (error instanceof pegjs.GrammarError) { let e: pegjs.GrammarError = error; diff --git a/pixi.js/index.d.ts b/pixi.js/index.d.ts index a344cb02fecbd1..6e8640e91cc4f8 100644 --- a/pixi.js/index.d.ts +++ b/pixi.js/index.d.ts @@ -1106,7 +1106,7 @@ declare namespace PIXI { static uuid(): number; static hex2rgb(hex: number, out?: number[]): number[]; - static hex2String(hex: number): string; + static hex2string(hex: number): string; static rgb2hex(rgb: Number[]): number; static canUseNewCanvasBlendModel(): boolean; static getNextPowerOfTwo(number: number): number; diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index c40bdc1bd2721a..329560d6f77a3b 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -461,7 +461,7 @@ namespace basics { var style: PIXI.TextStyle = { font: '36px Arial bold italic', - fill: '#F7EDCA', + fill: PIXI.utils.hex2string(0xF7EDCA), stroke: '#4a1850', strokeThickness: 5, dropShadow: true, diff --git a/polymer/index.d.ts b/polymer/index.d.ts index c4321bc07db4e7..65217fd12f9dff 100644 --- a/polymer/index.d.ts +++ b/polymer/index.d.ts @@ -7,7 +7,7 @@ declare namespace polymer { - type PropConstructorType = StringConstructor|ObjectConstructor|BooleanConstructor|NumberConstructor|DateConstructor|ArrayConstructor; + type PropConstructorType = StringConstructor | ObjectConstructor | BooleanConstructor | NumberConstructor | DateConstructor | ArrayConstructor; interface PropObjectType { type: PropConstructorType; @@ -292,25 +292,42 @@ declare namespace polymer { } interface Settings { + hasNativeCSSProperties: boolean + hasNativeImports: boolean + hasShadow: boolean + nativeShadow: boolean + useNativeCSSProperties: boolean + useNativeCustomElements: boolean + useNativeImports: boolean + useNativeShadow: boolean + usePolyfillProto: boolean + useShadow: boolean + wantShadow: boolean + } - wantShadow:boolean; - hasShadow:boolean; - nativeShadow:boolean; - useShadow:boolean; - useNativeShadow:boolean; - useNativeImports:boolean; - useNativeCustomElements:boolean; + interface RenderStatus { + afterNextRender(element: Element, fn: Function, args?: any): void; + hasRendered(): boolean; + whenReady(cb: Function): void; } - interface PolymerStatic { + interface ImportStatus extends RenderStatus { + whenLoaded(cb: Function): void; + } + interface PolymerStatic { Settings: Settings; - dom:DomApiStatic; + dom: DomApiStatic; + + (prototype: Base | { new (): Base }): webcomponents.CustomElementConstructor; + + Class(prototype: Base | { new (): Base }): webcomponents.CustomElementConstructor; - (prototype: Base|{new ():Base}):webcomponents.CustomElementConstructor; + RenderStatus: RenderStatus - Class(prototype: Base|{new ():Base}):webcomponents.CustomElementConstructor; + /** @deprecated */ + ImportStatus: ImportStatus } } diff --git a/prompt-sync-history/index.d.ts b/prompt-sync-history/index.d.ts new file mode 100644 index 00000000000000..09ac3af5b34844 --- /dev/null +++ b/prompt-sync-history/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for prompt-sync-history 1.0.1 +// Project: https://github.com/davidmarkclements/prompt-sync-history +// Definitions by: TANAKA Koichi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import {History} from 'prompt-sync'; + +declare namespace history {} +declare function history(file?:string, max?:number): History; + +export = history; diff --git a/prompt-sync-history/prompt-sync-history-tests.ts b/prompt-sync-history/prompt-sync-history-tests.ts new file mode 100644 index 00000000000000..40b00f2270daea --- /dev/null +++ b/prompt-sync-history/prompt-sync-history-tests.ts @@ -0,0 +1,8 @@ +import * as promptHistory from 'prompt-sync-history'; +import * as PromptSync from 'prompt-sync'; + +let history:PromptSync.History; + +history = promptHistory(); +history = promptHistory('/path/to/file'); +history = promptHistory(null, 1000); diff --git a/prompt-sync-history/tsconfig.json b/prompt-sync-history/tsconfig.json new file mode 100644 index 00000000000000..708d0e40c7b6d2 --- /dev/null +++ b/prompt-sync-history/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prompt-sync-history-tests.ts" + ] +} \ No newline at end of file diff --git a/prompt-sync/index.d.ts b/prompt-sync/index.d.ts new file mode 100644 index 00000000000000..baefafcf850c39 --- /dev/null +++ b/prompt-sync/index.d.ts @@ -0,0 +1,73 @@ +// Type definitions for prompt-sync 4.1.4 +// Project: https://github.com/0x00A/prompt-sync +// Definitions by: TANAKA Koichi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace PromptSync { + export interface Prompt { + + (opts: Option): string; + (ask: string): string; + (ask: string, opts: Option): string; + (ask: string, value: string): string; + /** + * prompt -- sync function for reading user input from stdin + * @param {String} ask opening question/statement to prompt for + * @param {String} value initial value for the prompt + * @param {Object} opts { + * echo: set to a character to be echoed, default is '*'. Use '' for no echo + * value: {String} initial value for the prompt + * ask: {String} opening question/statement to prompt for, does not override ask param + * autocomplete: {StringArray} function({String}) + * } + * + * @returns {string} Returns the string input or (if sigint === false) + * null if user terminates with a ^C + */ + (ask: string, value: string, opts: Option): string; + + hide(ask: string): string; + } + + export interface Option { + ask?: string; + echo?: string; + autocomplete?: AutoCompleteFunction; + value?: string; + } + + export interface Config { + sigint?: boolean; + autocomplete?: AutoCompleteFunction; + history?: History; + } + + export interface History { + atStart(): boolean; + atPenultimate(): boolean; + pastEnd(): boolean; + atEnd(): boolean; + prev(): string; + next(): string; + reset(): void; + push(str: string): void; + save(): void; + } + + export interface AutoCompleteFunction { + (input: string): string[]; + } +} + +/** + * create -- sync function for reading user input from stdin + * @param {Object} config { + * sigint: {Boolean} exit on ^C + * autocomplete: {StringArray} function({String}) + * history: {String} a history control object (see `prompt-sync-history`) + * } + * @returns {Function} prompt function + */ +declare function PromptSync(config?: PromptSync.Config): PromptSync.Prompt; + +export = PromptSync; diff --git a/prompt-sync/prompt-sync-tests.ts b/prompt-sync/prompt-sync-tests.ts new file mode 100644 index 00000000000000..2c803e0a492845 --- /dev/null +++ b/prompt-sync/prompt-sync-tests.ts @@ -0,0 +1,52 @@ +import * as promptSync from 'prompt-sync'; + +declare const history: promptSync.History; + +let prompt: promptSync.Prompt; + +// without config +prompt = promptSync(); + +// with config +prompt = promptSync({ + history: history, + sigint: false, + autocomplete: (input:string) => [input] +}); + +// with empty config +prompt = promptSync({}); + +let name:string = prompt('Enter name: '); +let nickname:string = prompt({ask: 'Enter nickname: ', value: 'N/A'}); +let gender:string = prompt('Enter gender: ', { autocomplete: complete(['male', 'female']) }); +let age:string = prompt('Enter age: ', '18', { echo: '*' }); +let password:string = prompt.hide('Enter password: '); +let anotherPassword:string = prompt('Enter another password: ', { echo: '', value: '*password*'}); + +function complete(commands: string[]) { + return function (str: string) { + const ret:string[] = []; + for (let i=0; i< commands.length; i++) { + if (commands[i].indexOf(str) == 0) + ret.push(commands[i]); + } + return ret; + }; +} + +// History interface +let bool: boolean; + +bool = history.atStart(); +bool = history.atPenultimate(); +bool = history.pastEnd(); +bool = history.atEnd(); + +let str: string; +str = history.prev(); +str = history.next(); + +history.reset(); +history.push('aaa'); +history.save(); diff --git a/prompt-sync/tsconfig.json b/prompt-sync/tsconfig.json new file mode 100644 index 00000000000000..91e09a0edea800 --- /dev/null +++ b/prompt-sync/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prompt-sync-tests.ts" + ] +} \ No newline at end of file diff --git a/quill/index.d.ts b/quill/index.d.ts index df50e16937cb82..1a159d44070980 100644 --- a/quill/index.d.ts +++ b/quill/index.d.ts @@ -1,13 +1,29 @@ // Type definitions for Quill -// Project: http://quilljs.com +// Project: https://github.com/quilljs/quill/ // Definitions by: Sumit // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace QuillJS { +declare namespace Quill { + + type Key = { key: string, shortKey?: boolean }; + type Sources = "api" | "user" | "silent"; + type Formats = { [key: string]: any }; + + export interface KeyboardStatic { + addBinding(key: Key, callback: (range: RangeStatic, context: any) => void): void; + addBinding(key: Key, context: any, callback: (range: RangeStatic, context: any) => void) : void; + } + + export interface ClipboardStatic { + addMatcher(selector: string, callback: (node: any, delta: DeltaStatic) => DeltaStatic) : void; + addMatcher(nodeType: number, callback: (node: any, delta: DeltaStatic) => DeltaStatic) : void; + dangerouslyPasteHTML(html: string, source?: Sources): void; + dangerouslyPasteHTML(index: number, html: string, source?: Sources): void; + } export interface QuillOptionsStatic { debug?: string, - modules?: { [key: string]: any }, + modules?: Formats, placeholder?: string, readOnly?: boolean, theme?: string, @@ -22,11 +38,26 @@ declare namespace QuillJS { } export interface DeltaStatic { + new (ops: Array) : DeltaStatic; + new (ops: any) : DeltaStatic; ops?: Array; - retain?: any, - delete?: any, - insert?: any, - attributes?: any + retain(length: number, attributes: any) : DeltaStatic; + delete(length: number) : DeltaStatic; + filter(predicate: any) : DeltaStatic; + forEach(predicate: any) : DeltaStatic; + insert(text: any, attributes: any): DeltaStatic; + map(predicate: any) : DeltaStatic; + partition(predicate: any) : DeltaStatic; + reduce(predicate: any, initial: number): DeltaStatic; + chop() : DeltaStatic; + length(): number; + slice(start: number, end: number): DeltaStatic; + compose(other: any): DeltaStatic; + concat(other: DeltaStatic): DeltaStatic; + diff(other: DeltaStatic, index: number) : DeltaStatic; + eachLine(predicate: any, newline: any) : DeltaStatic; + transform(other: any, priority: any) : DeltaStatic; + transformPosition(index: number, priority: any) : DeltaStatic; } export interface RangeStatic { @@ -35,62 +66,70 @@ declare namespace QuillJS { length: number; } - type sourceType = "api" | "user" | "silent"; - type formatsType = { [key: string]: any }; - - export interface QuillStatic { - new (container: string | Element, options?: QuillOptionsStatic): QuillStatic; - deleteText(start: number, end: number, source?: sourceType): void; + export interface Quill { + new (container: string | Element, options?: QuillOptionsStatic): Quill; + deleteText(index: number, length: number, source?: Sources): void; disable(): void; enable(enabled?: boolean): void; - getContents(start?: number, end?: number): DeltaStatic; + getContents(index?: number, length?: number): DeltaStatic; getLength(): number; - getText(start?: number, end?: number): string; - insertEmbed(index: number, type: string, url: string, source?: sourceType): void; - insertText(index: number, text: string, source?: sourceType): void; - insertText(index: number, text: string, format: string, value: string, source?: sourceType): void; - insertText(index: number, text: string, formats: formatsType, source?: sourceType): void; - pasteHTML(index: number, html: string, source?:sourceType): string; - pasteHTML(html:string, source?: sourceType): string; - setContents(delta: DeltaStatic, source?: sourceType): void; - setText(text: string, source?: sourceType): void; + getText(index?: number, length?: number): string; + insertEmbed(index: number, type: string, value: any, source?: Sources): void; + insertText(index: number, text: string, source?: Sources): DeltaStatic; + insertText(index: number, text: string, format: string, value: any, source?: Sources): DeltaStatic; + insertText(index: number, text: string, formats: Formats, source?: Sources): DeltaStatic; + /** + * @deprecated Use clipboard.dangerouslyPasteHTML(index: number, html: string, source: Sources) + */ + pasteHTML(index: number, html: string, source?: Sources): string; + /** + * @deprecated Use dangerouslyPasteHTML(html: string, source: Sources): void; + */ + pasteHTML(html: string, source?: Sources): string; + setContents(delta: DeltaStatic, source?: Sources): DeltaStatic; + setText(text: string, source?: Sources): DeltaStatic; update(source?: string): void; - updateContents(delta: DeltaStatic, source?: sourceType): void; - - format(name: string, value: any, source?: sourceType): void; - formatLine(index: number, length: number, source?: sourceType): void; - formatLine(index: number, length: number, format: string, value: any, source?: sourceType): void; - formatLine(index: number, length: number, formats: formatsType, source?: sourceType): void; - formatText(index: number, length: number, source?: sourceType): void; - formatText(index: number, length: number, format: string, value: any, source?: sourceType): void; - formatText(index: number, length: number, formats: formatsType, source?: sourceType): void; - getFormat(range?: RangeStatic): formatsType; - getFormat(index: number, length?: number): formatsType; - removeFormat(index: Number, length: Number, source?: sourceType): void; + updateContents(delta: DeltaStatic, source?: Sources): DeltaStatic; + + format(name: string, value: any, source?: Sources): DeltaStatic; + formatLine(index: number, length: number, source?: Sources): DeltaStatic; + formatLine(index: number, length: number, format: string, value: any, source?: Sources): DeltaStatic; + formatLine(index: number, length: number, formats: Formats, source?: Sources): DeltaStatic; + formatText(index: number, length: number, source?: Sources): DeltaStatic; + formatText(index: number, length: number, format: string, value: any, source?: Sources): DeltaStatic; + formatText(index: number, length: number, formats: Formats, source?: Sources): DeltaStatic; + getFormat(range?: RangeStatic): Formats; + getFormat(index: number, length?: number): Formats; + removeFormat(index: number, length: number, source?: Sources): void; blur(): void; focus(): void; getBounds(index: number, length?: number): BoundsStatic; getSelection(focus?: boolean): RangeStatic; hasFocus(): boolean; - setSelection(index: number, length: number, source?: sourceType): void; - setSelection(range: RangeStatic, source?: sourceType): void; + setSelection(index: number, length: number, source?: Sources): void; + setSelection(range: RangeStatic, source?: Sources): void; on(eventName: string, callback: ((delta: T, oldContents: T, source: string) => void) | - ((name: string, ...args: any[]) => void)): QuillStatic; - once(eventName: string, callback: (delta: DeltaStatic, source: string) => void): QuillStatic; - off(eventName: string, callback: (delta: DeltaStatic, source: string) => void): QuillStatic; + ((name: string, ...args: any[]) => void)): Quill; + once(eventName: string, callback: (delta: DeltaStatic, source: string) => void): Quill; + off(eventName: string, callback: (delta: DeltaStatic, source: string) => void): Quill; debug(level: string): void; import(path: string): any; register(path: string, def: any, suppressWarning?: boolean): void; - register(defs: formatsType, suppressWarning?: boolean): void; + register(defs: Formats, suppressWarning?: boolean): void; addContainer(className: string, refNode?: any): any; + addContainer(domNode: any, refNode?: any): any; getModule(name: string): any + + clipboard: ClipboardStatic; } } -declare var Quill: QuillJS.QuillStatic; +declare var Quill: Quill.Quill; + +declare var Delta: Quill.DeltaStatic; declare module "quill" { export = Quill; diff --git a/quill/quill-tests.ts b/quill/quill-tests.ts index c606993993eb00..b16c90b384cc47 100644 --- a/quill/quill-tests.ts +++ b/quill/quill-tests.ts @@ -23,9 +23,14 @@ function test_enable() { quillEditor.enable(); } +function test_enable_false() { + let quillEditor = new Quill('#Editor'); + quillEditor.enable(false); +} + function test_getContents() { var quillEditor = new Quill('#editor'); - var delta: QuillJS.DeltaStatic = quillEditor.getContents(); + var delta: Quill.DeltaStatic = quillEditor.getContents(); } function test_getLength() { @@ -93,24 +98,24 @@ function test_insertEmbed() { function test_updateContents() { var quillEditor = new Quill('#editor'); - quillEditor.updateContents({ + quillEditor.updateContents(new Delta({ ops: [ { retain: 6 }, // Keep 'Hello ' { delete: 5 }, // 'World' is deleted { insert: 'Quill' }, // Insert 'Quill' { retain: 1, attributes: { bold: true } } // Apply bold to exclamation mark ] - }); + })); } function test_setContents() { var quillEditor = new Quill('#editor'); - quillEditor.setContents([ + quillEditor.setContents(new Delta({ ops: [ { insert: 'Hello ' }, { insert: 'World!', attributes: { bold: true } }, { insert: '\n' } - ]); + ]})); } function test_setText() { diff --git a/react-addons-css-transition-group/index.d.ts b/react-addons-css-transition-group/index.d.ts index a15527e032bdee..77ddc09f5a1edd 100644 --- a/react-addons-css-transition-group/index.d.ts +++ b/react-addons-css-transition-group/index.d.ts @@ -7,24 +7,26 @@ import 'react-addons-transition-group'; import { ComponentClass, TransitionGroupProps } from 'react'; declare var CSSTransitionGroup: CSSTransitionGroup; -type CSSTransitionGroup = ComponentClass; +type CSSTransitionGroup = ComponentClass; export = CSSTransitionGroup; -interface CSSTransitionGroupTransitionName { - enter: string; - enterActive?: string; - leave: string; - leaveActive?: string; - appear?: string; - appearActive?: string; -} +declare namespace CSSTransitionGroup { + interface CSSTransitionGroupTransitionName { + enter: string; + enterActive?: string; + leave: string; + leaveActive?: string; + appear?: string; + appearActive?: string; + } -interface CSSTransitionGroupProps extends TransitionGroupProps { - transitionName: string | CSSTransitionGroupTransitionName; - transitionAppear?: boolean; - transitionAppearTimeout?: number; - transitionEnter?: boolean; - transitionEnterTimeout?: number; - transitionLeave?: boolean; - transitionLeaveTimeout?: number; + interface CSSTransitionGroupProps extends TransitionGroupProps { + transitionName: string | CSSTransitionGroupTransitionName; + transitionAppear?: boolean; + transitionAppearTimeout?: number; + transitionEnter?: boolean; + transitionEnterTimeout?: number; + transitionLeave?: boolean; + transitionLeaveTimeout?: number; + } } diff --git a/react-bytesize-icons/index.d.ts b/react-bytesize-icons/index.d.ts new file mode 100644 index 00000000000000..99339d1b18bb40 --- /dev/null +++ b/react-bytesize-icons/index.d.ts @@ -0,0 +1,104 @@ +// Type definitions for react-bytesize-icons 0.6.4 +// Project: https://github.com/abdelhai/react-bytesize-icons +// Definitions by: rhysd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from "react"; + +export type StrokeLinejoin = "round" | "bevel" | "miter" | "inherit"; +export type StrokeLinecap = "round" | "butt" | "square" | "inherit"; +interface BytesizeIconsProps extends React.Props { + width?: number; + height?: number; + strokeWidth?: string; + strokeLinejoin?: StrokeLinejoin; + strokeLinecap?: StrokeLinecap; + color?: string; +} +export class BytesizeIconComponent extends React.Component {} + +export class Activity extends BytesizeIconComponent {} +export class Alert extends BytesizeIconComponent {} +export class Archive extends BytesizeIconComponent {} +export class ArrowBottom extends BytesizeIconComponent {} +export class ArrowLeft extends BytesizeIconComponent {} +export class ArrowRight extends BytesizeIconComponent {} +export class ArrowTop extends BytesizeIconComponent {} +export class Backwards extends BytesizeIconComponent {} +export class Ban extends BytesizeIconComponent {} +export class Bell extends BytesizeIconComponent {} +export class Bookmark extends BytesizeIconComponent {} +export class Camera extends BytesizeIconComponent {} +export class CaretBottom extends BytesizeIconComponent {} +export class CaretLeft extends BytesizeIconComponent {} +export class CaretRight extends BytesizeIconComponent {} +export class CaretTop extends BytesizeIconComponent {} +export class Cart extends BytesizeIconComponent {} +export class Checkmark extends BytesizeIconComponent {} +export class ChevronBottom extends BytesizeIconComponent {} +export class ChevronLeft extends BytesizeIconComponent {} +export class ChevronRight extends BytesizeIconComponent {} +export class ChevronTop extends BytesizeIconComponent {} +export class Clock extends BytesizeIconComponent {} +export class Close extends BytesizeIconComponent {} +export class Code extends BytesizeIconComponent {} +export class Compose extends BytesizeIconComponent {} +export class Creditcard extends BytesizeIconComponent {} +export class Download extends BytesizeIconComponent {} +export class Send extends BytesizeIconComponent {} +export class Edit extends BytesizeIconComponent {} +export class Eject extends BytesizeIconComponent {} +export class EllipsisHorizontal extends BytesizeIconComponent {} +export class EllipsisVertical extends BytesizeIconComponent {} +export class End extends BytesizeIconComponent {} +export class Export extends BytesizeIconComponent {} +export class External extends BytesizeIconComponent {} +export class Book extends BytesizeIconComponent {} +export class Calendar extends BytesizeIconComponent {} +export class Print extends BytesizeIconComponent {} +export class Eye extends BytesizeIconComponent {} +export class File extends BytesizeIconComponent {} +export class Fire extends BytesizeIconComponent {} +export class Flag extends BytesizeIconComponent {} +export class FolderOpen extends BytesizeIconComponent {} +export class Folder extends BytesizeIconComponent {} +export class Forwards extends BytesizeIconComponent {} +export class Gift extends BytesizeIconComponent {} +export class Github extends BytesizeIconComponent {} +export class Heart extends BytesizeIconComponent {} +export class Home extends BytesizeIconComponent {} +export class Import extends BytesizeIconComponent {} +export class Inbox extends BytesizeIconComponent {} +export class Info extends BytesizeIconComponent {} +export class Lightning extends BytesizeIconComponent {} +export class Link extends BytesizeIconComponent {} +export class Location extends BytesizeIconComponent {} +export class Lock extends BytesizeIconComponent {} +export class Mail extends BytesizeIconComponent {} +export class Menu extends BytesizeIconComponent {} +export class Message extends BytesizeIconComponent {} +export class Music extends BytesizeIconComponent {} +export class Mute extends BytesizeIconComponent {} +export class Options extends BytesizeIconComponent {} +export class Paperclip extends BytesizeIconComponent {} +export class Pause extends BytesizeIconComponent {} +export class Photo extends BytesizeIconComponent {} +export class Plus extends BytesizeIconComponent {} +export class Minus extends BytesizeIconComponent {} +export class Play extends BytesizeIconComponent {} +export class Portfolio extends BytesizeIconComponent {} +export class Reload extends BytesizeIconComponent {} +export class Reply extends BytesizeIconComponent {} +export class Search extends BytesizeIconComponent {} +export class Settings extends BytesizeIconComponent {} +export class Star extends BytesizeIconComponent {} +export class Start extends BytesizeIconComponent {} +export class Tag extends BytesizeIconComponent {} +export class Trash extends BytesizeIconComponent {} +export class Twitter extends BytesizeIconComponent {} +export class Unlock extends BytesizeIconComponent {} +export class Upload extends BytesizeIconComponent {} +export class User extends BytesizeIconComponent {} +export class Video extends BytesizeIconComponent {} +export class Volume extends BytesizeIconComponent {} +export class Work extends BytesizeIconComponent {} diff --git a/react-bytesize-icons/react-bytesize-icons-tests.tsx b/react-bytesize-icons/react-bytesize-icons-tests.tsx new file mode 100644 index 00000000000000..6d73100fe2e615 --- /dev/null +++ b/react-bytesize-icons/react-bytesize-icons-tests.tsx @@ -0,0 +1,7 @@ +import * as React from 'react'; +import {render} from 'react-dom'; +import {Activity, External, Export} from 'react-bytesize-icons'; + +render(, document.getElementById('test')); +render(, document.getElementById('test')); +render(, document.getElementById('test')); diff --git a/react-bytesize-icons/tsconfig.json b/react-bytesize-icons/tsconfig.json new file mode 100644 index 00000000000000..d6de5cbf29fcd0 --- /dev/null +++ b/react-bytesize-icons/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-bytesize-icons-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-color/index.d.ts b/react-color/index.d.ts new file mode 100644 index 00000000000000..cdf723d33bb0f4 --- /dev/null +++ b/react-color/index.d.ts @@ -0,0 +1,248 @@ +// Type definitions for react-color v2.3.4 +// Project: https://casesandberg.github.io/react-color/ +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ReactColor { + interface HSLColor { + a?: number + h: number + l: number + s: number + } + + interface RGBColor { + a?: number + b: number + g: number + r: number + } + + type Color = string | HSLColor | RGBColor + + interface ColorResult { + hex: string + hsl: HSLColor + rgb: RGBColor + } + + type ColorChangeHandler = (color: ColorResult) => void + + interface ColorPickerProps extends React.ClassAttributes { + color?: Color + onChange?: ColorChangeHandler + onChangeComplete?: ColorChangeHandler + } + + /* Predefined pickers */ + interface AlphaPickerProps extends ColorPickerProps { + height?: string + width?: string + } + interface AlphaPicker extends React.ComponentClass {} + const AlphaPicker: AlphaPicker + + interface BlockPickerProps extends ColorPickerProps { + colors?: Array + width?: string + } + interface BlockPicker extends React.ComponentClass {} + const BlockPicker: BlockPicker + + interface ChromePickerProps extends ColorPickerProps { + disableAlpha?: boolean + } + interface ChromePicker extends React.ComponentClass {} + const ChromePicker: ChromePicker + + interface CirclePickerProps extends ColorPickerProps { + colors?: Array + width?: string + } + interface CirclePicker extends React.ComponentClass {} + const CirclePicker: CirclePicker + + interface CompactPickerProps extends ColorPickerProps { + colors?: Array + } + interface CompactPicker extends React.ComponentClass {} + const CompactPicker: CompactPicker + + interface GithubPickerProps extends ColorPickerProps { + colors?: Array + width?: string + } + interface GithubPicker extends React.ComponentClass {} + const GithubPicker: GithubPicker + + interface HuePickerProps extends ColorPickerProps { + height?: string + width?: string + } + interface HuePicker extends React.ComponentClass {} + const HuePicker: HuePicker + + interface MaterialPickerProps extends ColorPickerProps {} + interface MaterialPicker extends React.ComponentClass {} + const MaterialPicker: MaterialPicker + + interface PhotoshopPickerProps extends ColorPickerProps { + header?: string + onAccept?: ColorChangeHandler + onCancel?: ColorChangeHandler + } + interface PhotoshopPicker extends React.ComponentClass {} + const PhotoshopPicker: PhotoshopPicker + + interface SketchPickerProps extends ColorPickerProps { + disableAlpha?: boolean + presetColors?: Array + width?: string + } + interface SketchPicker extends React.ComponentClass {} + const SketchPicker: SketchPicker + + interface SliderPickerProps extends ColorPickerProps {} + interface SliderPicker extends React.ComponentClass {} + const SliderPicker: SliderPicker + + interface SwatchesPickerProps extends ColorPickerProps { + colors?: Array> + height?: number + width?: number + } + interface SwatchesPicker extends React.ComponentClass {} + const SwatchesPicker: SwatchesPicker + + interface TwitterPickerProps extends ColorPickerProps {} + interface TwitterPicker extends React.ComponentClass {} + const TwitterPicker: TwitterPicker + + /* For custom picker */ + interface InjectedColorProps { + hex?: string + hsl?: HSLColor + rgb?: RGBColor + onChange?: ColorChangeHandler + } + + function CustomPicker(component: React.ComponentClass | React.StatelessComponent): React.ComponentClass + + interface CustomPickerProps extends React.ClassAttributes { + color?: Color + pointer?: React.ReactNode + onChange?: ColorChangeHandler + } + + interface AlphaProps extends CustomPickerProps {} + interface Alpha extends React.ComponentClass {} + const Alpha: Alpha + + interface EditableInputStyles { + input?: React.CSSProperties + label?: React.CSSProperties + wrap?: React.CSSProperties + } + interface EditableInputProps extends React.ClassAttributes { + color?: Color + label?: string + onChange?: ColorChangeHandler + styles?: EditableInputStyles + value?: any + } + interface EditableInput extends React.ComponentClass {} + const EditableInput: EditableInput + + interface HueProps extends CustomPickerProps { + direction?: "horizontal" | "vertical" + } + interface Hue extends React.ComponentClass {} + const Hue: Hue + + interface SaturationProps extends CustomPickerProps {} + interface Saturation extends React.ComponentClass {} + const Saturation: Saturation + + interface CheckboardProps extends React.ClassAttributes { + grey?: string + size?: number + white?: string + } + interface Checkboard extends React.ComponentClass {} + const Checkboard: Checkboard +} + +declare module "react-color/lib/components/common/Alpha" { export default ReactColor.Alpha } +declare module "react-color/lib/components/common/Checkboard" { export default ReactColor.Checkboard } +declare module "react-color/lib/components/common/EditableInput" { export default ReactColor.EditableInput } +declare module "react-color/lib/components/common/Hue" { export default ReactColor.Hue } +declare module "react-color/lib/components/common/Saturation" { export default ReactColor.Saturation } +declare module "react-color/lib/components/common/ColorWrap" { export default ReactColor.CustomPicker } + +declare module "react-color/lib/components/common" { + import Alpha from "react-color/lib/components/common/Alpha" + import Checkboard from "react-color/lib/components/common/Checkboard" + import EditableInput from "react-color/lib/components/common/EditableInput" + import Hue from "react-color/lib/components/common/Hue" + import Saturation from "react-color/lib/components/common/Saturation" + + export { + Alpha, + Checkboard, + EditableInput, + Hue, + Saturation + } +} + +declare module "react-color/lib/components/alpha/Alpha" { export default ReactColor.AlphaPicker } +declare module "react-color/lib/components/block/Block" { export default ReactColor.BlockPicker } +declare module "react-color/lib/components/chrome/Chrome" { export default ReactColor.ChromePicker } +declare module "react-color/lib/components/circle/Circle" { export default ReactColor.CirclePicker } +declare module "react-color/lib/components/compact/Compact" { export default ReactColor.CompactPicker } +declare module "react-color/lib/components/github/Github" { export default ReactColor.GithubPicker } +declare module "react-color/lib/components/hue/Hue" { export default ReactColor.HuePicker } +declare module "react-color/lib/components/meterial/Material" { export default ReactColor.MaterialPicker } +declare module "react-color/lib/components/photoshop/Photoshop" { export default ReactColor.PhotoshopPicker } +declare module "react-color/lib/components/sketch/Sketch" { export default ReactColor.SketchPicker } +declare module "react-color/lib/components/slider/Slider" { export default ReactColor.SliderPicker } +declare module "react-color/lib/components/swatches/Swatches" { export default ReactColor.SwatchesPicker } +declare module "react-color/lib/components/twitter/Twitter" { export default ReactColor.TwitterPicker } + +declare module "react-color" { + import AlphaPicker from "react-color/lib/components/alpha/Alpha" + import BlockPicker from "react-color/lib/components/block/Block" + import ChromePicker from "react-color/lib/components/chrome/Chrome" + import CirclePicker from "react-color/lib/components/circle/Circle" + import CompactPicker from "react-color/lib/components/compact/Compact" + import GithubPicker from "react-color/lib/components/github/Github" + import HuePicker from "react-color/lib/components/hue/Hue" + import MaterialPicker from "react-color/lib/components/meterial/Material" + import PhotoshopPicker from "react-color/lib/components/photoshop/Photoshop" + import SketchPicker from "react-color/lib/components/sketch/Sketch" + import SliderPicker from "react-color/lib/components/slider/Slider" + import SwatchesPicker from "react-color/lib/components/swatches/Swatches" + import TwitterPicker from "react-color/lib/components/twitter/Twitter" + import CustomPicker from "react-color/lib/components/common/ColorWrap" + + export type CustomPickerProps = ReactColor.CustomPickerProps + + export { + AlphaPicker, + BlockPicker, + ChromePicker, + CirclePicker, + CompactPicker, + GithubPicker, + HuePicker, + MaterialPicker, + PhotoshopPicker, + SketchPicker, + SliderPicker, + SwatchesPicker, + TwitterPicker, + CustomPicker + } +} diff --git a/react-color/react-color-tests.tsx b/react-color/react-color-tests.tsx new file mode 100644 index 00000000000000..7969047569008a --- /dev/null +++ b/react-color/react-color-tests.tsx @@ -0,0 +1,46 @@ +import * as React from "react" +import { StatelessComponent } from "react" +import { render } from "react-dom" +import { + AlphaPicker, BlockPicker, ChromePicker, CirclePicker, + CompactPicker, GithubPicker, HuePicker, MaterialPicker, + PhotoshopPicker, SketchPicker, SliderPicker, SwatchesPicker, + TwitterPicker, CustomPicker +} from "react-color" +import { Alpha, Checkboard, EditableInput, Hue, Saturation } from "react-color/lib/components/common" + +interface CustomProps extends ReactColor.InjectedColorProps { + color?: ReactColor.Color +} + +var CustomComponent: StatelessComponent = (props: CustomProps) => { + function onChange (color: ReactColor.ColorResult) {} + + return ( +
+ + + + + +
+ ) +} +var Custom = CustomPicker(CustomComponent) + +var colors: Array = ["#000", "#333"] + +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) +render(, document.getElementById("main")) diff --git a/react-color/tsconfig.json b/react-color/tsconfig.json new file mode 100644 index 00000000000000..269782214d20b8 --- /dev/null +++ b/react-color/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-color-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-css-transition-replace/index.d.ts b/react-css-transition-replace/index.d.ts new file mode 100644 index 00000000000000..292e45e5e52809 --- /dev/null +++ b/react-css-transition-replace/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for react-css-transition-replace 2.0.1 +// Project: http://marnusw.github.io/react-css-transition-replace/ +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from "react"; +import * as CSSTransitionGroup from "react-addons-css-transition-group"; + +declare namespace CSSTransitionReplace { + interface Props extends CSSTransitionGroup.CSSTransitionGroupProps { + overflowHidden?: boolean + } +} + +declare var CSSTransitionReplace: CSSTransitionReplace; +type CSSTransitionReplace = React.ComponentClass; +export = CSSTransitionReplace; diff --git a/react-css-transition-replace/react-css-transition-replace-tests.tsx b/react-css-transition-replace/react-css-transition-replace-tests.tsx new file mode 100644 index 00000000000000..2da448d448024f --- /dev/null +++ b/react-css-transition-replace/react-css-transition-replace-tests.tsx @@ -0,0 +1,10 @@ +import * as React from "react" +import { render } from 'react-dom'; +import * as CSSTransitionReplace from "react-css-transition-replace" + +render( + +
Test
+
, + document.getElementById("main") +) diff --git a/react-css-transition-replace/tsconfig.json b/react-css-transition-replace/tsconfig.json new file mode 100644 index 00000000000000..8c1e3238f673b2 --- /dev/null +++ b/react-css-transition-replace/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-css-transition-replace-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-fa/index.d.ts b/react-fa/index.d.ts index 725686c0f3bd95..f25d6aa53543af 100644 --- a/react-fa/index.d.ts +++ b/react-fa/index.d.ts @@ -6,22 +6,30 @@ /// -import { ComponentClass, Props } from 'react'; - -interface IconProps extends Props { - name: string; - className?: string; - size?: string; - spin?: boolean; - rotate?: string; - flip?: string; - fixedWidth?: boolean; - pulse?: boolean; - stack?: string; - inverse?: boolean; +import { Component, ClassAttributes } from 'react'; + +type IconSize = "lg" | "2x" | "3x" | "4x" | "5x" + +interface IconProps extends ClassAttributes { + name: string + className?: string + size?: IconSize + rotate?: "45" | "90" | "135" | "180" | "225" | "270" | "315" + flip?: "horizontal" | "vertical" + fixedWidth?: boolean + spin?: boolean + pulse?: boolean + stack?: "1x" | "2x" + inverse?: boolean + Component?: string | Function } -interface Icon extends ComponentClass { } -declare const Icon: Icon; +export class Icon extends Component {} + +interface IconStackProps extends ClassAttributes { + className?: string + size?: IconSize +} +export class IconStack extends Component {} -export = Icon; +export default Icon; \ No newline at end of file diff --git a/react-fa/react-fa-4.0.0.d.ts b/react-fa/react-fa-4.0.0.d.ts new file mode 100644 index 00000000000000..0b6b166a22b7fb --- /dev/null +++ b/react-fa/react-fa-4.0.0.d.ts @@ -0,0 +1,28 @@ +// Type definitions for react-fa v4.0.0 +// Project: https://github.com/andreypopp/react-fa +// Definitions by: Frank Laub +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "react-fa" { + import { ComponentClass, Props } from 'react'; + + interface IconProps extends Props { + name: string; + className?: string; + size?: string; + spin?: boolean; + rotate?: string; + flip?: string; + fixedWidth?: boolean; + pulse?: boolean; + stack?: string; + inverse?: boolean; + } + + interface Icon extends ComponentClass { } + const Icon: Icon; + + export = Icon; +} diff --git a/react-fa/react-fa-tests.tsx b/react-fa/react-fa-tests.tsx index 1f94758b7d9b97..2cfa3a3dbe5984 100644 --- a/react-fa/react-fa-tests.tsx +++ b/react-fa/react-fa-tests.tsx @@ -1,10 +1,20 @@ /// -import * as React from "react"; -import { render } from 'react-dom'; -import Icon = require('react-fa'); +// Imports +// -------------------------------------------------------------------------------- +import * as React from "react" +import { render } from "react-dom" +import { Icon, IconStack } from "react-fa" render( - , - document.getElementById('main') + , + document.getElementById("main") +) + +render( + + + + , + document.getElementById("main") ) diff --git a/react-ga/index.d.ts b/react-ga/index.d.ts index 3a80651dc128c5..0a0973113b25b0 100644 --- a/react-ga/index.d.ts +++ b/react-ga/index.d.ts @@ -16,10 +16,15 @@ declare namespace __reactGA { debug?: boolean; } + export interface FieldsObject { + [i: string]: any; + } + export function initialize(trackingCode: string, options?: InitializeOptions): void; export function pageview(path: string): void; export function modalview(name: string): void; export function event(args: EventArgs): void; + export function set(fieldsObject: FieldsObject): void; } declare module 'react-ga' { diff --git a/react-ga/react-ga-tests.tsx b/react-ga/react-ga-tests.tsx index 2248665dd94fb0..1dd6e04bd72c0c 100644 --- a/react-ga/react-ga-tests.tsx +++ b/react-ga/react-ga-tests.tsx @@ -8,11 +8,11 @@ describe("Testing react-ga initialize object", () => { }); it("Able to initailize react-ga object", () => { let ga = __reactGA; - + let options: __reactGA.InitializeOptions = { debug: true, } - + ga.initialize("UA-65432-1", options); }); }); @@ -21,7 +21,7 @@ describe("Testing react-ga pageview calls", () => { it("Able to make pageview calls", () => { let ga = __reactGA; ga.initialize("UA-65432-1"); - + ga.pageview("http://telshin.com"); }); }); @@ -30,7 +30,7 @@ describe("Testing react-ga modal calls", () => { it("Able to make modal calls", () => { let ga = __reactGA; ga.initialize("UA-65432-1"); - + ga.modalview("Test modal"); }); }); @@ -39,7 +39,7 @@ describe("Testing react-ga event calls", () => { it("Able to make event calls", () => { let ga = __reactGA; ga.initialize("UA-65432-1"); - + let options: __reactGA.EventArgs = { category: "Test", action: "CI", @@ -47,7 +47,20 @@ describe("Testing react-ga event calls", () => { value: 4, nonInteraction: true, } - + ga.event(options); }); -}); \ No newline at end of file +}); + +describe("Testing react-ga set calls", () => { + it("Able to make set calls", () => { + let ga = __reactGA; + ga.initialize("UA-65432-1"); + + let fieldObject: __reactGA.FieldsObject = { + page: '/users' + }; + + ga.set(fieldObject); + }); +}); diff --git a/react-intl-redux/index.d.ts b/react-intl-redux/index.d.ts new file mode 100644 index 00000000000000..79ab678c33db0a --- /dev/null +++ b/react-intl-redux/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for react-intl-redux v0.1.0 +// Project: https://github.com/ratson/react-intl-redux +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Action } from "redux" +import { Provider as ReduxProvider } from "react-redux" +import { IntlProvider as ReactIntlProvider } from "react-intl" + +interface IntlState { + locale: string + messages: any +} + +interface IntlAction extends Action { + payload?: IntlState +} + +export function intlReducer(state: IntlState, action: IntlAction): IntlState +export function updateIntl (opts: IntlState): IntlAction +export class IntlProvider extends ReactIntlProvider {} +export class Provider extends ReduxProvider {} diff --git a/react-intl-redux/react-intl-redux-tests.tsx b/react-intl-redux/react-intl-redux-tests.tsx new file mode 100644 index 00000000000000..2c3e55fffa821c --- /dev/null +++ b/react-intl-redux/react-intl-redux-tests.tsx @@ -0,0 +1,20 @@ +import * as React from "react" +import { render } from "react-dom" +import { Provider, IntlProvider, IntlState, IntlAction, intlReducer, updateIntl } from "react-intl-redux" + +var action: IntlAction = updateIntl({ locale : "en", messages : {} }) +var state: IntlState = intlReducer({ locale : "en", messages : {} }, action) + +render( + +
Test
+
, + document.getElementById("main") +) + +render( + +
Test
+
, + document.getElementById("main") +) diff --git a/react-intl-redux/tsconfig.json b/react-intl-redux/tsconfig.json new file mode 100644 index 00000000000000..ea3d912eac8d11 --- /dev/null +++ b/react-intl-redux/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-intl-redux-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-native-sortable-list/index.d.ts b/react-native-sortable-list/index.d.ts new file mode 100644 index 00000000000000..8774c2ad1fd40f --- /dev/null +++ b/react-native-sortable-list/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for react-native-sortable-list +// Project: https://github.com/gitim/react-native-sortable-list +// Definitions by: Michael Sivolobov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from 'react'; + +type DataKey = string | number; + +type DataValue = any + +type DataByNumber = { + [key: number]: DataValue +} + +type DataByString = { + [key: string]: DataValue +} + +type Data = DataByNumber | DataByString; + +export interface RowProps { + active: boolean + data: DataValue + key?: DataKey + index?: number + disabled?: boolean +} + +interface SortableListProps { + + /** + * data source + */ + data: Data + + /** + * an array of keys from data, the order of keys from the array will be used to initial rows order + */ + order?: DataKey[] + + /** + * style of HOC + */ + style?: React.ViewStyle + + /** + * these styles will be applied to the inner scroll view content container + */ + contentContainerStyle?: React.ViewStyle + + /** + * when false, rows are not sortable. The default value is true. + */ + sortingEnabled?: boolean + + /** + * when false, the content does not scrollable. The default value is true. + */ + scrollEnabled?: boolean + + /** + * Takes a row key, row index, data entry from the data source and its statuses disabled, + * active and should return a renderable component to be rendered as the row. + */ + renderRow: (props: RowProps) => JSX.Element + + /** + * Called when rows were reordered, takes an array of rows keys of the next rows order. + */ + onChangeOrder?: (nextOrder: DataKey[]) => void + + /** + * Called when a row was activated (user long tapped). + */ + onActivateRow?: (key: DataKey) => void + + /** + * Called when the active row was released. + */ + onReleaseRow?: (key: DataKey) => void +} + +interface SortableListStatic extends React.ClassicComponentClass {} + +declare var SortableList: SortableListStatic; +declare type SortableList = SortableListStatic; + +export default SortableList; \ No newline at end of file diff --git a/react-native-sortable-list/react-native-sortable-list-tests.tsx b/react-native-sortable-list/react-native-sortable-list-tests.tsx new file mode 100644 index 00000000000000..57a59b8d201f1e --- /dev/null +++ b/react-native-sortable-list/react-native-sortable-list-tests.tsx @@ -0,0 +1,203 @@ +import * as React from 'react'; +import { + Animated, + Easing, + AppRegistry, + StyleSheet, + Text, + Image, + View, + Dimensions, + FlexJustifyType, + FlexAlignType +} from 'react-native'; +import SortableList, {RowProps} from 'react-native-sortable-list'; + +const window = Dimensions.get('window'); + +const data = { + 0: { + image: 'https://placekitten.com/200/200', + text: 'Chloe', + }, + 1: { + image: 'https://placekitten.com/200/201', + text: 'Jasper', + }, + 2: { + image: 'https://placekitten.com/200/202', + text: 'Pepper', + }, + 3: { + image: 'https://placekitten.com/200/203', + text: 'Oscar', + }, + 4: { + image: 'https://placekitten.com/200/204', + text: 'Dusty', + }, + 5: { + image: 'https://placekitten.com/200/205', + text: 'Spooky', + }, + 6: { + image: 'https://placekitten.com/200/210', + text: 'Kiki', + }, + 7: { + image: 'https://placekitten.com/200/215', + text: 'Smokey', + }, + 8: { + image: 'https://placekitten.com/200/220', + text: 'Gizmo', + }, + 9: { + image: 'https://placekitten.com/220/239', + text: 'Kitty', + }, +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: "center" as FlexJustifyType, + alignItems: "center" as FlexAlignType, + backgroundColor: '#eee', + paddingTop: 60, + }, + + list: { + flex: 1, + }, + + contentContainer: { + width: window.width, + paddingHorizontal: 30, + }, + + row: { + flexDirection: 'row', + alignItems: 'center', + backgroundColor: 'white', + padding: 16, + marginVertical: 5, + height: 90, + width: window.width - 30 * 2, + borderRadius: 4, + shadowColor: 'rgba(0,0,0,0.2)', + shadowOpacity: 1, + shadowOffset: {height: 2, width: 2}, + shadowRadius: 2, + }, + + image: { + width: 60, + height: 60, + marginRight: 30, + borderRadius: 30, + }, + + text: { + fontSize: 24, + }, + +}); + +class Basic extends React.Component { + render() { + return ( + + + + ); + } + + _renderRow = ({data, active}: RowProps) => { + return + } +} + +interface RowState { + style: { + shadowRadius: Animated.Value + transform: {scale: Animated.Value}[] + } +} + +class Row extends React.Component { + + state = { + style: { + shadowRadius: new Animated.Value(2), + transform: [{scale: new Animated.Value(1)}], + } + }; + + componentWillReceiveProps(nextProps: RowProps) { + if (this.props.active !== nextProps.active) { + if (this.props.active !== nextProps.active) { + if (nextProps.active) { + this.startActivationAnimation(); + } else { + this.startDeactivationAnimation(); + } + } + } + } + + startActivationAnimation = () => { + const {style} = this.state; + + Animated.parallel([ + Animated.timing(style.transform[0].scale, { + duration: 100, + easing: Easing.out(Easing.quad), + toValue: 1.1 + }), + Animated.timing(style.shadowRadius, { + duration: 100, + easing: Easing.out(Easing.quad), + toValue: 10 + }), + ]).start(); + }; + + startDeactivationAnimation = () => { + const {style} = this.state; + + Animated.parallel([ + Animated.timing(style.transform[0].scale, { + duration: 100, + easing: Easing.out(Easing.quad), + toValue: 1 + }), + Animated.timing(style.shadowRadius, { + duration: 100, + easing: Easing.out(Easing.quad), + toValue: 2 + }), + ]).start(); + }; + + render() { + const {data} = this.props; + + return ( + + + {data.text} + + ); + } +} + + +AppRegistry.registerComponent('Basic', () => Basic); diff --git a/react-native-sortable-list/tsconfig.json b/react-native-sortable-list/tsconfig.json new file mode 100644 index 00000000000000..1f709abb745e50 --- /dev/null +++ b/react-native-sortable-list/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-native-sortable-list-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-native/index.d.ts b/react-native/index.d.ts index 8900ce0a0b47ec..e08bb9fcd94f0f 100644 --- a/react-native/index.d.ts +++ b/react-native/index.d.ts @@ -7616,11 +7616,16 @@ declare module "react" { export interface NavigationHeaderProps { renderTitleComponent?(props: Object): JSX.Element + renderLeftComponent?(props: Object): JSX.Element + renderRightComponent?(props: Object): JSX.Element onNavigateBack(): void + style?: ViewStyle + viewProps?: any + statusBarHeight?: number | NavigationAnimatedValue } export interface NavigationHeaderStatic extends React.ComponentClass { - Title: JSX.Element + Title: () => JSX.ElementClass HEIGHT: number } diff --git a/react-onclickoutside/index.d.ts b/react-onclickoutside/index.d.ts new file mode 100644 index 00000000000000..476601d056e3f3 --- /dev/null +++ b/react-onclickoutside/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for react-onclickoutside v5.7.0 +// Project: https://github.com/Pomax/react-onclickoutside +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace ReactOnClickOutside { + interface OnClickOutsideComponent { + handleClickOutside(e: React.MouseEvent): void + } + + interface OnClickOutsideProps { + disableOnClickOutside?: boolean | Function + enableOnClickOutside?: Function + eventTypes?: string | Array + outsideClickIgnoreClass?: string + preventDefault?: boolean + stopPropagation?: boolean + } + + interface onClickOutside { +
(component: React.ComponentClass | React.StatelessComponent): React.ComponentClass + } +} + +declare const onClickOutside: ReactOnClickOutside.onClickOutside +export = onClickOutside; \ No newline at end of file diff --git a/react-onclickoutside/react-onclickoutside-tests.tsx b/react-onclickoutside/react-onclickoutside-tests.tsx new file mode 100644 index 00000000000000..dabba332b15264 --- /dev/null +++ b/react-onclickoutside/react-onclickoutside-tests.tsx @@ -0,0 +1,26 @@ +// React onClickOutside Test +// ================================================================================ + +// Imports +// -------------------------------------------------------------------------------- +import * as React from "react" +import { Component, StatelessComponent, MouseEvent } from "react" +import { render } from "react-dom" +import * as onClickOutside from "react-onclickoutside" + +interface TestProps {} + +var TestStateless: StatelessComponent = (props: TestProps) => { + return (
Test
) +} + +var TestStatelessWrapped = onClickOutside(TestStateless) + +render( + , + document.getElementById("main") +) \ No newline at end of file diff --git a/react-onclickoutside/tsconfig.json b/react-onclickoutside/tsconfig.json new file mode 100644 index 00000000000000..7d7bfb3377a582 --- /dev/null +++ b/react-onclickoutside/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-onclickoutside-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-redux-i18n/index.d.ts b/react-redux-i18n/index.d.ts new file mode 100644 index 00000000000000..aa47bb2723018f --- /dev/null +++ b/react-redux-i18n/index.d.ts @@ -0,0 +1,62 @@ +// Type definitions for react-redux-i18n +// Project: https://github.com/zoover/react-redux-i18n +// Definitions by: Clément Devos +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'react-redux-i18n' { + import * as react from "react" + import * as redux from "redux" + + /** + * Helper methods + */ + interface I18n { + t(code: string, options?: any): string; + l(timestamp: number, options?: any): string; + } + export var I18n : I18n; + + type SubTranslationObject = string | { [key: string]: SubTranslationObject }; + + type TranslationObjects = { [lang: string]: SubTranslationObject }; + + type I18nState = { + translations: TranslationObjects; + locale: string; + } + + type TranslateProps = { + value: string; + [prop: string]: string; + + } + type LocalizeProps = { + value: string | number; + dateFormat?: string; + options?: Object; + } + + /** + * React components + */ + export class Translate extends react.Component{ } + export class Localize extends react.Component{ } + + /** + * Reducer + */ + export function i18nReducer(state?: any, options?: any): redux.Reducer; + + /** + * Reducer init + */ + export function syncTranslationWithStore(store: redux.Store): void; + + /** + * Redux Actions + */ + export function loadTranslations(translationsObject: TranslationObjects): void; + + export function setLocale(locale: string): void; + +} diff --git a/react-redux-i18n/react-redux-i18n-tests.tsx b/react-redux-i18n/react-redux-i18n-tests.tsx new file mode 100644 index 00000000000000..0811dca83d4be7 --- /dev/null +++ b/react-redux-i18n/react-redux-i18n-tests.tsx @@ -0,0 +1,50 @@ +import * as React from "react"; +import * as I18n from "react-redux-i18n"; + +class ReactReduxI18nTests_Translate1 extends React.Component, {}>{ + + render() { + return ( + + ) + } +} + + + +class ReactReduxI18nTests_Translate2 extends React.Component, {}>{ + + render() { + return ( + + ) + } +} + + +class ReactReduxI18nTests_Translate3 extends React.Component, {}>{ + + render() { + return ( + + ) + } +} + + +class ReactReduxI18nTests_Translate4 extends React.Component, {}>{ + + render() { + return ( + + ) + } +} + +function testI18Helper() { + I18n.I18n.t('application.title'); // => returns 'Toffe app met i18n!' + I18n.I18n.t('application.name', { name: 'Aad' }); // => returns 'Hallo, Aad!' + + I18n.I18n.l(1385856000000, { dateFormat: 'date.long' }); // => returns '1 december 2013' + I18n.I18n.l(Math.PI, { maximumFractionDigits: 2 }); // => returns '3,14' +} diff --git a/react-redux-i18n/tsconfig.json b/react-redux-i18n/tsconfig.json new file mode 100644 index 00000000000000..102c56da02f983 --- /dev/null +++ b/react-redux-i18n/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-redux-i18n-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-select/index.d.ts b/react-select/index.d.ts index 958298855c0a98..1d98fb2a72ade8 100644 --- a/react-select/index.d.ts +++ b/react-select/index.d.ts @@ -311,7 +311,7 @@ declare namespace ReactSelectClass { /** * initial field value */ - value?: Option | Option[] | string | string[] | number | number[]; + value?: Option | Option[] | string | string[] | number | number[] | boolean; /** * the option property to use for the value * @default "value" diff --git a/react-syntax-highlighter/index.d.ts b/react-syntax-highlighter/index.d.ts new file mode 100644 index 00000000000000..35019a7b7ec5fc --- /dev/null +++ b/react-syntax-highlighter/index.d.ts @@ -0,0 +1,500 @@ +// Type definitions for react-syntax-highlighter +// Project: https://github.com/conorhastings/react-syntax-highlighter +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'react-syntax-highlighter' { + import SyntaxHighlighter from 'react-syntax-highlighter/dist/light'; + export default SyntaxHighlighter; +} + +declare module 'react-syntax-highlighter/dist/light' { + import * as React from 'react'; + + interface SyntaxHighlighterProps { + language?: string; + style?: any; + customStyle?: any; + codeTagProps?: HTMLElement; + useInlineStyles?: boolean; + showLineNumbers?: boolean; + startingLineNumber?: number; + lineNumberStyle?: any; + [spread: string]: any; + } + + export default class SyntaxHighlighter extends React.Component { + + } +} + +declare module 'react-syntax-highlighter/dist/styles' { + export { default as agate } from 'react-syntax-highlighter/dist/styles/agate'; + export { default as androidstudio } from 'react-syntax-highlighter/dist/styles/androidstudio'; + export { default as arduinoLight } from 'react-syntax-highlighter/dist/styles/arduino-light'; + export { default as arta } from 'react-syntax-highlighter/dist/styles/arta'; + export { default as ascetic } from 'react-syntax-highlighter/dist/styles/ascetic'; + export { default as atelierCaveDark } from 'react-syntax-highlighter/dist/styles/atelier-cave-dark'; + export { default as atelierCaveLight } from 'react-syntax-highlighter/dist/styles/atelier-cave-light'; + export { default as atelierDuneDark } from 'react-syntax-highlighter/dist/styles/atelier-dune-dark'; + export { default as atelierDuneLight } from 'react-syntax-highlighter/dist/styles/atelier-dune-light'; + export { default as atelierEstuaryDark } from 'react-syntax-highlighter/dist/styles/atelier-estuary-dark'; + export { default as atelierEstuaryLight } from 'react-syntax-highlighter/dist/styles/atelier-estuary-light'; + export { default as atelierForestDark } from 'react-syntax-highlighter/dist/styles/atelier-forest-dark'; + export { default as atelierForestLight } from 'react-syntax-highlighter/dist/styles/atelier-forest-light'; + export { default as atelierHeathDark } from 'react-syntax-highlighter/dist/styles/atelier-heath-dark'; + export { default as atelierHeathLight } from 'react-syntax-highlighter/dist/styles/atelier-heath-light'; + export { default as atelierLakesideDark } from 'react-syntax-highlighter/dist/styles/atelier-lakeside-dark'; + export { default as atelierLakesideLight } from 'react-syntax-highlighter/dist/styles/atelier-lakeside-light'; + export { default as atelierPlateauDark } from 'react-syntax-highlighter/dist/styles/atelier-plateau-dark'; + export { default as atelierPlateauLight } from 'react-syntax-highlighter/dist/styles/atelier-plateau-light'; + export { default as atelierSavannaDark } from 'react-syntax-highlighter/dist/styles/atelier-savanna-dark'; + export { default as atelierSavannaLight } from 'react-syntax-highlighter/dist/styles/atelier-savanna-light'; + export { default as atelierSeasideDark } from 'react-syntax-highlighter/dist/styles/atelier-seaside-dark'; + export { default as atelierSeasideLight } from 'react-syntax-highlighter/dist/styles/atelier-seaside-light'; + export { default as atelierSulphurpoolDark } from 'react-syntax-highlighter/dist/styles/atelier-sulphurpool-dark'; + export { default as atelierSulphurpoolLight } from 'react-syntax-highlighter/dist/styles/atelier-sulphurpool-light'; + export { default as atomOneDark } from 'react-syntax-highlighter/dist/styles/atom-one-dark'; + export { default as atomOneLight } from 'react-syntax-highlighter/dist/styles/atom-one-light'; + export { default as brownPaper } from 'react-syntax-highlighter/dist/styles/brown-paper'; + export { default as codepenEmbed } from 'react-syntax-highlighter/dist/styles/codepen-embed'; + export { default as colorBrewer } from 'react-syntax-highlighter/dist/styles/color-brewer'; + export { default as darcula } from 'react-syntax-highlighter/dist/styles/darcula'; + export { default as dark } from 'react-syntax-highlighter/dist/styles/dark'; + export { default as darkula } from 'react-syntax-highlighter/dist/styles/darkula'; + export { default as defaultStyle } from 'react-syntax-highlighter/dist/styles/default-style'; + export { default as docco } from 'react-syntax-highlighter/dist/styles/docco'; + export { default as dracula } from 'react-syntax-highlighter/dist/styles/dracula'; + export { default as far } from 'react-syntax-highlighter/dist/styles/far'; + export { default as foundation } from 'react-syntax-highlighter/dist/styles/foundation'; + export { default as githubGist } from 'react-syntax-highlighter/dist/styles/github-gist'; + export { default as github } from 'react-syntax-highlighter/dist/styles/github'; + export { default as googlecode } from 'react-syntax-highlighter/dist/styles/googlecode'; + export { default as grayscale } from 'react-syntax-highlighter/dist/styles/grayscale'; + export { default as gruvboxDark } from 'react-syntax-highlighter/dist/styles/gruvbox-dark'; + export { default as gruvboxLight } from 'react-syntax-highlighter/dist/styles/gruvbox-light'; + export { default as hopscotch } from 'react-syntax-highlighter/dist/styles/hopscotch'; + export { default as hybrid } from 'react-syntax-highlighter/dist/styles/hybrid'; + export { default as idea } from 'react-syntax-highlighter/dist/styles/idea'; + export { default as irBlack } from 'react-syntax-highlighter/dist/styles/ir-black'; + export { default as kimbieDark } from 'react-syntax-highlighter/dist/styles/kimbie.dark'; + export { default as kimbieLight } from 'react-syntax-highlighter/dist/styles/kimbie.light'; + export { default as magula } from 'react-syntax-highlighter/dist/styles/magula'; + export { default as monoBlue } from 'react-syntax-highlighter/dist/styles/mono-blue'; + export { default as monokaiSublime } from 'react-syntax-highlighter/dist/styles/monokai-sublime'; + export { default as monokai } from 'react-syntax-highlighter/dist/styles/monokai'; + export { default as obsidian } from 'react-syntax-highlighter/dist/styles/obsidian'; + export { default as ocean } from 'react-syntax-highlighter/dist/styles/ocean'; + export { default as paraisoDark } from 'react-syntax-highlighter/dist/styles/paraiso-dark'; + export { default as paraisoLight } from 'react-syntax-highlighter/dist/styles/paraiso-light'; + export { default as pojoaque } from 'react-syntax-highlighter/dist/styles/pojoaque'; + export { default as purebasic } from 'react-syntax-highlighter/dist/styles/purebasic'; + export { default as qtcreatorDark } from 'react-syntax-highlighter/dist/styles/qtcreator_dark'; + export { default as qtcreatorLight } from 'react-syntax-highlighter/dist/styles/qtcreator_light'; + export { default as railscasts } from 'react-syntax-highlighter/dist/styles/railscasts'; + export { default as rainbow } from 'react-syntax-highlighter/dist/styles/rainbow'; + export { default as schoolBook } from 'react-syntax-highlighter/dist/styles/school-book'; + export { default as solarizedDark } from 'react-syntax-highlighter/dist/styles/solarized-dark'; + export { default as solarizedLight } from 'react-syntax-highlighter/dist/styles/solarized-light'; + export { default as sunburst } from 'react-syntax-highlighter/dist/styles/sunburst'; + export { default as tomorrowNightBlue } from 'react-syntax-highlighter/dist/styles/tomorrow-night-blue'; + export { default as tomorrowNightBright } from 'react-syntax-highlighter/dist/styles/tomorrow-night-bright'; + export { default as tomorrowNightEighties } from 'react-syntax-highlighter/dist/styles/tomorrow-night-eighties'; + export { default as tomorrowNight } from 'react-syntax-highlighter/dist/styles/tomorrow-night'; + export { default as tomorrow } from 'react-syntax-highlighter/dist/styles/tomorrow'; + export { default as vs } from 'react-syntax-highlighter/dist/styles/vs'; + export { default as xcode } from 'react-syntax-highlighter/dist/styles/xcode'; + export { default as xt256 } from 'react-syntax-highlighter/dist/styles/xt256'; + export { default as zenburn } from 'react-syntax-highlighter/dist/styles/zenburn'; +} + +declare module 'react-syntax-highlighter/dist/styles/agate' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/androidstudio' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/arduino-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/arta' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/ascetic' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-cave-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-cave-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-dune-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-dune-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-estuary-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-estuary-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-forest-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-forest-light' { + const style: any; + export default style; +} + + +declare module 'react-syntax-highlighter/dist/styles/atelier-heath-dark' { + const style: any; + export default style; +} + + +declare module 'react-syntax-highlighter/dist/styles/atelier-heath-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-lakeside-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-lakeside-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-plateau-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-plateau-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-savanna-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-savanna-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-seaside-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-seaside-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-sulphurpool-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atelier-sulphurpool-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atom-one-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/atom-one-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/brown-paper' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/codepen-embed' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/color-brewer' { + const style: any; + export default style; +} + + +declare module 'react-syntax-highlighter/dist/styles/darcula' { + const style: any; + export default style; +} + + +declare module 'react-syntax-highlighter/dist/styles/dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/darkula' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/default-style' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/docco' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/dracula' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/far' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/foundation' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/github-gist' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/github' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/googlecode' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/grayscale' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/gruvbox-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/gruvbox-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/hopscotch' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/hybrid' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/idea' { + const style: any; + export default style; +} + + +declare module 'react-syntax-highlighter/dist/styles/ir-black' { + const style: any; + export default style; +} + + +declare module 'react-syntax-highlighter/dist/styles/kimbie.dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/kimbie.light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/magula' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/mono-blue' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/monokai-sublime' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/monokai' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/obsidian' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/ocean' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/paraiso-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/paraiso-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/pojoaque' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/purebasic' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/qtcreator_dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/qtcreator_light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/railscasts' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/rainbow' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/school-book' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/solarized-dark' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/solarized-light' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/sunburst' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/tomorrow-night-blue' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/tomorrow-night-bright' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/tomorrow-night-eighties' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/tomorrow-night' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/tomorrow' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/vs' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/xcode' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/xt256' { + const style: any; + export default style; +} + +declare module 'react-syntax-highlighter/dist/styles/zenburn' { + const style: any; + export default style; +} \ No newline at end of file diff --git a/react-syntax-highlighter/react-syntax-highlighter-tests.tsx b/react-syntax-highlighter/react-syntax-highlighter-tests.tsx new file mode 100644 index 00000000000000..7cb8a9dc209494 --- /dev/null +++ b/react-syntax-highlighter/react-syntax-highlighter-tests.tsx @@ -0,0 +1,18 @@ +import * as React from 'react'; +import SyntaxHighlighter from 'react-syntax-highlighter'; +import { docco } from 'react-syntax-highlighter/dist/styles'; + +function highlighter(): JSX.Element { + const codeString: string = +`class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + public version(): string { + return this.version; + } +} +`; + return {codeString}; +} \ No newline at end of file diff --git a/react-syntax-highlighter/tsconfig.json b/react-syntax-highlighter/tsconfig.json new file mode 100644 index 00000000000000..36f77f2acbe90b --- /dev/null +++ b/react-syntax-highlighter/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-syntax-highlighter-tests.tsx" + ] +} \ No newline at end of file diff --git a/react/index.d.ts b/react/index.d.ts index dd2add0e0ed29c..49ff853c4caed4 100644 --- a/react/index.d.ts +++ b/react/index.d.ts @@ -177,7 +177,7 @@ declare namespace React { // on the existence of `children` in `P`, then we should remove this. props: P & { children?: ReactNode }; state: S; - context: {}; + context: any; refs: { [key: string]: ReactInstance }; diff --git a/reactcss/index.d.ts b/reactcss/index.d.ts new file mode 100644 index 00000000000000..7f610cc342f869 --- /dev/null +++ b/reactcss/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for ReactCSS v1.0.0 +// Project: http://reactcss.com/ +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace ReactCSS { + interface LoopableProps { + "first-child"?: boolean + "last-child"?: boolean + even?: boolean + odd?: boolean + [nthChild: string]: boolean + } + + interface HoverProps { + hover?: boolean + } + + interface Classes { + default: any + [scope: string]: any + } +} + +declare module "reactcss" { + export type LoopableProps = ReactCSS.LoopableProps + export function hover
(component: React.ComponentClass | React.StatelessComponent): React.ComponentClass + export function loop(i: number, length: number): ReactCSS.LoopableProps + export default function reactCSS (classes: ReactCSS.Classes, ...activations: Array): any +} diff --git a/reactcss/reactcss-tests.tsx b/reactcss/reactcss-tests.tsx new file mode 100644 index 00000000000000..852976b0d24cf5 --- /dev/null +++ b/reactcss/reactcss-tests.tsx @@ -0,0 +1,21 @@ +import * as React from "react" +import { StatelessComponent } from "react" +import { render } from "react-dom" +import { default as reactCSS, hover, loop } from "reactcss" + +interface TestProps extends ReactCSS.HoverProps {} + +var styles: any = reactCSS({ + default : {}, + hover : {} +}, { hover : true }) + +var loopProps: ReactCSS.LoopableProps = loop(1, 10) + +var TestComponent: StatelessComponent +var Test = hover(TestComponent) + +render( + , + document.getElementById("main") +) diff --git a/reactcss/tsconfig.json b/reactcss/tsconfig.json new file mode 100644 index 00000000000000..b3a43ddee49452 --- /dev/null +++ b/reactcss/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "index.d.ts", + "reactcss-tests.tsx" + ] +} \ No newline at end of file diff --git a/redux-storage/redux-storage-tests.ts b/redux-storage/redux-storage-tests.ts index 2be0d91db24a9e..4e84468a64fa51 100644 --- a/redux-storage/redux-storage-tests.ts +++ b/redux-storage/redux-storage-tests.ts @@ -8,6 +8,7 @@ import createReactNativeAsyncStorageEngine from "redux-storage-engine-reactnativ interface TestState { a: number; b: string; + c: string; } function rootReducer(state: TestState, action: Action): TestState { @@ -16,7 +17,7 @@ function rootReducer(state: TestState, action: Action): TestState { const enhancedReducer = reducer(rootReducer, reduxStorageImmutableMerger); -const storageEngine = createEngine("test"); +const storageEngine = filter(createEngine("test"), ['a', 'b'], ['c']); const initialStateLoader = createLoader(storageEngine); diff --git a/redux-storage/redux-storage.d.ts b/redux-storage/redux-storage.d.ts index dac23aeebc470b..f04ee2b522d48a 100644 --- a/redux-storage/redux-storage.d.ts +++ b/redux-storage/redux-storage.d.ts @@ -26,7 +26,7 @@ declare module "redux-storage" { * Save * @param state */ - save(state: any): PromiseLike + save(state: any): PromiseLike; } export interface StateMerger { @@ -66,28 +66,33 @@ declare module "redux-storage" { declare module "redux-storage-decorator-filter" { import { StorageEngine } from "redux-storage"; - interface WhitelistArg { + interface FilterList { [key: number]: string | string[]; } /** * Filter decorator for redux-storage to only store a subset of the whole state tree. - * @param engine - * @param whitelist + * @param {StorageEngine} engine the redux storage engine + * @param {FilterList} [whitelist=[]] keys that will be stored. + * @param {FilterList} [blacklist=[]] keys that won't be stored. * @example + * import filter from 'redux-storage-decorator-filter'; * engine = filter(engine, [ - * 'simple-key', + * 'whitelisted-key', * ['nested', 'key'], * ['another', 'very', 'nested', 'key'] + * ], [ + * 'blacklisted-key', + * ['nested', 'blacklisted-key'] * ]); */ - export default function(engine: StorageEngine, whitelist?: WhitelistArg): StorageEngine; + export default function (engine: StorageEngine, whitelist?: FilterList, blacklist?: FilterList): StorageEngine; } declare module "redux-storage-engine-localstorage" { import { StorageEngine } from "redux-storage"; - export interface LocalStorageEngine extends StorageEngine {} + export interface LocalStorageEngine extends StorageEngine { } /** * Create local storage @@ -99,7 +104,7 @@ declare module "redux-storage-engine-localstorage" { declare module "redux-storage-engine-reactnativeasyncstorage" { import { StorageEngine } from "redux-storage"; - export interface ReactNativeAsyncStorageEngine extends StorageEngine {} + export interface ReactNativeAsyncStorageEngine extends StorageEngine { } /** * Create React Native Async Storage diff --git a/spotify-api/index.d.ts b/spotify-api/index.d.ts index b175080ac85d50..d0f655358abe73 100644 --- a/spotify-api/index.d.ts +++ b/spotify-api/index.d.ts @@ -5,6 +5,9 @@ // Release comments: // ----------------- + +// The audio analysis object is not yet in the Object Model at Spotify, therefore it is typed as any in this file. + // TrackObjects and AlbumObjects is specified in the docs as always having the available_markets property, // but when it is sent in https://developer.spotify.com/web-api/console/get-current-user-saved-tracks // the available_markets are missing. Therefore it is marked as optional in this source code. @@ -37,6 +40,69 @@ declare namespace SpotifyApi { offset?: number; } + /** + * Object for use in Recommendations Based on Seeds. + * See: [Recommendations Based on Seeds](https://developer.spotify.com/web-api/get-recommendations/) + * + * @limit q Optional. The target size of the list of recommended tracks. For seeds with unusually small pools or when highly restrictive filtering is applied, it may be impossible to generate the requested number of recommended tracks. Debugging information for such cases is available in the response. Default: 20. Minimum: 1. Maximum: 100. + * @market q Optional. An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking. Because min_*, max_* and target_* are applied to pools before relinking, the generated results may not precisely match the filters applied. Original, non-relinked tracks are available via the linked_from attribute of the relinked track response. + * @max_ q Optional. Multiple values. For each tunable track attribute, a hard ceiling on the selected track attribute’s value can be provided. See tunable track attributes below for the list of available options. For example, max_instrumentalness=0.35 would filter out most tracks that are likely to be instrumental. + * @min_ q Optional. Multiple values. For each tunable track attribute, a hard floor on the selected track attribute’s value can be provided. See tunable track attributes below for the list of available options. For example, min_tempo=140 would restrict results to only those tracks with a tempo of greater than 140 beats per minute. + * @seed_artists q A comma separated list of Spotify IDs for seed artists. Up to 5 seed values may be provided in any combination of seed_artists, seed_tracks and seed_genres. + * @seed_genres q A comma separated list of any genres in the set of available genre seeds. Up to 5 seed values may be provided in any combination of seed_artists, seed_tracks and seed_genres. + * @seed_tracks q A comma separated list of Spotify IDs for a seed track. Up to 5 seed values may be provided in any combination of seed_artists, seed_tracks and seed_genres. + * @target_ q Optional. Multiple values. For each of the tunable track attributes (below) a target value may be provided. Tracks with the attribute values nearest to the target values will be preferred. For example, you might request target_energy=0.6 and target_danceability=0.8. All target values will be weighed equally in ranking results. + */ + interface RecommendationsOptionsObject { + limit?: number, + market?: string, + max_acousticness?: number, + max_danceability?: number, + max_duration_ms?: number, + max_energy?: number, + max_instrumentalness?: number, + max_key?: number, + max_liveness?: number, + max_loudness?: number, + max_mode?: number, + max_popularity?: number, + max_speechiness?: number, + max_tempo?: number, + max_time_signature?: number, + max_valence?: number, + min_acousticness?: number, + min_danceability?: number, + min_duration_ms?: number, + min_energy?: number, + min_instrumentalness?: number, + min_key?: number, + min_liveness?: number, + min_loudness?: number, + min_mode?: number, + min_popularity?: number, + min_speechiness?: number, + min_tempo?: number, + min_time_signature?: number, + min_valence?: number, + seed_artists?: string, // Comma separated string + seed_genres?: string, // Comma separated string + seed_tracks?: string, // Comma separated string + target_acousticness?: number + target_danceability?: number + target_duration_ms?: number + target_energy?: number + target_instrumentalness?: number + target_key?: number + target_liveness?: number + target_loudness?: number + target_mode?: number + target_popularity?: number + target_speechiness?: number + target_tempo?: number + target_time_signature?: number + target_valence?: number + } + // // Responses from the Spotify Web API in the same order as in the API endpoint docs seen here: @@ -62,13 +128,17 @@ declare namespace SpotifyApi { /** * Get an Album + * * GET /v1/albums/{id} + * https://developer.spotify.com/web-api/get-album/ */ interface SingleAlbumResponse extends AlbumObjectFull {} /** * Get Several Albums - * GET /v1/albums + * + * GET /v1/albums?ids={ids} + * https://developer.spotify.com/web-api/get-several-albums/ */ interface MultipleAlbumsResponse { albums: AlbumObjectFull[] @@ -76,19 +146,25 @@ declare namespace SpotifyApi { /** * Get an Album’s Tracks + * * GET /v1/albums/{id}/tracks + * https://developer.spotify.com/web-api/get-albums-tracks/ */ interface AlbumTracksResponse extends PagingObject {} /** * Get an Artist + * * GET /v1/artists/{id} + * https://developer.spotify.com/web-api/get-artist/ */ interface SingleArtistResponse extends ArtistObjectFull {} /** * Get Several Artists - * GET /v1/artists + * + * /v1/artists?ids={ids} + * https://developer.spotify.com/web-api/get-several-artists/ */ interface MultipleArtistsResponse { artists: ArtistObjectFull[] @@ -96,13 +172,17 @@ declare namespace SpotifyApi { /** * Get an Artist’s Albums + * * GET /v1/artists/{id}/albums + * https://developer.spotify.com/web-api/get-artists-albums/ */ interface ArtistsAlbumsResponse extends PagingObject {} /** * Get an Artist’s Top Tracks + * * GET /v1/artists/{id}/top-tracks + * https://developer.spotify.com/web-api/get-artists-top-tracks/ */ interface ArtistsTopTracksResponse { tracks: TrackObjectFull[] @@ -110,21 +190,38 @@ declare namespace SpotifyApi { /** * Get an Artist’s Related Artists + * * GET /v1/artists/{id}/related-artists + * https://developer.spotify.com/web-api/get-related-artists/ */ interface ArtistsRelatedArtistsResponse { artists: ArtistObjectFull[] } + /** + * Get Audio Analysis for a Track + * + * GET /v1/audio-analysis/{id} + * https://developer.spotify.com/web-api/get-audio-analysis/ + * + * At the time of typing, the Audio Analysis Object is absent from the Object Model, so it is typed as any. + * Object Model: https://developer.spotify.com/web-api/object-model/ + */ + interface AudioAnalysisResponse extends Object {} + /** * Get audio features for a track + * * GET /v1/audio-features/{id} + * https://developer.spotify.com/web-api/get-audio-features/ */ interface AudioFeaturesResponse extends AudioFeaturesObject {} /** * Get audio features for several tracks - * GET /v1/audio-features + * + * GET /v1/audio-features?ids={ids} + * https://developer.spotify.com/get-several-audio-features/ */ interface MultipleAudioFeaturesResponse { "audio_features": AudioFeaturesObject[] @@ -132,7 +229,9 @@ declare namespace SpotifyApi { /** * Get a list of featured playlists + * * GET /v1/browse/featured-playlists + * https://developer.spotify.com/web-api/get-list-featured-playlists/ */ interface ListOfFeaturedPlaylistsResponse { message?: string, @@ -141,7 +240,9 @@ declare namespace SpotifyApi { /** * Get a list of new releases + * * GET /v1/browse/new-releases + * https://developer.spotify.com/web-api/get-list-new-releases/ */ interface ListOfNewReleasesResponse { message?: string, @@ -150,7 +251,9 @@ declare namespace SpotifyApi { /** * Get a list of categories + * * GET /v1/browse/categories + * https://developer.spotify.com/web-api/get-list-categories/ */ interface MultipleCategoriesResponse { categories: PagingObject @@ -158,13 +261,17 @@ declare namespace SpotifyApi { /** * Get a category - * GET /v1/browse/categories/{category_id} + * + * GET /v1/browse/categories/{id} + * https://developer.spotify.com/web-api/get-category/ */ interface SingleCategoryResponse extends CategoryObject {} /** * Get a categorys playlists + * * GET /v1/browse/categories/{id}/playlists + * https://developer.spotify.com/web-api/get-categorys-playlists/ */ interface CategoryPlaylistsReponse { playlists: PagingObject @@ -172,13 +279,17 @@ declare namespace SpotifyApi { /** * Get Current User’s Profile + * * GET /v1/me + * https://developer.spotify.com/web-api/get-current-users-profile/ */ interface CurrentUsersProfileResponse extends UserObjectPrivate {} /** * Get User’s Followed Artists - * GET /v1/me/following?type=artist + * + * GET /v1/me/following + * https://developer.spotify.com/web-api/get-followed-artists/ */ interface UsersFollowedArtistsResponse { artists: CursorBasedPagingObject @@ -186,103 +297,147 @@ declare namespace SpotifyApi { /** * Follow artists or users + * * PUT /v1/me/following + * https://developer.spotify.com/web-api/follow-artists-users/ */ interface FollowArtistsOrUsersResponse extends VoidResponse {} /** * Unfollow artists or users + * * DELETE /v1/me/following + * https://developer.spotify.com/web-api/unfollow-artists-users/ */ interface UnfollowArtistsOrUsersResponse extends VoidResponse {} /** * Check if User Follows Users or Artists + * * GET /v1/me/following/contains + * https://developer.spotify.com/web-api/check-current-user-follows/ */ interface UserFollowsUsersOrArtistsResponse extends Array {} /** * Follow a Playlist + * * PUT /v1/users/{owner_id}/playlists/{playlist_id}/followers + * https://developer.spotify.com/web-api/follow-playlist/ */ interface FollowPlaylistReponse extends VoidResponse {} /** * Unfollow a Playlist + * * DELETE /v1/users/{owner_id}/playlists/{playlist_id}/followers + * https://developer.spotify.com/web-api/unfollow-playlist/ */ interface UnfollowPlaylistReponse extends VoidResponse {} /** * Save tracks for user + * * PUT /v1/me/tracks?ids={ids} + * https://developer.spotify.com/web-api/save-tracks-user/ */ interface SaveTracksForUserResponse extends VoidResponse {} /** * Get user's saved tracks + * * GET /v1/me/tracks + * https://developer.spotify.com/web-api/get-users-saved-tracks/ */ interface UsersSavedTracksResponse extends PagingObject {} /** * Remove User’s Saved Tracks + * * DELETE /v1/me/tracks?ids={ids} + * https://developer.spotify.com/web-api/remove-tracks-user/ */ interface RemoveUsersSavedTracksResponse extends VoidResponse {} /** * Check User’s Saved Tracks - * GET /v1/me/tracks/contains + * + * GET /v1/me/tracks/contains?ids={ids} + * https://developer.spotify.com/web-api/check-users-saved-tracks/ */ interface CheckUsersSavedTracksResponse extends Array {} /** * Save albums for user + * * PUT /v1/me/albums?ids={ids} + * https://developer.spotify.com/web-api/save-albums-user/ */ interface SaveAlbumsForUserResponse extends VoidResponse {} /** * Get user's saved albums + * * GET /v1/me/albums + * https://developer.spotify.com/web-api/get-users-saved-albums/ */ - interface UsersSavedAlbumsResponse extends PagingObject {} + interface UsersSavedAlbumsResponse extends PagingObject {} /** * Remove Albums for Current User + * * DELETE /v1/me/albums?ids={ids} + * https://developer.spotify.com/web-api/remove-albums-user/ */ interface RemoveAlbumsForUserResponse extends VoidResponse {} /** * Check user's saved albums - * DELETE /v1/me/albums/contains?ids={ids} + * + * GET /v1/me/albums/contains?ids={ids} + * https://developer.spotify.com/web-api/check-users-saved-albums/ */ interface CheckUserSavedAlbumsResponse extends Array {} /** - * Get a User’s Top Artists and Tracks + * Get a User’s Top Artists and Tracks (Note: This is only Artists) + * * GET /v1/me/top/{type} + * https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/ */ - interface UsersTopTracksResponse extends PagingObject {} + interface UsersTopArtistsResponse extends PagingObject {} /** - * Get a User’s Top Artists and Tracks + * Get a User’s Top Artists and Tracks (Note: This is only Tracks) + * * GET /v1/me/top/{type} + * https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/ */ - interface UsersTopArtistsResponse extends PagingObject {} + interface UsersTopTracksResponse extends PagingObject {} /** * Get recommendations based on seeds + * * GET /v1/recommendations + * https://developer.spotify.com/get-recommendations/ */ interface RecommendationsFromSeedsResponse extends RecommendationsObject {} + /** + * Get available genre seeds + * + * GET /v1/recommendations/available-genre-seeds + * https://developer.spotify.com/web-api/get-recommendations/#available-genre-seeds + */ + interface AvailableGenreSeedsResponse { + "genres": string[] + } + /** * Search for an album + * * GET /v1/search?type=album + * https://developer.spotify.com/web-api/search-item/ */ interface AlbumSearchResponse { albums: PagingObject @@ -290,7 +445,9 @@ declare namespace SpotifyApi { /** * Search for an artist + * * GET /v1/search?type=artist + * https://developer.spotify.com/web-api/search-item/ */ interface ArtistSearchResponse { artists: PagingObject @@ -298,7 +455,9 @@ declare namespace SpotifyApi { /** * Search for a playlist + * * GET /v1/search?type=playlist + * https://developer.spotify.com/web-api/search-item/ */ interface PlaylistSearchResponse { playlists: PagingObject @@ -306,7 +465,9 @@ declare namespace SpotifyApi { /** * Search for a track + * * GET /v1/search?type=track + * https://developer.spotify.com/web-api/search-item/ */ interface TrackSearchResponse { tracks: PagingObject @@ -314,13 +475,17 @@ declare namespace SpotifyApi { /** * Get a track + * * GET /v1/tracks/{id} + * https://developer.spotify.com/web-api/get-track/ */ interface SingleTrackResponse extends TrackObjectFull {} /** * Get multiple tracks + * * GET /v1/tracks?ids={ids} + * https://developer.spotify.com/web-api/get-several-tracks/ */ interface MultipleTracksResponse { tracks: TrackObjectFull[] @@ -328,73 +493,97 @@ declare namespace SpotifyApi { /** * Get user profile + * * GET /v1/users/{user_id} + * https://developer.spotify.com/web-api/get-users-profile/ */ interface UserProfileResponse extends UserObjectPublic {} /** * Get a list of a user's playlists + * * GET /v1/users/{user_id}/playlists + * https://developer.spotify.com/web-api/get-list-users-playlists/ */ interface ListOfUsersPlaylistsResponse extends PagingObject {} /** * Get a list of the current user's playlists + * * GET /v1/me/playlists + * https://developer.spotify.com/web-api/get-list-users-playlists/ */ interface ListOfCurrentUsersPlaylistsResponse extends PagingObject {} /** * Get a playlist + * * GET /v1/users/{user_id}/playlists/{playlist_id} + * https://developer.spotify.com/web-api/get-playlist/ */ interface SinglePlaylistResponse extends PlaylistObjectFull {} /** * Get a playlist's tracks + * * GET /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/get-playlists-tracks/ */ interface PlaylistTrackResponse extends PagingObject {} /** * Create a Playlist + * * POST /v1/users/{user_id}/playlists + * https://developer.spotify.com/web-api/create-playlist/ */ interface CreatePlaylistResponse extends PlaylistObjectFull {} /** * Change a Playlist’s Details + * * PUT /v1/users/{user_id}/playlists/{playlist_id} + * https://developer.spotify.com/web-api/change-playlist-details/ */ interface ChangePlaylistDetailsReponse extends VoidResponse {} /** * Add Tracks to a Playlist + * * POST /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/add-tracks-to-playlist/ */ interface AddTracksToPlaylistResponse extends PlaylistSnapshotResponse {} /** * Remove Tracks from a Playlist + * * DELETE /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/remove-tracks-playlist/ */ interface RemoveTracksFromPlaylistResponse extends PlaylistSnapshotResponse {} /** * Reorder a Playlist’s Tracks + * * PUT /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/reorder-playlists-tracks/ */ interface ReorderPlaylistTracksResponse extends PlaylistSnapshotResponse {} /** * Replace a Playlist’s Tracks + * * PUT /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/replace-playlists-tracks/ */ interface ReplacePlaylistTracksResponse extends VoidResponse {} /** * Check if Users Follow a Playlist + * * GET /v1/users/{user_id}/playlists/{playlist_id}/followers/contains + * https://developer.spotify.com/web-api/check-user-following-playlist/ */ interface UsersFollowPlaylistReponse extends Array {} diff --git a/spotify-api/spotify-api-tests.ts b/spotify-api/spotify-api-tests.ts index a7d77da67bb06b..b6d57a5574a3c0 100644 --- a/spotify-api/spotify-api-tests.ts +++ b/spotify-api/spotify-api-tests.ts @@ -1,22 +1,24 @@ +// Tests for the type definitions for The Spotify Web API (including changes March 29th 2016) +// Project: https://developer.spotify.com/web-api/ +// Definitions by: Niels Kristian Hansen Skovmand +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + /* * This test file contains the sample output from The Spotify Web Api obtained from [The Web API Console](https://developer.spotify.com/web-api/console/) - * The standard suggested values for input were used. - * - * Updated for the March 29th, 2016 changes to the Spotify Web Api. * - * Combined with the typings it should compile without errors. + * Run the tests (they should always compile without any errors): + * tsc spotify-api-tests.ts --target es6 --noImplicitAny * * The order of tests is the same as on [The Spotify Web Api](https://developer.spotify.com/web-api/endpoint-reference/) - * To find tests, search for "* Tests" instead of scrolling to keep sane. */ - - - /** - * Tests the response of https://developer.spotify.com/web-api/get-album/ + * Get an Album + * + * GET /v1/albums/{id} + * https://developer.spotify.com/web-api/get-album/ */ const getSingleAlbum : SpotifyApi.SingleAlbumResponse = { "album_type" : "album", @@ -401,9 +403,11 @@ const getSingleAlbum : SpotifyApi.SingleAlbumResponse = { - /** - * Tests https://developer.spotify.com/web-api/get-several-albums/ + * Get Several Albums + * + * GET /v1/albums?ids={ids} + * https://developer.spotify.com/web-api/get-several-albums/ */ const getMultipleAlbumsResponse : SpotifyApi.MultipleAlbumsResponse = { "albums" : [ { @@ -2236,7 +2240,10 @@ const getMultipleAlbumsResponse : SpotifyApi.MultipleAlbumsResponse = { /** - * Tests https://developer.spotify.com/web-api/get-albums-tracks/ + * Get an Album’s Tracks + * + * GET /v1/albums/{id}/tracks + * https://developer.spotify.com/web-api/get-albums-tracks/ */ const getAlbumTracks : SpotifyApi.AlbumTracksResponse = { "href" : "https://api.spotify.com/v1/albums/6akEvsycLGftJxYudPjmqK/tracks?offset=0&limit=2", @@ -2302,7 +2309,10 @@ const getAlbumTracks : SpotifyApi.AlbumTracksResponse = { /** - * Tests https://developer.spotify.com/web-api/get-artist/ + * Get an Artist + * + * GET /v1/artists/{id} + * https://developer.spotify.com/web-api/get-artist/ */ const getAnArtist : SpotifyApi.SingleArtistResponse = { "external_urls" : { @@ -2341,7 +2351,10 @@ const getAnArtist : SpotifyApi.SingleArtistResponse = { /** - * Tests https://developer.spotify.com/web-api/get-several-artists/ + * Get Several Artists + * + * GET /v1/artists + * https://developer.spotify.com/web-api/get-several-artists/ */ const getSeveralArtists : SpotifyApi.MultipleArtistsResponse = { "artists" : [ { @@ -2415,7 +2428,10 @@ const getSeveralArtists : SpotifyApi.MultipleArtistsResponse = { /** - * Tests https://developer.spotify.com/web-api/get-artists-albums/ + * Get an Artist’s Albums + * + * GET /v1/artists/{id}/albums + * https://developer.spotify.com/web-api/get-artists-albums/ */ const getArtistsAlbums : SpotifyApi.ArtistsAlbumsResponse = { "href" : "https://api.spotify.com/v1/artists/1vCWHaC5f2uS3yhpwWbIA6/albums?offset=0&limit=2&album_type=single", @@ -2477,6 +2493,12 @@ const getArtistsAlbums : SpotifyApi.ArtistsAlbumsResponse = { +/** + * Get an Artist’s Top Tracks + * + * GET /v1/artists/{id}/top-tracks + * https://developer.spotify.com/web-api/get-artists-top-tracks/ + */ const getArtistsTopTracks : SpotifyApi.ArtistsTopTracksResponse = { "tracks" : [ { "album" : { @@ -3042,6 +3064,12 @@ const getArtistsTopTracks : SpotifyApi.ArtistsTopTracksResponse = { +/** + * Get an Artist’s Related Artists + * + * GET /v1/artists/{id}/related-artists + * https://developer.spotify.com/web-api/get-related-artists/ + */ const getArtistRelatedArtists : SpotifyApi.ArtistsRelatedArtistsResponse = { "artists" : [ { "external_urls" : { @@ -3687,7 +3715,10 @@ const getArtistRelatedArtists : SpotifyApi.ArtistsRelatedArtistsResponse = { /** - * Tests https://developer.spotify.com/get-audio-features/ + * Get audio features for a track + * + * GET /v1/audio-features/{id} + * https://developer.spotify.com/web-api/get-audio-features/ */ const singleAudioFeaturesResponse : SpotifyApi.AudioFeaturesResponse = { "danceability": 0.281, @@ -3715,7 +3746,10 @@ const singleAudioFeaturesResponse : SpotifyApi.AudioFeaturesResponse = { /** - * Tests https://developer.spotify.com/web-api/get-several-audio-features/ + * Get audio features for several tracks + * + * GET /v1/audio-features?ids={ids} + * https://developer.spotify.com/get-several-audio-features/ */ const severalAudioFeaturesResponse : SpotifyApi.MultipleAudioFeaturesResponse = { audio_features: [ { "danceability": 0.808, @@ -3782,7 +3816,10 @@ const severalAudioFeaturesResponse : SpotifyApi.MultipleAudioFeaturesResponse = /** - * Tests https://developer.spotify.com/web-api/get-list-featured-playlists/ + * Get a list of featured playlists + * + * GET /v1/browse/featured-playlists + * https://developer.spotify.com/web-api/get-list-featured-playlists/ */ const featuredPlaylists : SpotifyApi.ListOfFeaturedPlaylistsResponse = { "message" : "Enjoy a mellow afternoon.", @@ -3861,7 +3898,10 @@ const featuredPlaylists : SpotifyApi.ListOfFeaturedPlaylistsResponse = { /** - * Tests https://developer.spotify.com/web-api/get-list-new-releases/ + * Get a list of new releases + * + * GET /v1/browse/new-releases + * https://developer.spotify.com/web-api/get-list-new-releases/ */ const newReleases : SpotifyApi.ListOfNewReleasesResponse = { "albums" : { @@ -4359,7 +4399,10 @@ const newReleases : SpotifyApi.ListOfNewReleasesResponse = { /** - * Tests https://developer.spotify.com/web-api/get-list-categories/ + * Get a list of categories + * + * GET /v1/browse/categories + * https://developer.spotify.com/web-api/get-list-categories/ */ const listOfCategories : SpotifyApi.MultipleCategoriesResponse = { "categories" : { @@ -4557,7 +4600,10 @@ const listOfCategories : SpotifyApi.MultipleCategoriesResponse = { /** - * Tests https://developer.spotify.com/web-api/get-category/ + * Get a category + * + * GET /v1/browse/categories/{category_id} + * https://developer.spotify.com/web-api/get-category/ */ const category : SpotifyApi.SingleCategoryResponse = { "href" : "https://api.spotify.com/v1/browse/categories/rock", @@ -4574,7 +4620,10 @@ const category : SpotifyApi.SingleCategoryResponse = { /** - * Tests https://developer.spotify.com/web-api/get-categorys-playlists/ + * Get a categorys playlists + * + * GET /v1/browse/categories/{id}/playlists + * https://developer.spotify.com/web-api/get-categorys-playlists/ */ const categoryPlaylists : SpotifyApi.CategoryPlaylistsReponse = { "playlists" : { @@ -4651,8 +4700,12 @@ const categoryPlaylists : SpotifyApi.CategoryPlaylistsReponse = { + /** - * Tests https://developer.spotify.com/web-api/get-current-users-profile/ + * Get Current User’s Profile + * + * GET /v1/me + * https://developer.spotify.com/web-api/get-current-users-profile/ */ const userProfilePrivate : SpotifyApi.CurrentUsersProfileResponse = { "birthdate" : "1982-06-29", @@ -4678,7 +4731,10 @@ const userProfilePrivate : SpotifyApi.CurrentUsersProfileResponse = { /** - * Tests https://developer.spotify.com/web-api/get-followed-artists/ + * Get User’s Followed Artists + * + * GET /v1/me/following?type=artist + * https://developer.spotify.com/web-api/get-followed-artists/ */ const followedArtists : SpotifyApi.UsersFollowedArtistsResponse = { "artists" : { @@ -4757,7 +4813,10 @@ const followedArtists : SpotifyApi.UsersFollowedArtistsResponse = { /** - * Tests https://developer.spotify.com/web-api/follow-artists-users/ + * Follow artists or users + * + * PUT /v1/me/following + * https://developer.spotify.com/web-api/follow-artists-users/ */ const followArtistsOrUsers : SpotifyApi.FollowArtistsOrUsersResponse = {} @@ -4765,7 +4824,10 @@ const followArtistsOrUsers : SpotifyApi.FollowArtistsOrUsersResponse = {} /** - * Tests https://developer.spotify.com/web-api/unfollow-artists-users/ + * Unfollow artists or users + * + * DELETE /v1/me/following + * https://developer.spotify.com/web-api/unfollow-artists-users/ */ const unfollowArtistsOrUsers : SpotifyApi.UnfollowArtistsOrUsersResponse = {} @@ -4773,7 +4835,10 @@ const unfollowArtistsOrUsers : SpotifyApi.UnfollowArtistsOrUsersResponse = {} /** - * Tests https://developer.spotify.com/web-api/check-current-user-follows/ + * Check if User Follows Users or Artists + * + * GET /v1/me/following/contains + * https://developer.spotify.com/web-api/check-current-user-follows/ */ const checkCurrentUserFollows : SpotifyApi.UserFollowsUsersOrArtistsResponse = [ true, true, false ]; @@ -4781,7 +4846,10 @@ const checkCurrentUserFollows : SpotifyApi.UserFollowsUsersOrArtistsResponse = [ /** - * Tests https://developer.spotify.com/web-api/follow-playlist/ + * Follow a Playlist + * + * PUT /v1/users/{owner_id}/playlists/{playlist_id}/followers + * https://developer.spotify.com/web-api/follow-playlist/ */ const followPlaylist : SpotifyApi.FollowPlaylistReponse = {}; @@ -4789,7 +4857,10 @@ const followPlaylist : SpotifyApi.FollowPlaylistReponse = {}; /** - * Tests https://developer.spotify.com/web-api/unfollow-playlist/ + * Unfollow a Playlist + * + * DELETE /v1/users/{owner_id}/playlists/{playlist_id}/followers + * https://developer.spotify.com/web-api/unfollow-playlist/ */ const unfollowPlaylist : SpotifyApi.UnfollowPlaylistReponse = {}; @@ -4797,7 +4868,10 @@ const unfollowPlaylist : SpotifyApi.UnfollowPlaylistReponse = {}; /** - * Tests https://developer.spotify.com/web-api/save-tracks-user/ + * Save tracks for user + * + * PUT /v1/me/tracks?ids={ids} + * https://developer.spotify.com/web-api/save-tracks-user/ */ const saveTracksForUser : SpotifyApi.SaveTracksForUserResponse = {}; @@ -4805,7 +4879,10 @@ const saveTracksForUser : SpotifyApi.SaveTracksForUserResponse = {}; /** - * Tests https://developer.spotify.com/web-api/console/get-current-user-saved-tracks + * Get user's saved tracks + * + * GET /v1/me/tracks + * https://developer.spotify.com/web-api/get-users-saved-tracks/ */ const getSavedTracks : SpotifyApi.UsersSavedTracksResponse = { "href" : "https://api.spotify.com/v1/me/tracks?offset=0&limit=5&market=DK", @@ -5101,7 +5178,10 @@ const getSavedTracks : SpotifyApi.UsersSavedTracksResponse = { /** - * Tests https://developer.spotify.com/web-api/remove-tracks-user/ + * Remove User’s Saved Tracks + * + * DELETE /v1/me/tracks?ids={ids} + * https://developer.spotify.com/web-api/remove-tracks-user/ */ const removeUsersTracks : SpotifyApi.RemoveUsersSavedTracksResponse = {}; @@ -5109,7 +5189,10 @@ const removeUsersTracks : SpotifyApi.RemoveUsersSavedTracksResponse = {}; /** - * Tests https://developer.spotify.com/web-api/check-users-saved-tracks/ + * Check User’s Saved Tracks + * + * GET /v1/me/tracks/contains?ids={ids} + * https://developer.spotify.com/web-api/check-users-saved-tracks/ */ const checkUsersTracks : SpotifyApi.CheckUserSavedAlbumsResponse = [ false, false, true ]; @@ -5117,15 +5200,167 @@ const checkUsersTracks : SpotifyApi.CheckUserSavedAlbumsResponse = [ false, fals /** - * Tests https://developer.spotify.com/web-api/save-albums-user/ + * Save albums for user + * + * PUT /v1/me/albums?ids={ids} + * https://developer.spotify.com/web-api/save-albums-user/ */ const saveAlbumForUser : SpotifyApi.SaveAlbumsForUserResponse = {}; +/** + * Get user's saved albums + * + * GET /v1/me/albums + * https://developer.spotify.com/web-api/get-users-saved-albums/ + */ +const usersSavedAlbums : SpotifyApi.UsersSavedAlbumsResponse = { + "href" : "https://api.spotify.com/v1/me/albums?offset=0&limit=1", + "items" : [ { + "added_at" : "2015-11-26T19:13:31Z", + "album" : { + "album_type" : "album", + "artists" : [ { + "external_urls" : { + "spotify" : "https://open.spotify.com/artist/58RMTlPJKbmpmVk1AmRK3h" + }, + "href" : "https://api.spotify.com/v1/artists/58RMTlPJKbmpmVk1AmRK3h", + "id" : "58RMTlPJKbmpmVk1AmRK3h", + "name" : "Abidaz", + "type" : "artist", + "uri" : "spotify:artist:58RMTlPJKbmpmVk1AmRK3h" + } ], + "available_markets" : [ "AR", "AT", "AU", "BE", "BR", "CL", "CO", "CY", "CZ", "DE" ], + "copyrights" : [ { + "text" : "(C) 2013 Soblue Music Group AB, Under exclusive license to Universal Music AB", + "type" : "C" + }, { + "text" : "(P) 2013 Soblue Music Group AB, Under exclusive license to Universal Music AB", + "type" : "P" + } ], + "external_ids" : { + "upc" : "00602537623730" + }, + "external_urls" : { + "spotify" : "https://open.spotify.com/album/5m4VYOPoIpkV0XgOiRKkWC" + }, + "genres" : [ ], + "href" : "https://api.spotify.com/v1/albums/5m4VYOPoIpkV0XgOiRKkWC", + "id" : "5m4VYOPoIpkV0XgOiRKkWC", + "images" : [ { + "height" : 640, + "url" : "https://i.scdn.co/image/ccbb1e3bea2461e69783895e880965b171e29f4c", + "width" : 640 + }, { + "height" : 300, + "url" : "https://i.scdn.co/image/2210b7d23f320a2cab2736bd3b3b948415dd21d8", + "width" : 300 + }, { + "height" : 64, + "url" : "https://i.scdn.co/image/609153aca7f4760136d97fbaccdb4ec0757e4c9e", + "width" : 64 + } ], + "name" : "In & ut", + "popularity" : 49, + "release_date" : "2013-01-01", + "release_date_precision" : "day", + "tracks" : { + "href" : "https://api.spotify.com/v1/albums/5m4VYOPoIpkV0XgOiRKkWC/tracks?offset=0&limit=50", + "items" : [ { + "artists" : [ { + "external_urls" : { + "spotify" : "https://open.spotify.com/artist/58RMTlPJKbmpmVk1AmRK3h" + }, + "href" : "https://api.spotify.com/v1/artists/58RMTlPJKbmpmVk1AmRK3h", + "id" : "58RMTlPJKbmpmVk1AmRK3h", + "name" : "Abidaz", + "type" : "artist", + "uri" : "spotify:artist:58RMTlPJKbmpmVk1AmRK3h" + }, { + "external_urls" : { + "spotify" : "https://open.spotify.com/artist/1l63szZeUpN1m87MOD1u7K" + }, + "href" : "https://api.spotify.com/v1/artists/1l63szZeUpN1m87MOD1u7K", + "id" : "1l63szZeUpN1m87MOD1u7K", + "name" : "Chapee", + "type" : "artist", + "uri" : "spotify:artist:1l63szZeUpN1m87MOD1u7K" + }, { + "external_urls" : { + "spotify" : "https://open.spotify.com/artist/1VLf7Ncxb5Jga6eyd3jh6K" + }, + "href" : "https://api.spotify.com/v1/artists/1VLf7Ncxb5Jga6eyd3jh6K", + "id" : "1VLf7Ncxb5Jga6eyd3jh6K", + "name" : "C.U.P", + "type" : "artist", + "uri" : "spotify:artist:1VLf7Ncxb5Jga6eyd3jh6K" + } ], + "available_markets" : [ "AR", "AT", "AU", "BE", "BR", "CL", "CO", "CY", "CZ", "DE" ], + "disc_number" : 1, + "duration_ms" : 170920, + "explicit" : false, + "external_urls" : { + "spotify" : "https://open.spotify.com/track/3VNWq8rTnQG6fM1eldSpZ0" + }, + "href" : "https://api.spotify.com/v1/tracks/3VNWq8rTnQG6fM1eldSpZ0", + "id" : "3VNWq8rTnQG6fM1eldSpZ0", + "name" : "E.C.", + "preview_url" : "https://p.scdn.co/mp3-preview/f95e0dba1a76b44fa2b52da2bc273d4f1c4126a5", + "track_number" : 1, + "type" : "track", + "uri" : "spotify:track:3VNWq8rTnQG6fM1eldSpZ0" + }, + { + "artists" : [ { + "external_urls" : { + "spotify" : "https://open.spotify.com/artist/58RMTlPJKbmpmVk1AmRK3h" + }, + "href" : "https://api.spotify.com/v1/artists/58RMTlPJKbmpmVk1AmRK3h", + "id" : "58RMTlPJKbmpmVk1AmRK3h", + "name" : "Abidaz", + "type" : "artist", + "uri" : "spotify:artist:58RMTlPJKbmpmVk1AmRK3h" + } ], + "available_markets" : [ "AR", "AT", "AU", "BE", "BR", "CL", "CO", "CY", "CZ", "DE", "DK", "EE" ], + "disc_number" : 1, + "duration_ms" : 165946, + "explicit" : false, + "external_urls" : { + "spotify" : "https://open.spotify.com/track/6ZrVKylVlxkaXHj42O0q2r" + }, + "href" : "https://api.spotify.com/v1/tracks/6ZrVKylVlxkaXHj42O0q2r", + "id" : "6ZrVKylVlxkaXHj42O0q2r", + "name" : "Råknas - Radio Edit", + "preview_url" : "https://p.scdn.co/mp3-preview/a7c9a4bfa9e346e3733e9d88076ad1ae409136fb", + "track_number" : 13, + "type" : "track", + "uri" : "spotify:track:6ZrVKylVlxkaXHj42O0q2r" + } ], + "limit" : 50, + "next" : null, + "offset" : 0, + "previous" : null, + "total" : 13 + }, + "type" : "album", + "uri" : "spotify:album:5m4VYOPoIpkV0XgOiRKkWC" + } + } ], + "limit" : 1, + "next" : "https://api.spotify.com/v1/me/albums?offset=1&limit=1", + "offset" : 0, + "previous" : null, + "total" : 19 +} + + /** - * Tests https://developer.spotify.com/web-api/remove-albums-user/ + * Remove Albums for Current User + * + * DELETE /v1/me/albums?ids={ids} + * https://developer.spotify.com/web-api/remove-albums-user/ */ const removeAlbumForUser : SpotifyApi.RemoveAlbumsForUserResponse = {}; @@ -5134,14 +5369,20 @@ const removeAlbumForUser : SpotifyApi.RemoveAlbumsForUserResponse = {}; /** - * Tests https://developer.spotify.com/web-api/check-users-saved-albums/ + * Check user's saved albums + * + * DELETE /v1/me/albums/contains?ids={ids} + * https://developer.spotify.com/web-api/check-users-saved-albums/ */ const checkUsersSavedAlbums : SpotifyApi.CheckUserSavedAlbumsResponse = [ true, false, false, true ]; /** - * Tests https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/ + * Get a User’s Top Artists and Tracks (Note: This is only Artists) + * + * GET /v1/me/top/{type} + * https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/ */ const usersTopArtists : SpotifyApi.UsersTopArtistsResponse = { "items" : [ @@ -5219,8 +5460,12 @@ const usersTopArtists : SpotifyApi.UsersTopArtistsResponse = { + /** - * Tests https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/ + * Get a User’s Top Artists and Tracks (Note: This is only Tracks) + * + * GET /v1/me/top/{type} + * https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/ */ const usersTopTracks : SpotifyApi.UsersTopTracksResponse = { "items" : [ @@ -5362,7 +5607,10 @@ const usersTopTracks : SpotifyApi.UsersTopTracksResponse = { /** - * Tests + * Get recommendations based on seeds + * + * GET /v1/recommendations + * https://developer.spotify.com/get-recommendations/ */ const recommendationsBasedOnSeeds: SpotifyApi.RecommendationsFromSeedsResponse = { "tracks": [ @@ -5449,7 +5697,21 @@ const recommendationsBasedOnSeeds: SpotifyApi.RecommendationsFromSeedsResponse = /** - * Tests https://developer.spotify.com/web-api/search-item/?type=album + * Get available genre seeds + * + * GET /v1/recommendations/available-genre-seeds + * https://developer.spotify.com/web-api/get-recommendations/#available-genre-seeds + */ +const availableGenreSeeds : SpotifyApi.AvailableGenreSeedsResponse = { + "genres" : [ "acoustic", "afrobeat", "alt-rock", "alternative", "ambient", "anime", "black-metal", "bluegrass", "blues", "bossanova", "brazil", "breakbeat", "british", "cantopop", "chicago-house", "children", "chill", "classical", "club", "comedy", "country", "dance", "dancehall", "death-metal", "deep-house", "detroit-techno", "disco", "disney", "drum-and-bass", "dub", "dubstep", "edm", "electro", "electronic", "emo", "folk", "forro", "french", "funk", "garage", "german", "gospel", "goth", "grindcore", "groove", "grunge", "guitar", "happy", "hard-rock", "hardcore", "hardstyle", "heavy-metal", "hip-hop", "holidays", "honky-tonk", "house", "idm", "indian", "indie", "indie-pop", "industrial", "iranian", "j-dance", "j-idol", "j-pop", "j-rock", "jazz", "k-pop", "kids", "latin", "latino", "malay", "mandopop", "metal", "metal-misc", "metalcore", "minimal-techno", "movies", "mpb", "new-age", "new-release", "opera", "pagode", "party", "philippines-opm", "piano", "pop", "pop-film", "post-dubstep", "power-pop", "progressive-house", "psych-rock", "punk", "punk-rock", "r-n-b", "rainy-day", "reggae", "reggaeton", "road-trip", "rock", "rock-n-roll", "rockabilly", "romance", "sad", "salsa", "samba", "sertanejo", "show-tunes", "singer-songwriter", "ska", "sleep", "songwriter", "soul", "soundtracks", "spanish", "study", "summer", "swedish", "synth-pop", "tango", "techno", "trance", "trip-hop", "turkish", "work-out", "world-music" ] +} + + +/** + * Search for an album + * + * GET /v1/search?type=album + * https://developer.spotify.com/web-api/search-item/ */ const searchAlbums : SpotifyApi.AlbumSearchResponse = { "albums" : { @@ -5515,7 +5777,10 @@ const searchAlbums : SpotifyApi.AlbumSearchResponse = { /** - * Tests https://developer.spotify.com/web-api/search-item/?type=artist + * Search for an artist + * + * GET /v1/search?type=artist + * https://developer.spotify.com/web-api/search-item/ */ const searchArtists : SpotifyApi.ArtistSearchResponse = { "artists" : { @@ -5561,7 +5826,10 @@ const searchArtists : SpotifyApi.ArtistSearchResponse = { /** - * Tests https://developer.spotify.com/web-api/search-item/?type=playlist + * Search for a playlist + * + * GET /v1/search?type=playlist + * https://developer.spotify.com/web-api/search-item/ */ const searchPlaylists : SpotifyApi.PlaylistSearchResponse = { "playlists" : { @@ -5655,7 +5923,10 @@ const searchPlaylists : SpotifyApi.PlaylistSearchResponse = { /** - * Tests https://developer.spotify.com/web-api/search-item/?type=track + * Search for a track + * + * GET /v1/search?type=track + * https://developer.spotify.com/web-api/search-item/ */ const searchTracks : SpotifyApi.TrackSearchResponse = { "tracks" : { @@ -5799,7 +6070,10 @@ const searchTracks : SpotifyApi.TrackSearchResponse = { /** - * Tests https://developer.spotify.com/web-api/get-track/ + * Get a track + * + * GET /v1/tracks/{id} + * https://developer.spotify.com/web-api/get-track/ */ const track : SpotifyApi.SingleTrackResponse = { "album" : { @@ -5861,7 +6135,10 @@ const track : SpotifyApi.SingleTrackResponse = { /** - * Tests https://developer.spotify.com/web-api/get-several-tracks/ + * Get multiple tracks + * + * GET /v1/tracks?ids={ids} + * https://developer.spotify.com/web-api/get-several-tracks/ */ const tracks : SpotifyApi.MultipleTracksResponse = { "tracks" : [ { @@ -5977,9 +6254,11 @@ const tracks : SpotifyApi.MultipleTracksResponse = { - /** - * Tests https://developer.spotify.com/web-api/get-users-profile/ + * Get user profile + * + * GET /v1/users/{user_id} + * https://developer.spotify.com/web-api/get-users-profile/ */ const userProfile : SpotifyApi.UserProfileResponse = { "display_name" : "Ronald Pompa", @@ -6005,7 +6284,10 @@ const userProfile : SpotifyApi.UserProfileResponse = { /** - * Tests https://developer.spotify.com/web-api/get-list-users-playlists/ + * Get a list of a user's playlists + * + * GET /v1/users/{user_id}/playlists + * https://developer.spotify.com/web-api/get-list-users-playlists/ */ const usersPlaylists : SpotifyApi.ListOfUsersPlaylistsResponse = { "href" : "https://api.spotify.com/v1/users/wizzler/playlists?offset=0&limit=2", @@ -6081,7 +6363,89 @@ const usersPlaylists : SpotifyApi.ListOfUsersPlaylistsResponse = { /** - * Tests https://developer.spotify.com/web-api/get-playlist/ + * Get a list of the current user's playlists + * + * GET /v1/users/{user_id}/playlists + * https://developer.spotify.com/web-api/get-list-users-playlists/ + */ +const currentUsersPlaylists : SpotifyApi.ListOfUsersPlaylistsResponse = { + "href" : "https://api.spotify.com/v1/users/wizzler/playlists?offset=0&limit=2", + "items" : [ { + "collaborative" : false, + "external_urls" : { + "spotify" : "http://open.spotify.com/user/wizzler/playlist/6yRf9SJ1YiAhNAu7UCwgXQ" + }, + "href" : "https://api.spotify.com/v1/users/wizzler/playlists/6yRf9SJ1YiAhNAu7UCwgXQ", + "id" : "6yRf9SJ1YiAhNAu7UCwgXQ", + "images" : [ { + "height" : 640, + "url" : "https://i.scdn.co/image/5c383056e25a3e3ec858151afb70afe763c00f9b", + "width" : 640 + } ], + "name" : "My Shazam Tracks", + "owner" : { + "external_urls" : { + "spotify" : "http://open.spotify.com/user/wizzler" + }, + "href" : "https://api.spotify.com/v1/users/wizzler", + "id" : "wizzler", + "type" : "user", + "uri" : "spotify:user:wizzler" + }, + "public" : true, + "snapshot_id" : "WlQppvajE5kH/Xt5cHfHxJ6mSsFckwYixA06q7y1asdUz+m5v7pq6xb1f0FiFa7I", + "tracks" : { + "href" : "https://api.spotify.com/v1/users/wizzler/playlists/6yRf9SJ1YiAhNAu7UCwgXQ/tracks", + "total" : 1 + }, + "type" : "playlist", + "uri" : "spotify:user:wizzler:playlist:6yRf9SJ1YiAhNAu7UCwgXQ" + }, { + "collaborative" : false, + "external_urls" : { + "spotify" : "http://open.spotify.com/user/wizzler/playlist/3FJd21jWvCjGCLx7eKrext" + }, + "href" : "https://api.spotify.com/v1/users/wizzler/playlists/3FJd21jWvCjGCLx7eKrext", + "id" : "3FJd21jWvCjGCLx7eKrext", + "images" : [ { + "height" : 300, + "url" : "https://i.scdn.co/image/15858d38fdac4af890dcc634f4946c5bf83c0915", + "width" : 300 + } ], + "name" : "Video Game Masterpieces", + "owner" : { + "external_urls" : { + "spotify" : "http://open.spotify.com/user/wizzler" + }, + "href" : "https://api.spotify.com/v1/users/wizzler", + "id" : "wizzler", + "type" : "user", + "uri" : "spotify:user:wizzler" + }, + "public" : true, + "snapshot_id" : "LO0O/RGsDLEgeDC3xVR4HisMNsDqoPLE8QBRqllyvevTJ09tFWIUbjrYoEJbUhCa", + "tracks" : { + "href" : "https://api.spotify.com/v1/users/wizzler/playlists/3FJd21jWvCjGCLx7eKrext/tracks", + "total" : 33 + }, + "type" : "playlist", + "uri" : "spotify:user:wizzler:playlist:3FJd21jWvCjGCLx7eKrext" + } ], + "limit" : 2, + "next" : "https://api.spotify.com/v1/users/wizzler/playlists?offset=2&limit=2", + "offset" : 0, + "previous" : null, + "total" : 7 +}; + + + + +/** + * Get a playlist + * + * GET /v1/users/{user_id}/playlists/{playlist_id} + * https://developer.spotify.com/web-api/get-playlist/ */ const playlist : SpotifyApi.SinglePlaylistResponse = { "collaborative" : false, @@ -6339,7 +6703,10 @@ const playlist : SpotifyApi.SinglePlaylistResponse = { /** - * Tests + * Get a playlist's tracks + * + * GET /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/get-playlists-tracks/ */ const playlistTracks : SpotifyApi.PlaylistTrackResponse = { "href" : "https://api.spotify.com/v1/users/spotify_espa%C3%B1a/playlists/21THa8j9TaSGuXYNBU5tsC/tracks?offset=0&limit=3", @@ -6583,7 +6950,10 @@ const playlistTracks : SpotifyApi.PlaylistTrackResponse = { /** - * Tests https://developer.spotify.com/web-api/create-playlist/ + * Create a Playlist + * + * POST /v1/users/{user_id}/playlists + * https://developer.spotify.com/web-api/create-playlist/ */ const newPlaylist : SpotifyApi.CreatePlaylistResponse = { "collaborative" : false, @@ -6627,7 +6997,10 @@ const newPlaylist : SpotifyApi.CreatePlaylistResponse = { /** - * Tests https://developer.spotify.com/web-api/change-playlist-details/ + * Change a Playlist’s Details + * + * PUT /v1/users/{user_id}/playlists/{playlist_id} + * https://developer.spotify.com/web-api/change-playlist-details/ */ const changePlaylistDetails : SpotifyApi.ChangePlaylistDetailsReponse = {}; @@ -6635,7 +7008,10 @@ const changePlaylistDetails : SpotifyApi.ChangePlaylistDetailsReponse = {}; /** - * Tests https://developer.spotify.com/web-api/add-tracks-to-playlist/ + * Add Tracks to a Playlist + * + * POST /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/add-tracks-to-playlist/ */ const addTracksToPlaylist : SpotifyApi.AddTracksToPlaylistResponse = { "snapshot_id" : "4qQeMTnHV5LCL9w/lI9Mlu5shi2pk+iiIm6VEpmKdMPCE6adhRNTG9SXflxh8DTt" @@ -6645,7 +7021,10 @@ const addTracksToPlaylist : SpotifyApi.AddTracksToPlaylistResponse = { /** - * Tests https://developer.spotify.com/web-api/remove-tracks-playlist/ + * Remove Tracks from a Playlist + * + * DELETE /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/remove-tracks-playlist/ */ const removeTracksFromPlaylist : SpotifyApi.RemoveTracksFromPlaylistResponse = { "snapshot_id" : "t3+4ZWOqedj+bmcHHu1HKNqYfIyYAfXKlSHHykvS4KAm7hoVhDoCpn+KIuFZebZp" @@ -6655,7 +7034,10 @@ const removeTracksFromPlaylist : SpotifyApi.RemoveTracksFromPlaylistResponse = { /** - * Tests https://developer.spotify.com/web-api/reorder-playlists-tracks/ + * Reorder a Playlist’s Tracks + * + * PUT /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/reorder-playlists-tracks/ */ const reorderTracksInPlaylist : SpotifyApi.ReorderPlaylistTracksResponse = { "snapshot_id" : "t3+4ZWOqedj+bmcHHu1HKNqYfIyYAfXKlSHHykvS4KAm7hoVhDoCpn+KIuFZebZp" @@ -6665,7 +7047,10 @@ const reorderTracksInPlaylist : SpotifyApi.ReorderPlaylistTracksResponse = { /** - * Tests https://developer.spotify.com/web-api/replace-playlists-tracks/ + * Replace a Playlist’s Tracks + * + * PUT /v1/users/{user_id}/playlists/{playlist_id}/tracks + * https://developer.spotify.com/web-api/replace-playlists-tracks/ */ const replacePlaylistTracks : SpotifyApi.ReplacePlaylistTracksResponse = {}; @@ -6673,6 +7058,9 @@ const replacePlaylistTracks : SpotifyApi.ReplacePlaylistTracksResponse = {}; /** - * Tests https://developer.spotify.com/web-api/check-user-following-playlist/ + * Check if Users Follow a Playlist + * + * GET /v1/users/{user_id}/playlists/{playlist_id}/followers/contains + * https://developer.spotify.com/web-api/check-user-following-playlist/ */ const checkUserFollowsPlaylist : SpotifyApi.UsersFollowPlaylistReponse = [true, false, true]; \ No newline at end of file diff --git a/synaptic/index.d.ts b/synaptic/index.d.ts new file mode 100644 index 00000000000000..5b11b119dc560e --- /dev/null +++ b/synaptic/index.d.ts @@ -0,0 +1,648 @@ +// Type definitions for synaptic 1.0.8 +// Project: https://github.com/cazala/synaptic +// Definitions by: Markus Peloso +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Synaptic from "synaptic"; // Need this to refer to Synaptic from within the `declare global` + +declare global { + var Neuron: typeof Synaptic.Neuron; + var Layer: typeof Synaptic.Layer; + var Network: typeof Synaptic.Network; + var Architect: typeof Synaptic.Architect; + var Trainer: typeof Synaptic.Trainer; +} + +export as namespace Synaptic; + +export namespace Neuron { + type SquashingFunction = (x: number, derivate: boolean) => number; + + namespace squash { + const LOGISTIC: SquashingFunction; + const TANH: SquashingFunction; + const IDENTITY: SquashingFunction; + const HLIM: SquashingFunction; + const ReLU: SquashingFunction; + } + + class Connection { + ID: number; + from: number; + to: number; + weight: number; + gain: number; + gater: Neuron; + + constructor(from: number, to: number, weight?: number); + + static uid(): number; + } + + var connection: typeof Connection; +} + +/** + * Neurons are the basic unit of the neural network. They can be connected together, or used to gate connections between other neurons. + */ +export class Neuron { + /** + * By default, a neuron uses a Logistic Sigmoid as its squashing/activation function. + * @default LOGISTIC + */ + squash: Neuron.SquashingFunction; + + /** + * By default, a neuron uses a random bias. + * @default random + */ + bias: number; + + /** + * Neurons are the basic unit of the neural network. They can be connected together, or used to gate connections between other neurons. + */ + constructor(); + + /** + * A neuron can project a connection to another neuron. Neurons can also self-connect. + */ + project(neuron: Neuron, weight?: number): Neuron.Connection; + + /** + * A neuron can gate a connection between two neurons, or a neuron's self-connection. This allows you to create second order neural network architectures. + * @param connection + */ + gate(connection: Neuron.Connection): void; + + /** + * When a neuron activates, it computes its state from all its input connections and squashes it using its activation function, and returns the output (activation). + * @param activation You can provide the activation as a parameter (useful for neurons in the input layer. it has to be a float between 0 and 1). + */ + activate(activation?: number): number; + + /** + * After an activation, you can teach the neuron what should have been the correct output (a.k.a. train). This is done by backpropagating the error. + * @param learningRate a learning rate + * @param targetValue a target value (float between 0 and 1) + */ + propagate(learningRate: number, targetValue: number): void; + + /** + * Returns true or false whether the neuron is self-connected or not. + */ + selfconnected(): boolean; + + /** + * Returns true or false whether the neuron is connected to another neuron (parameter). + * @param neuron + */ + connected(neuron?: any): { result: any; connection: any } | boolean; + + /** + * Clears all the traces (the neuron forgets it's context, but the connections remain intact). + */ + clear(): void; + + /** + * All the connections are randomized and the traces are cleared. + */ + reset(): void; + + /** + * Hardcodes the behavior of the neuron into an optimized function. + */ + optimize(optimized?: any, layer?: any): { + memory: any; + neurons: any; + inputs: any; + outputs: any; + targets: any; + variables: any; + activation_sentences: any; + trace_sentences: any; + propagation_sentences: any; + layers: any; + }; + + static uid(): number; + + static quantity(): { neurons: number; connections: number; }; +} + +export namespace Layer { + /** + * Types of connections. + */ + enum connectionType { + /** + * It connects every neuron from layer A, to every neuron in layer B. + */ + ALL_TO_ALL, + + /** + * It connects each neuron from layer A, to one neuron in layer B. Both layers must be the same size in order to work. + */ + ONE_TO_ONE, + + /** + * Useful only in self-connections. It connects every neuron from a layer to all the other neurons in that same layer, except with itself. If this connectionType is used in a connection between different layers, it produces the same result as ALL_TO_ALL. + */ + ALL_TO_ELSE + } + + /** + * Represents a connection from one layer to another, and keeps track of its weight and gain. + */ + class LayerConnection { + ID: number; + from: any; + to: any; + selfconnection: any; + type: any; + connections: any; + list: any; + size: any; + gatedfrom: any; + + static uid(): number; + } + + var connection: typeof LayerConnection; + + /** + * Types of gates. + */ + enum gateType { + /** + * If layer C is gating connections between layer A and B, all the neurons from C gate all the input connections to B. + */ + INPUT, + + /** + * If layer C is gating connections between layer A and B, all the neurons from C gate all the output connections from A. + */ + OUTPUT, + + /** + * If layer C is gating connections between layer A and B, each neuron from C gates one connection from A to B. This is useful for gating self-connected layers. To use this kind of gateType, A, B and C must be the same size. + */ + ONE_TO_ONE + } + + interface Options { + label?: any; + squash?: Neuron.SquashingFunction; + bias?: number; + } +} + +/** + * Normally you won't work with single neurons, but use Layers instead. A layer is basically an array of neurons, they can do pretty much the same things as neurons do, but it makes the programming process faster. + */ +export class Layer { + size: number; + list: Neuron[]; + label: any; + connectedTo: any; + + /** + * Normally you won't work with single neurons, but use Layers instead. A layer is basically an array of neurons, they can do pretty much the same things as neurons do, but it makes the programming process faster. + * @param numberOfNeurons the number of neurons in that layer + */ + constructor(numberOfNeurons: number); + + /** + * A layer can project a connection to another layer. Layers can also self-connect. + * @param connectionType If not specified, the connection type is always Layer.connectionType.ALL_TO_ALL when connecting two different layers, and is Layer.connectionType.ONE_TO_ONE when connecting a layer to itself (ie myLayer.project(myLayer)). + */ + project(layer: Layer | Network, connectionType?: Layer.connectionType, weights?: any): Layer.LayerConnection; + + /** + * A layer can gate a connection between two other layers, or a layers's self-connection. + */ + gate(connection: Layer.LayerConnection, gateType: Layer.gateType): void; + + /** + * When a layer activates, it just activates all the neurons in that layer in order, and returns an array with the outputs. + * @param activation It accepts an array of activations as parameter (for input layers). + */ + activate(activation?: number[]): number[]; + + /** + * After an activation, you can teach the layer what should have been the correct output (a.k.a. train). This is done by backpropagating the error. + * @param learningRate A learning rate. + * @param targetValue A target value (array of floats between 0 and 1). + */ + propagate(learningRate: number, targetValue: number[]): void; + + /** + * True or false whether the whole layer is self-connected or not. + */ + selfconnected(): boolean; + + /** + * True of false whether the layer is connected to another layer (parameter) or not. + * @param layer + */ + connected(layer: any): any; + + /** + * Clears all the neurons in the layer. + */ + clear(): void; + + /** + * Resets all the neurons in the layer. + */ + reset(): void; + + /** + * Adds a neuron to the layer. + * @param neuron + */ + add(neuron: any): void; + + /** + * Set the squashing function and bias of all the neurons in a layer. + * @param options + */ + set(options: Layer.Options): this; + + /** + * Returns an array with all the neurons in the layer, in activation order. + */ + neurons(): Neuron[]; +} + +export namespace Network { + interface Options { + input: Layer; + hidden: Layer[]; + output: Layer; + } + + interface Optimized { + memory: Float64Array; + ownership: (memoryBuffer: Float64Array) => void; + } +} + +/** + * Networks are basically an array of layers. They have an input layer, a number of hidden layers, and an output layer. + */ +export class Network { + layer: Network.Options; + + optimized: Network.Optimized; + + /** + * Networks are basically an array of layers. They have an input layer, a number of hidden layers, and an output layer. + */ + constructor(options?: Network.Options); + /** + * A network can project a connection to another, or gate a connection between two others networks in the same way Layers do. + * @param [connectionType=Layer.connectionType.ALL_TO_ALL] + */ + project(otherNetwork: Network | Layer, connectionType?: Layer.connectionType, weights?: any): Layer.LayerConnection; + + /** + * A Network can gate a connection between two other Networks or Layers, or a Layers's self-connection. + * @param layerConnection + * @param gateType + */ + gate(layerConnection: Layer.LayerConnection, gateType: Layer.gateType): void; + + /** + * When a network is activated, an input must be provided to activate the input layer, then all the hidden layers are activated in order, and finally the output layer is activated and its activation is returned. + * @param activation + */ + activate(activation: number[]): number[]; + + /** + * You can provide a target value and a learning rate to a network and backpropagate the error from the output layer to all the hidden layers in reverse order until reaching the input layer. + * @param learningRate + * @param targetValue + */ + propagate(learningRate: number, targetValue: number[]): void; + + /** + * Networks can be stored as JSON's. + */ + toJSON(): string; + + /** + * Creates a static String to store the source code of the functions that are identical for all the workers (train, _trainSet, test). + * @returns Source code that can train a network inside a worker. + */ + static getWorkerSharedFunctions(): string; + + /** + * Rebuild a network that has been stored in a json using the method toJSON(). + */ + static fromJSON(exported: string): Network; + + /** + * The network can be converted into a WebWorker. This feature doesn't work in node.js, and it's not supported on every browser (it must support Blob). + * @returns Return a HTML5 WebWorker specialized on training the network stored in `memory`. Train based on the given dataSet and options. The worker returns the updated `memory` when done. + */ + worker(memory?: any, set?: any, options?: any): Worker; + + /** + * Export the topology into dot language which can be visualized as graphs using dot. + * @param edgeConnection + */ + toDot(edgeConnection?: any): { code: string; link: string }; + + /** + * The network can be exported to a single javascript Function. This can be useful when your network is already trained and you just need to use it, since the standalone functions is just one javascript function with an array and operations within, with no dependencies on Synaptic or any other library. + * @returns Returns a function that works as the activation of the network and can be used without depending on the library. + */ + standalone(): (inputs: number[]) => number[]; + + /** + * A network can be cloned to a completely new instance, with the same connections and traces. + * @returns Returns a copy of the network. + */ + clone(): Network; + + /** + * Return an array with all the neurons in the network, in activation order. + */ + neurons(): number[]; + + /** + * The method set(layers) receives an object with layers in the same format as the constructor of Network and sets them as the layers of the Network, this is useful when you are extending the Network class to create your own architectures. + */ + set(options: Network.Options): void; + + /** + * Returns number of inputs of the network. + */ + inputs(): number; + + /** + * Returns number of outputs of hte network. + */ + outputs(): number; + + setOptimize(optimize: any): void; + + /** + * Restores all the values from the optimized network the their respective objects in order to manipulate the network. + */ + restore(): any | void; + + /** + * Hardcodes the behaviour of the whole network into a single optimized function. + */ + optimize(): void; + + /** + * Clear all elegibility traces and extended elegibility traces (the network forgets its context, but not what was trained). + */ + clear(): void; + + /** + * Reset all weights and clear all traces (ends up like a new network). + */ + reset(): void; +} + +/** + * The Architect contains built-in architectures, ready to use. + */ +export namespace Architect { + /** + * This architecture allows you to create multilayer perceptrons, also known as feed-forward neural networks. They consist of a sequence of layers, each fully connected to the next one. + */ + class Perceptron extends Network { + trainer: Trainer; + + /** + * This architecture allows you to create multilayer perceptrons, also known as feed-forward neural networks. They consist of a sequence of layers, each fully connected to the next one. + * @param numberOfNeurons You have to provide a minimum of 3 layers (input, hidden and output), but you can use as many hidden layers as you wish. + */ + constructor(...numberOfNeurons: number[]); + } + + /** + * The long short-term memory is an architecture well-suited to learn from experience to classify, process and predict time series when there are very long time lags of unknown size between important events. + */ + class LSTM extends Network { + trainer: Trainer; + + /** + * The long short-term memory is an architecture well-suited to learn from experience to classify, process and predict time series when there are very long time lags of unknown size between important events. + * @param numberOfNeurons To use this architecture you have to set at least one input layer, one memory block assembly (consisting of four layers: input gate, memory cell, forget gate and output gate), and an output layer. Also you can set many layers of memory blocks. + */ + constructor(...numberOfNeurons: number[]); + } + + /** + * The Liquid architecture allows you to create Liquid State Machines. In these networks, neurons are randomly connected to each other. The recurrent nature of the connections turns the time varying input into a spatio-temporal pattern of activations in the network nodes. + */ + class Liquid extends Network { + trainer: Trainer; + + /** + * The Liquid architecture allows you to create Liquid State Machines. In these networks, neurons are randomly connected to each other. The recurrent nature of the connections turns the time varying input into a spatio-temporal pattern of activations in the network nodes. + * @param input The size of the input layer. + * @param pool The size of the pool. + * @param output The size of the output layer. + * @param connections The number of random connections in the pool. + * @param gates The number of random gates among the connections. + */ + constructor(input: number, pool: number, output: number, connections: number, gates: number); + } + + /** + * The Hopfield architecture serves as content-addressable memory. They are trained to remember patterns and then when feeding new patterns to the network it returns the most similar one from the patterns it was trained to remember. + */ + class Hopfield extends Network { + /** + * The Hopfield architecture serves as content-addressable memory. They are trained to remember patterns and then when feeding new patterns to the network it returns the most similar one from the patterns it was trained to remember. + * @param patternSize Pattern size in bits. + */ + constructor(patternSize: number); + + /** + * Teach the network two different patterns. + * @param patterns + */ + learn(patterns: [number[], number[]]): any; + + /** + * Feed new patterns to the network and it will return the most similar to the ones it was trained to remember. + * @param pattern + */ + feed(pattern: number[]): number[]; + } +} + +export namespace Trainer { + interface TrainingPair { + input: number[]; + output: number[]; + } + + type TrainingSet = TrainingPair[]; + + interface TrainingOptions { + /** + * Learning rate to train the network. It can be a static rate (just a number), dynamic (an array of numbers, which will transition from one to the next one according to the number of iterations) or a callback function: (iterations, error) => rate. + */ + rate?: number | number[] | ((iterations: number, error: number) => number); + + /** + * Maximum number of iterations. + */ + iterations?: number; + + /** + * Minimum error. + */ + error?: number; + + /** + * If true, the training set is shuffled after every iteration, this is useful for training data sequences which order is not meaningful to networks with context memory, like LSTM's. + */ + shuffle?: boolean; + + /** + * You can set what cost function to use for the training, there are three built-in cost functions (Trainer.cost.CROSS_ENTROPY, Trainer.cost.MSE and Trainer.cost.BINARY) to choose from cross-entropy or mean squared error. You can also use you own cost function(targetValues, outputValues). + */ + cost?: CostFunction; + + /** + * This commands the trainer to console.log the error and iterations every X number of iterations. + */ + log?: number; + + /** + * You can create custom scheduled tasks that will be executed every X number of iterations. It can be used to create custom logs, or to compute analytics based on the data passed to the task (data object includes error, iterations and the current learning rate). If the returned value of the task is true, the training will be aborted. This can be used to create special conditions to stop the training (i.e. if the error starts to increase). + */ + schedule?: TrainingScheduleOptions; + } + + interface TrainingScheduleDoData { + error: any; + + iterations: any; + + /** + * The current learning rate. + */ + rate: any; + } + + interface TrainingScheduleOptions { + every: number; + do: (data: TrainingScheduleDoData) => boolean | void; + } + + type CostFunction = (targetValues: number[], outputValues: number[]) => number; + + namespace cost { + const CROSS_ENTROPY: CostFunction; + const MSE: CostFunction; + const BINARY: CostFunction; + } + + interface TrainingResult { + error: number; + iterations: number; + time: number; + } + + interface XOROptions { + iterations?: number; + log?: number; + shuffle?: boolean; + cost?: CostFunction; + } + + interface DSROptions { + targets?: number[]; + distractors?: number[]; + prompts?: number[]; + length?: number; + success?: number; + iterations?: number; + rate?: number; + log?: number; + schedule?: TrainingScheduleOptions; + cost?: CostFunction; + } + + interface DSRTrainingResult { + error: number; + iterations: number; + time: number; + success: any; + } + + interface ERGOptions { + iterations?: number; + error?: number; + rate?: number; + log?: number; + cost?: CostFunction; + } + + interface ERGTrainingResult { + error: number; + iterations: number; + time: number; + test: any; + generate: any; + } +} + +/** + * The Trainer makes it easier to train any set to any network, no matter its architecture. The trainer also contains built-in tasks to test the performance of your network. + */ +export class Trainer { + /** + * The Trainer makes it easier to train any set to any network, no matter its architecture. The trainer also contains built-in tasks to test the performance of your network. + * @param network + */ + constructor(network: Network); + + /** + * This method allows you to train any training set to a Network. + * @returns When the training is done this method returns an object with the error, the iterations, and the elapsed time of the training. + */ + train(trainingSet: Trainer.TrainingSet, trainingOptions?: Trainer.TrainingOptions): Trainer.TrainingResult; + + /** + * This method allows you to train any training set to a Network. + * @returns When the training is done this method returns an object with the error, the iterations, and the elapsed time of the training. + */ + trainAsync(trainingSet: Trainer.TrainingSet, trainingOptions?: Trainer.TrainingOptions): Promise; + + /** + * This method accepts the same arguments as train(dataSet, options). It will iterate over the dataSet, activating the network. + * @returns It returns the elapsed time and the error (by default, the MSE, but you can specify the cost function in the options, same way as in train()). + */ + test(trainingSet: Trainer.TrainingSet, trainingOptions?: Trainer.TrainingOptions): Trainer.TrainingResult; + + /** + * This method trains an XOR to the network, is useful when you are experimenting with different architectures and you want to test and compare their performances. + */ + XOR(options?: Trainer.XOROptions): Trainer.TrainingResult; + + /** + * This method trains the network to complete a Discrete Sequence Recall, which is a task for testing context memory in neural networks. + */ + DSR(options?: Trainer.DSROptions): Trainer.DSRTrainingResult; + + /** + * This method trains the network to pass an Embedded Reber Grammar test. + */ + ERG(options?: Trainer.ERGOptions): Trainer.ERGTrainingResult; + + /** + * This test challenges the network to complete a timing task. + */ + timingTask(options?: any): { train: any; test: any }; +} diff --git a/synaptic/synaptic-tests.ts b/synaptic/synaptic-tests.ts new file mode 100644 index 00000000000000..8c06985d63897e --- /dev/null +++ b/synaptic/synaptic-tests.ts @@ -0,0 +1,520 @@ +// Neurons +// ======= +namespace NeuronTests { + // project + // ------- + var A = new Neuron(); + var B = new Neuron(); + A.project(B); // A now projects a connection to B + A.project(A); // Neurons can also self-connect + + // gate + // ---- + var A = new Neuron(); + var B = new Neuron(); + var connection = A.project(B); + + var C = new Neuron(); + C.gate(connection); // now C gates the connection between A and B + + // activate + // -------- + var A = new Neuron(); + var B = new Neuron(); + A.project(B); + + A.activate(0.5); // 0.5 + B.activate(); // 0.3244554645 + + // propagate + // --------- + var A = new Neuron(); + var B = new Neuron(); + A.project(B); + + var learningRate = .3; + + for (var i = 0; i < 20000; i++) { + // when A activates 1 + A.activate(1); + + // train B to activate 0 + B.activate(); + B.propagate(learningRate, 0); + } + + // test it + A.activate(1); + B.activate(); // 0.006540565760853365 + + // squashing function and bias + var A = new Neuron(); + A.squash = Neuron.squash.TANH; + A.bias = 1; +} + +// Layers +// ====== +namespace LayerTests { + // project + // ------- + var A = new Layer(5); + var B = new Layer(3); + A.project(B, Layer.connectionType.ALL_TO_ALL); // All the neurons in layer A now project a connection to all the neurons in layer B + A.project(A, Layer.connectionType.ONE_TO_ONE); + + // gate + // ---- + var A = new Layer(5); + var B = new Layer(3); + var connection = A.project(B); + + var C = new Layer(4); + C.gate(connection, Layer.gateType.INPUT); // now C gates the connection between A and B (input gate) + + // activate + // -------- + var A = new Layer(5); + var B = new Layer(3); + A.project(B); + + A.activate([1, 0, 1, 0, 1]); // [1,0,1,0,1] + B.activate(); // [0.3280457, 0.83243247, 0.5320423] + + // propagate + // --------- + var A = new Layer(5); + var B = new Layer(2); + A.project(B); + + var learningRate = .3; + + for (var i = 0; i < 20000; i++) { + // when A activates [1, 0, 1, 0, 1] + A.activate([1, 0, 1, 0, 1]); + + // train B to activate [0,0] + B.activate(); + B.propagate(learningRate, [0, 0]); + } + + // test it + A.activate([1, 0, 1, 0, 1]); + B.activate(); // [0.004606949693864496, 0.004606763721459169] + + // squashing function and bias + A.set({ + squash: Neuron.squash.TANH, + bias: 0 + }) + + // neurons + // ------- + A.neurons(); +} + +// Networks +// ======== + +namespace NetworkTests { + var inputLayer = new Layer(4); + var hiddenLayer = new Layer(6); + var outputLayer = new Layer(2); + + inputLayer.project(hiddenLayer); + hiddenLayer.project(outputLayer); + + var A = new Network({ + input: inputLayer, + hidden: [hiddenLayer], + output: outputLayer + }); + + var B = new Network({ + input: inputLayer, + hidden: [hiddenLayer], + output: outputLayer + }); + + // project + // ------- + A.project(B, Layer.connectionType.ALL_TO_ALL); + + // gate + // ---- + + var C = new Network({ + input: inputLayer, + hidden: [hiddenLayer], + output: outputLayer + }); + var connection = A.project(B); + C.gate(connection, Layer.gateType.INPUT); // now C's output layer gates the connection between A's output layer and B's input layer (input gate) + + // activate + // -------- + var inputLayer = new Layer(4); + var hiddenLayer = new Layer(6); + var outputLayer = new Layer(2); + + inputLayer.project(hiddenLayer); + hiddenLayer.project(outputLayer); + + var myNetwork = new Network({ + input: inputLayer, + hidden: [hiddenLayer], + output: outputLayer + }); + + myNetwork.activate([1, 0, 1, 0]); // [0.5200553602396137, 0.4792707231811006] + + // propagate + // --------- + // create the network + var inputLayer = new Layer(2); + var hiddenLayer = new Layer(3); + var outputLayer = new Layer(1); + + inputLayer.project(hiddenLayer); + hiddenLayer.project(outputLayer); + + var myNetwork = new Network({ + input: inputLayer, + hidden: [hiddenLayer], + output: outputLayer + }); + + // train the network + var learningRate = .3; + for (var i = 0; i < 20000; i++) { + // 0,0 => 0 + myNetwork.activate([0, 0]); + myNetwork.propagate(learningRate, [0]); + + // 0,1 => 1 + myNetwork.activate([0, 1]); + myNetwork.propagate(learningRate, [1]); + + // 1,0 => 1 + myNetwork.activate([1, 0]); + myNetwork.propagate(learningRate, [1]); + + // 1,1 => 0 + myNetwork.activate([1, 1]); + myNetwork.propagate(learningRate, [0]); + } + + // test the network + myNetwork.activate([0, 0]); // [0.015020775950893527] + myNetwork.activate([0, 1]); // [0.9815816381088985] + myNetwork.activate([1, 0]); // [0.9871822457132193] + myNetwork.activate([1, 1]); // [0.012950087641929467] + + // optimize + // -------- + + // extend + // ------ + + // toJSON/fromJSON + // --------------- + var exported = myNetwork.toJSON(); + var imported = Network.fromJSON(exported); + + // worker + // ------ + // training set + var learningRate = .3; + var trainingSet = [ + { + input: [0, 0], + output: [0] + }, + { + input: [0, 1], + output: [1] + }, + { + input: [1, 0], + output: [1] + }, + { + input: [1, 1], + output: [0] + }, + ]; + + // create a network + var inputLayer = new Layer(2); + var hiddenLayer = new Layer(3); + var outputLayer = new Layer(1); + + inputLayer.project(hiddenLayer); + hiddenLayer.project(outputLayer); + + var myNetwork = new Network({ + input: inputLayer, + hidden: [hiddenLayer], + output: outputLayer + }); + + // create a worker + var myWorker = myNetwork.worker(); + + // activate the network + function activateWorker(input: number[]) { + myWorker.postMessage({ + action: "activate", + input: input, + memoryBuffer: myNetwork.optimized.memory + }, [myNetwork.optimized.memory.buffer]); + } + + // backpropagate the network + function propagateWorker(target: number[]) { + myWorker.postMessage({ + action: "propagate", + target: target, + rate: learningRate, + memoryBuffer: myNetwork.optimized.memory + }, [myNetwork.optimized.memory.buffer]); + } + + // train the worker + myWorker.onmessage = function (e) { + // give control of the memory back to the network - this is mandatory! + myNetwork.optimized.ownership(e.data.memoryBuffer); + + if (e.data.action == "propagate") { + if (index >= 4) { + index = 0; + iterations++; + if (iterations % 100 == 0) { + var output00 = myNetwork.activate([0, 0]); + var output01 = myNetwork.activate([0, 1]); + var output10 = myNetwork.activate([1, 0]); + var output11 = myNetwork.activate([1, 1]); + + console.log("0,0 => ", output00); + console.log("0,1 => ", output01); + console.log("1,0 => ", output10); + console.log("1,1 => ", output11, "\n"); + } + } + + activateWorker(trainingSet[index].input); + } + + if (e.data.action == "activate") { + propagateWorker(trainingSet[index].output); + index++; + } + } + + // kick it + var index = 0; + var iterations = 0; + activateWorker(trainingSet[index].input); + + // standalone + // ---------- + var inputLayer = new Layer(4); + var hiddenLayer = new Layer(6); + var outputLayer = new Layer(2); + + inputLayer.project(hiddenLayer); + hiddenLayer.project(outputLayer); + + var myNetwork = new Network({ + input: inputLayer, + hidden: [hiddenLayer], + output: outputLayer + }); + + var standalone = myNetwork.standalone(); + + myNetwork.activate([1, 0, 1, 0]); // [0.5466397925108878, 0.5121246668637663] + standalone([1, 0, 1, 0]); // [0.5466397925108878, 0.5121246668637663] + + // clone + // ----- + var inputLayer = new Layer(4); + var hiddenLayer = new Layer(6); + var outputLayer = new Layer(2); + + inputLayer.project(hiddenLayer); + hiddenLayer.project(outputLayer); + + var myNetwork = new Network({ + input: inputLayer, + hidden: [hiddenLayer], + output: outputLayer + }); + + var clone = myNetwork.clone(); + + myNetwork.activate([1, 0, 1, 0]); // [0.5466397925108878, 0.5121246668637663] + clone.activate([1, 0, 1, 0]); // [0.5466397925108878, 0.5121246668637663] + + // neurons + // ------- + myNetwork.neurons(); + + // set + // --- + var inputLayer = new Layer(4); + var hiddenLayer = new Layer(6); + var outputLayer = new Layer(2); + + inputLayer.project(hiddenLayer); + hiddenLayer.project(outputLayer); + + var myNetwork = new Network(); + + myNetwork.set({ + input: inputLayer, + hidden: [hiddenLayer], + output: outputLayer + }); +} + +// Architect +// ========= +namespace ArchitectTests { + // Perceptron + // ---------- + var myPerceptron = new Architect.Perceptron(2, 3, 1); + + // LSTM + // ---- + var myLSTM = new Architect.LSTM(2, 6, 1); + + // Liquid + // ------ + var input = 2; + var pool = 20; + var output = 1; + var connections = 30; + var gates = 10; + + var myLiquidStateMachine = new Architect.Liquid(input, pool, output, connections, gates); + + // Hopfield + // -------- + var hopfield = new Architect.Hopfield(10) // create a network for 10-bit patterns + + // teach the network two different patterns + hopfield.learn([ + [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0] + ]) + + // feed new patterns to the network and it will return the most similar to the ones it was trained to remember + hopfield.feed([0, 1, 0, 1, 0, 1, 0, 1, 1, 1]) // [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + hopfield.feed([1, 1, 1, 1, 1, 0, 0, 1, 0, 0]) // [1, 1, 1, 1, 1, 0, 0, 0, 0, 0] +} + +// Trainer +// ======= +namespace TrainerTests { + // train + // ----- + var myNetwork = new Architect.Perceptron(2, 2, 1) + var trainer = new Trainer(myNetwork) + + var trainingSet = [ + { + input: [0, 0], + output: [0] + }, + { + input: [0, 1], + output: [1] + }, + { + input: [1, 0], + output: [1] + }, + { + input: [1, 1], + output: [0] + }, + ] + + trainer.train(trainingSet); + + var traningOptions = { + rate: .1, + iterations: 20000, + error: .005, + shuffle: true, + log: 1000, + cost: Trainer.cost.CROSS_ENTROPY, + schedule: { + every: 500, // repeat this task every 500 iterations + do: function (data: Synaptic.Trainer.TrainingScheduleDoData) { + // custom log + console.log("error", data.error, "iterations", data.iterations, "rate", data.rate); + if (data.error > .5) + return true; // abort/stop training + } + } + }; + + trainer.train(trainingSet, traningOptions); + + // trainAsync + // ---------- + var trainer = new Trainer(myNetwork); + trainer.trainAsync(trainingSet, traningOptions) + .then((results: any) => console.log('done!', results)) + + var myNetwork = new Architect.Perceptron(2, 2, 1) + var trainer = new Trainer(myNetwork) + + var trainingSet = [ + { + input: [0, 0], + output: [0] + }, + { + input: [0, 1], + output: [1] + }, + { + input: [1, 0], + output: [1] + }, + { + input: [1, 1], + output: [0] + }, + ] + + trainer.trainAsync(trainingSet) + .then((results: any) => console.log('done!', results)) + + // test + // ---- + + // XOR + // --- + var trainer = new Trainer(myNetwork); + trainer.XOR(); // {error: 0.004999821588193305, iterations: 21333, time: 111} + + // DSR + // --- + trainer.DSR({ + targets: [2, 4], + distractors: [3, 5], + prompts: [0, 1], + length: 10 + }); + + // ERG + // --- + trainer.ERG(); + + // timingTask + // ---------- +} diff --git a/synaptic/tsconfig.json b/synaptic/tsconfig.json new file mode 100644 index 00000000000000..ce04e16223dede --- /dev/null +++ b/synaptic/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "synaptic-tests.ts" + ] +} \ No newline at end of file diff --git a/toastr/index.d.ts b/toastr/index.d.ts index 8fe27edd73a651..40eb219869eab9 100644 --- a/toastr/index.d.ts +++ b/toastr/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Toastr 2.1.1 +// Type definitions for Toastr 2.1.3 // Project: https://github.com/CodeSeven/toastr // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -133,6 +133,10 @@ interface ToastrOptions { * Set if toastr should parse containing html **/ allowHtml?: boolean; + /** + * Set if toastr should escape html + **/ + escapeHtml?: boolean; } interface ToastrDisplayMethod { diff --git a/validator/index.d.ts b/validator/index.d.ts index 9fbed4b2992fd8..0eae66c3c9ccb2 100644 --- a/validator/index.d.ts +++ b/validator/index.d.ts @@ -72,6 +72,9 @@ declare namespace ValidatorJS { // check if the string is an email. isEmail(str: string, options?: IsEmailOptions): boolean; + // check if the string has a length of zero. + isEmpty(str: string): boolean; + // check if the string is a fully qualified domain name (e.g. domain.com). isFQDN(str: string, options?: IsFQDNOptions): boolean; @@ -407,6 +410,11 @@ declare module "validator/lib/isEmail" { export = isEmail; } +declare module "validator/lib/isEmpty" { + const isEmpty: typeof validator.isEmpty; + export = isEmpty; +} + declare module "validator/lib/isFQDN" { const isFQDN: typeof validator.isFQDN; export = isFQDN; diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index ec9fff32a6bd8a..c4cee64661eeff 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -27,6 +27,7 @@ import isDateFunc = require('validator/lib/isDate'); import isDecimalFunc = require('validator/lib/isDecimal'); import isDivisibleByFunc = require('validator/lib/isDivisibleBy'); import isEmailFunc = require('validator/lib/isEmail'); +import isEmptyFunc = require('validator/lib/isEmpty'); import isFQDNFunc = require('validator/lib/isFQDN'); import isFloatFunc = require('validator/lib/isFloat'); import isFullWidthFunc = require('validator/lib/isFullWidth'); @@ -126,6 +127,9 @@ namespace import_tests { let _isEmail = validator.isEmail; _isEmail = isEmailFunc; + let _isEmpty = validator.isEmpty; + _isEmpty = isEmptyFunc; + let _isFQDN = validator.isFQDN; _isFQDN = isFQDNFunc; diff --git a/validatorjs/index.d.ts b/validatorjs/index.d.ts new file mode 100644 index 00000000000000..cf962f15684ccc --- /dev/null +++ b/validatorjs/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for validatorjs v3.7.0 +// Project: https://github.com/skaterdav85/validatorjs +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Validator { + + interface ParsedRule { + attribute: Array<{ name: string, value: any }> + } + + interface ValidationErrors { + [field: string]: string + } + + interface ErrorMessages { + [key: string]: string + } + + interface AttributeNames { + [attribute: string]: string + } + + type AttributeFormatter = (attribute: any) => any + + interface Errors { + errors : ValidationErrors + add (attribute: string, message: string): void + get (attribute: string): Array + first (attribute: string): string | boolean + all (): ValidationErrors + has (attribute: string): boolean + } + + interface ValidatorStatic { + new (data: A, rules: any, customMessages?: ErrorMessages): Validator + setMessages (lang: string, messages: ErrorMessages): any + getMessages (lang: string): ErrorMessages + useLang (lang: string): void + getDefaultLang (): string + setAttributeFormatter (func: AttributeFormatter): void + stopOnError (attributes: boolean | Array): void + register (name: string, fn: Function, message: string): void + registerAsync (name: string, fn: Function, message: string): void + } + + interface Validator { + lang: string + input: A + messages: ErrorMessages + errors: Errors + errorCount: number + hasAsync: boolean + rules: any + numericRules: Array + attributeFormatter: AttributeFormatter + check (): boolean + checkAsync (passes?: Function, fails?: Function): void + setAttributeNames (attributes: AttributeNames): void + setAttributeFormatter (func: AttributeFormatter): void + getRule (name: string): Function + stopOnError (passes?: Function): boolean | void + passes (passes?: Function): boolean | void + fails (fails?: Function): boolean | void + } + +} + +declare const Validator: Validator.ValidatorStatic +export = Validator; +export as namespace Validator; diff --git a/validatorjs/tsconfig.json b/validatorjs/tsconfig.json new file mode 100644 index 00000000000000..176809589c4de4 --- /dev/null +++ b/validatorjs/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "validatorjs-tests.ts" + ] +} \ No newline at end of file diff --git a/validatorjs/validatorjs-tests.ts b/validatorjs/validatorjs-tests.ts new file mode 100644 index 00000000000000..b25551bc2fa005 --- /dev/null +++ b/validatorjs/validatorjs-tests.ts @@ -0,0 +1,34 @@ +import * as Validator from "validatorjs" + +var rules: any = { + foo: "required" +} + +var data: any = { + foo: "bar" +} + +var validator: Validator.Validator = new Validator(data, rules) + +var passes: boolean = validator.passes() as boolean +validator.passes(() => {}) + +var fails: boolean = validator.fails() as boolean +validator.fails(() => {}) + +var check: boolean = validator.check() + +var errors: Validator.Errors = validator.errors +var all: Validator.ValidationErrors = errors.all() +var error: Array = errors.get("foo") +var first: string | boolean = errors.first("foo") +var has: boolean = errors.has("foo") + +Validator.setMessages("en", {}) +var messages: Validator.ErrorMessages = Validator.getMessages("en") +Validator.useLang("en") +var lang: string = Validator.getDefaultLang() +Validator.setAttributeFormatter((attributes: any) => ({})) +Validator.stopOnError(true) +Validator.register("custom", () => {}, "error.custom") +Validator.registerAsync("custom", () => {}, "error.custom") diff --git a/webix/index.d.ts b/webix/index.d.ts index 7931ef83d9e5c4..1936102a6d505a 100644 --- a/webix/index.d.ts +++ b/webix/index.d.ts @@ -5941,7 +5941,10 @@ interface richselect extends webix.ui.baseview{ getChildViews():any[]; getFormView():webix.ui.baseview; getInputNode():HTMLElement; - getList():webix.ui.baseview; + /** + * returns list view of the control + */ + getList():webix.ui.list; getNode():any; getParentView():any; getPopup():webix.ui.baseview; diff --git a/webpack-dev-server/webpack-dev-server-tests.ts b/webpack-dev-server/webpack-dev-server-tests.ts index 21af59885afb28..8761eb9a59a674 100644 --- a/webpack-dev-server/webpack-dev-server-tests.ts +++ b/webpack-dev-server/webpack-dev-server-tests.ts @@ -1,3 +1,5 @@ +/// + import * as webpack from 'webpack'; import * as WebpackDevServer from 'webpack-dev-server'; var compiler = webpack({}); @@ -18,7 +20,7 @@ server = new WebpackDevServer(compiler, { // Enable special support for Hot Module Replacement // Page is no longer updated, but a "webpackHotUpdate" message is send to the content // Use "webpack/hot/dev-server" as additional module in your entry point - // Note: this does _not_ add the `HotModuleReplacementPlugin` like the CLI option does. + // Note: this does _not_ add the `HotModuleReplacementPlugin` like the CLI option does. // Set this as true if you want to access dev server from arbitrary url. // This is handy if you are using a html5 router. diff --git a/webpack-dev-server/webpack-dev-server.d.ts b/webpack-dev-server/webpack-dev-server.d.ts index 4669dbc67a3a00..d47bd115217662 100644 --- a/webpack-dev-server/webpack-dev-server.d.ts +++ b/webpack-dev-server/webpack-dev-server.d.ts @@ -25,7 +25,7 @@ declare module "webpack-dev-server" { watchOptions?: webpack.WatchOptions; publicPath: string; headers?: any; - stats?: webpack.compiler.StatsToJsonOptions | webpack.compiler.StatsToStringOptions; + stats?: webpack.compiler.StatsOptions| webpack.compiler.StatsToStringOptions; setup?(app: core.Express): void; } @@ -49,4 +49,4 @@ declare module "webpack-dev-server" { var wds: WebpackDevServer.WebpackDevServer; export = wds; -} \ No newline at end of file +} diff --git a/webpack/index.d.ts b/webpack/index.d.ts index 142a7a1a78d094..770fd3022541ee 100644 --- a/webpack/index.d.ts +++ b/webpack/index.d.ts @@ -62,6 +62,8 @@ declare namespace webpack { recordsOutputPath?: string; /** Add additional plugins to the compiler. */ plugins?: (Plugin | Function)[]; + /** Stats options for logging */ + stats?: Configuration; } interface Entry { @@ -481,12 +483,12 @@ declare namespace webpack { /** Returns true if there were warnings while compiling. */ hasWarnings(): boolean; /** Return information as json object */ - toJson(options?: StatsToJsonOptions): any; //TODO: type this + toJson(options?: StatsOptions): any; //TODO: type this /** Returns a formatted string of the result. */ toString(options?: StatsToStringOptions): string; } - interface StatsToJsonOptions { + interface StatsOptions { /** context directory for request shortening */ context?: boolean; /** add the hash of the compilation */ @@ -523,7 +525,7 @@ declare namespace webpack { assetsSort?: string; } - interface StatsToStringOptions extends StatsToJsonOptions { + interface StatsToStringOptions extends StatsOptions { /** With console colors */ colors?: boolean; } diff --git a/xmldoc/index.d.ts b/xmldoc/index.d.ts new file mode 100644 index 00000000000000..8590c68e16427a --- /dev/null +++ b/xmldoc/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for xmldoc 0.5.1 +// Project: https://www.npmjs.com/package/xmldoc +// Definitions by: Xavier Stouder +// Definitions: https://github.com/DefinitelyTyped/ + +export class XmlDocument { + constructor(xmlString: string); + + eachChild(func: (child: XmlElement, index?: number, array?: XmlElement[]) => void): void; + childNamed(name: string): XmlElement; + childrenNamed(name: string): XmlElement[]; + childWithAttribute(name: string, value?: string): XmlElement; + descendantWithPath(path: string): XmlElement; + valueWithPath(path: string): string; + toString(opts?: XmlOptions): string; +} +export class XmlElement { + eachChild(func: (child: XmlElement, index?: number, array?: XmlElement[]) => void): void; + childNamed(name: string): XmlElement; + childrenNamed(name: string): XmlElement[]; + childWithAttribute(name: string, value?: string): XmlElement; + descendantWithPath(path: string): XmlElement; + valueWithPath(path: string): string; + toString(opts?: XmlOptions): string; +} + +export interface XmlOptions { + compressed?: boolean; + trimmed?: boolean; + preserveWhitespace?: boolean; +} diff --git a/xmldoc/tsconfig.json b/xmldoc/tsconfig.json new file mode 100644 index 00000000000000..8cb7a0610795d0 --- /dev/null +++ b/xmldoc/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "xmldoc-tests.ts" + ] +} \ No newline at end of file diff --git a/xmldoc/xmldoc-tests.ts b/xmldoc/xmldoc-tests.ts new file mode 100644 index 00000000000000..09a3f35d9e1dee --- /dev/null +++ b/xmldoc/xmldoc-tests.ts @@ -0,0 +1,4 @@ +import * as xmldoc from "xmldoc"; + +const doc = new xmldoc.XmlDocument("magic"); +console.log(doc.toString()); \ No newline at end of file