diff --git a/.gitignore b/.gitignore index 4f0152028d..858238c5bf 100644 --- a/.gitignore +++ b/.gitignore @@ -30,10 +30,12 @@ _infrastructure/tests/build *.iml *.js.map !*.js/ +!scripts/new-package.js +!scripts/lint.js node_modules .sublimets .settings/launch.json - .vscode +yarn.lock \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 48704282ad..4db6a14a5b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - 4 + - 6.9.1 sudo: false diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 44f0d8e9a0..8b263f19ae 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 730bd78af2..a864dbcb13 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,8 +1,17 @@ -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. +- [ ] 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). +- [ ] Run `npm run lint -- package-name` if a `tslint.json` is present. + +If adding a new definition: +- [ ] The package does not provide its own types, and you can not add them. +- [ ] 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. Base these on the README, *not* on an existing project. + +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 7da7d1530b..d3e6c0e27c 100644 --- a/README.md +++ b/README.md @@ -109,54 +109,25 @@ Your package should have this structure: | foo-tests.ts | This contains sample code which tests the typings. This code does *not* run, but it is type-checked. | | tsconfig.json | This allows you to run `tsc` within the package. | -`index.d.ts` should start with a header looking like: +Generate these by running `npm run new-package -- new-package-name`. -```ts -// Type definitions for foo 1.2 -// Project: https://github.com/baz/foo -// Definitions by: My Self -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -``` - -The `Project` link does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website. - -`tsconfig.json` should look like this: - -```json -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "foo-tests.ts" - ] -} -``` - -These should be identical accross projects except that `foo-tests` will be replaced with the name of your test file, -and you may also add the `"jsx"` compiler option if your library needs it. +You may edit the `tsconfig.json` to add new files or to add the `"jsx"` compiler option. 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. @@ -183,6 +154,27 @@ Make a PR doing the following: To do this, add a `package.json` with `"dependencies": { "foo": "x.y.z" }`. +#### Lint + +To lint a package, just add a `tslint.json` to that package containing `{ "extends": "../tslint.json" }`. All new packages must be linted. +If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example: + +```json +{ + "extends": "../tslint.json", + "rules": { + // This package uses the Function type, and it will take effort to fix. + "forbidden-types": false + } +} +``` + +(To indicate that a lint rule truly does not apply, use `// tslint:disable:rule-name` or better, `//tslint:disable-next-line:rule-name`.) + +Only `.d.ts` files are linted. +Test the linter by running `npm run lint -- package-name`. Do not use a globally installed tslint. + + ## FAQ #### What exactly is the relationship between this repository and the `@types` packages on NPM? @@ -194,7 +186,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 +201,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 691b6b6ad0..bf487fd341 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/analytics-node/analytics-node-tests.ts b/analytics-node/analytics-node-tests.ts index 594c15fae6..5207fe560b 100644 --- a/analytics-node/analytics-node-tests.ts +++ b/analytics-node/analytics-node-tests.ts @@ -1,8 +1,8 @@ -import AnalyticsNode = require("analytics-node"); -var analytics: AnalyticsNode.Analytics; +import Analytics = require("analytics-node"); +var analytics: Analytics; function testConfig(): void { - analytics = new AnalyticsNode.Analytics('YOUR_WRITE_KEY', { + analytics = new Analytics('YOUR_WRITE_KEY', { flushAt: 20, flushAfter: 10000 }); diff --git a/analytics-node/index.d.ts b/analytics-node/index.d.ts index 455b13c92b..fa0b8d6426 100644 --- a/analytics-node/index.d.ts +++ b/analytics-node/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andrew Fong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = AnalyticsNode; +export = AnalyticsNode.Analytics; declare namespace AnalyticsNode { diff --git a/angular-material/index.d.ts b/angular-material/index.d.ts index 610dcf34d7..7895732ada 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-mocks/index.d.ts b/angular-mocks/index.d.ts index e3ef7bad18..3c24ed1cf6 100644 --- a/angular-mocks/index.d.ts +++ b/angular-mocks/index.d.ts @@ -107,7 +107,7 @@ declare module 'angular' { interface IComponentControllerService { // TBinding is an interface exposed by a component as per John Papa's style guide // https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#accessible-members-up-top - (componentName: string, locals: { $scope: IScope, [key: string]: any }, bindings?: TBinding, ident?: string): T; + (componentName: string, locals: { $scope?: IScope, [key: string]: any }, bindings?: TBinding, ident?: string): T; } diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index 8e0711d6f7..29a344426f 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 62deb4742f..d07777d2cf 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/archiver/index.d.ts b/archiver/index.d.ts index d67705e2ea..f11d0070ef 100644 --- a/archiver/index.d.ts +++ b/archiver/index.d.ts @@ -18,29 +18,32 @@ import * as FS from 'fs'; import * as STREAM from 'stream'; -interface nameInterface { - name?: string; -} -interface Archiver extends STREAM.Transform { - pipe(writeStream: FS.WriteStream): void; +declare function archiver(format: string, options?: archiver.Options): archiver.Archiver; + +declare namespace archiver { + + export function create(format: string, options?: Options): Archiver; + + + export interface nameInterface { + name?: string; + } + + export interface Archiver extends STREAM.Transform { + pipe(writeStream: FS.WriteStream): void; append(source: FS.ReadStream | Buffer | string, name: nameInterface): void; directory(dirpath: string, destpath: nameInterface | string): void; directory(dirpath: string, destpath: nameInterface | string, data: any | Function): void; bulk(mappings: any): void; - finalize(): void; -} + finalize(): void; + } -interface Options { + export interface Options { -} - -declare function archiver(format: string, options?: Options): Archiver; - -declare namespace archiver { - function create(format: string, options?: Options): Archiver; + } } export = archiver; diff --git a/async/async-tests.ts b/async/async-tests.ts index b724582368..c4a3506415 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 96da35c1ea..8b564fbd80 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 c655cc101a..5c890605cd 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 031047490f..fbee8f926c 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/aws4/aws4-tests.ts b/aws4/aws4-tests.ts new file mode 100644 index 0000000000..b611951e45 --- /dev/null +++ b/aws4/aws4-tests.ts @@ -0,0 +1,24 @@ +/// + +import * as aws4 from "."; + +let requestSigner = new aws4.RequestSigner({}, {}); +requestSigner.matchHost(""); +requestSigner.isSingleRegion(); +requestSigner.createHost(); +requestSigner.prepareRequest(); +requestSigner.sign(); +requestSigner.getDateTime(); +requestSigner.getDate(); +requestSigner.authHeader(); +requestSigner.signature(); +requestSigner.stringToSign(); +requestSigner.canonicalString(); +requestSigner.canonicalHeaders(); +requestSigner.signedHeaders(); +requestSigner.credentialString(); +requestSigner.defaultCredentials(); +requestSigner.parsePath(); +requestSigner.formatPath(); + +aws4.sign({}, {}); diff --git a/aws4/index.d.ts b/aws4/index.d.ts new file mode 100644 index 0000000000..88f54f2a3f --- /dev/null +++ b/aws4/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for aws4 1.5.0 +// Project: https://github.com/mhart/aws4 +// Definitions by: Andrew Crites +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class RequestSigner { + constructor(request?: any, credentials?: any); + request: any; + credentials: any; + service: any; + region: any; + isCodeCommitGit: any; + + matchHost(host?: string): string; + isSingleRegion(): boolean; + createHost(): string; + prepareRequest(): void; + sign(): any; + getDateTime(): string; + getDate(): string; + authHeader(): string; + signature(): string; + stringToSign(): string; + canonicalString(): string; + canonicalHeaders(): string; + signedHeaders(): string; + credentialString(): string; + defaultCredentials(): any; + parsePath(): any; + formatPath(): string; +} + +export function sign(options?: any, credentials?: any): RequestSigner; diff --git a/aws4/tsconfig.json b/aws4/tsconfig.json new file mode 100644 index 0000000000..fb9528a526 --- /dev/null +++ b/aws4/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", + "aws4-tests.ts" + ] +} diff --git a/base64-js/tslint.json b/base64-js/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/base64-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/bootstrap-select/bootstrap-select-tests.ts b/bootstrap-select/bootstrap-select-tests.ts new file mode 100644 index 0000000000..e2e8c88560 --- /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 0000000000..5f511685ba --- /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 0000000000..366216ab7f --- /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 6390b57864..7ce79b431f 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/classnames/index.d.ts b/classnames/index.d.ts index 7536aac170..22d9803399 100644 --- a/classnames/index.d.ts +++ b/classnames/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Dave Keen , Adi Dahiya , Jason Killian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null; +declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | false; interface ClassDictionary { [id: string]: boolean | undefined | null; diff --git a/color/color-tests.ts b/color/color-tests.ts new file mode 100644 index 0000000000..1b2d9369e0 --- /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 0000000000..0395cd1bf9 --- /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 0000000000..860f35d441 --- /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 0000000000..6e4317ac9d --- /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 0000000000..ccf2396833 --- /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 0000000000..cfff519c0b --- /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 0000000000..fec3c119d2 --- /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 0000000000..381b61562e --- /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 0000000000..43c76ef639 --- /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 0000000000..de2c6fade4 --- /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 0000000000..59886b5e60 --- /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 0000000000..7b38d340d4 --- /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/d3-geo/d3-geo-tests.ts b/d3-geo/d3-geo-tests.ts index b0c2adbb79..3d28bb610f 100644 --- a/d3-geo/d3-geo-tests.ts +++ b/d3-geo/d3-geo-tests.ts @@ -636,6 +636,15 @@ identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeature2 identityTransform = identityTransform.fitSize([960, 500], sampleFeatureCollection); identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeatureCollection); +let reflecting: boolean; + +identityTransform = identityTransform.reflectX(true); +// identityTransform = identityTransform.reflectX(5); // fails, wrong argument data type +reflecting = identityTransform.reflectX(); + +identityTransform = identityTransform.reflectY(true); +// identityTransform = identityTransform.reflectY(5); // fails, wrong argument data type +reflecting = identityTransform.reflectY(); // ---------------------------------------------------------------------- // Stream interface diff --git a/d3-geo/index.d.ts b/d3-geo/index.d.ts index f3222ce20e..9ab3ae74cd 100644 --- a/d3-geo/index.d.ts +++ b/d3-geo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-geo module v1.3.1 +// Type definitions for D3JS d3-geo module v1.4.0 // Project: https://github.com/d3/d3-geo/ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -1412,6 +1412,31 @@ export interface GeoIdentityTranform extends GeoStreamWrapper { */ fitSize(size: [number, number], object: ExtendedGeometryCollection): this; + /** + * Returns true if x-reflection is enabled, which defaults to false. + */ + reflectX(): boolean; + /** + * Sets whether or not the x-dimension is reflected (negated) in the output. + * + * @param reflect true = reflect x-dimension, false = do not reflect x-dimension. + */ + reflectX(reflect: boolean): this; + + /** + * Returns true if y-reflection is enabled, which defaults to false. + */ + reflectY(): boolean; + /** + * Sets whether or not the y-dimension is reflected (negated) in the output. + * + * This is especially useful for transforming from standard spatial reference systems, + * which treat positive y as pointing up, to display coordinate systems such as Canvas and SVG, + * which treat positive y as pointing down. + * + * @param reflect true = reflect y-dimension, false = do not reflect y-dimension. + */ + reflectY(reflect: boolean): this; /** * Returns the current scale factor. diff --git a/electron/electron-prebuilt.d.ts b/electron/electron-prebuilt.d.ts deleted file mode 100644 index 585c9e4668..0000000000 --- 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/electron/github-electron-main-tests.ts b/electron/github-electron-main-tests.ts index df5e6723eb..f333e86ec7 100644 --- a/electron/github-electron-main-tests.ts +++ b/electron/github-electron-main-tests.ts @@ -9,6 +9,7 @@ import { ipcMain, Menu, MenuItem, + net, powerMonitor, powerSaveBlocker, protocol, @@ -732,6 +733,51 @@ Menu.buildFromTemplate([ { label: '3', position: 'endof=numbers' } ]); +// net +// https://github.com/electron/electron/blob/master/docs/api/net.md + +app.on('ready', () => { + const request = net.request('https://github.com') + request.setHeader('Some-Custom-Header-Name', 'Some-Custom-Header-Value'); + let header = request.getHeader('Some-Custom-Header-Name'); + request.removeHeader('Some-Custom-Header-Name'); + request.on('response', (response) => { + console.log(`Status code: ${response.statusCode}`); + console.log(`Status message: ${response.statusMessage}`); + console.log(`Headers: ${JSON.stringify(response.headers)}`); + console.log(`Http version: ${response.httpVersion}`); + console.log(`Major Http version: ${response.httpVersionMajor}`); + console.log(`Minor Http version: ${response.httpVersionMinor}`); + response.on('data', (chunk) => { + console.log(`BODY: ${chunk}`); + }) + response.on('end', () => { + console.log('No more data in response.'); + }) + response.on('error', () => { + console.log('"error" event emitted'); + }); + response.on('aborted', () => { + console.log('"aborted" event emitted'); + }); + }) + request.on('login', (authInfo, callback) => { + callback('username', 'password'); + }); + request.on('finish', () => { + console.log('"finish" event emitted'); + }); + request.on('abort', () => { + console.log('"abort" event emitted'); + }); + request.on('error', () => { + console.log('"error" event emitted'); + }); + request.write('Hello World!', 'utf-8', () => { }); + request.end('Hello World!', 'utf-8', () => { }); + request.abort(); +}) + // power-monitor // https://github.com/atom/electron/blob/master/docs/api/power-monitor.md diff --git a/electron/index.d.ts b/electron/index.d.ts index c0797775a2..d55b47df4c 100644 --- a/electron/index.d.ts +++ b/electron/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Electron v1.4.2 +// Type definitions for Electron v1.4.5 // Project: http://electron.atom.io/ -// Definitions by: jedmao , rhysd , Milan Burda +// Definitions by: jedmao , rhysd , Milan Burda , aliib // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -2687,6 +2687,247 @@ declare namespace Electron { isTemplateImage(): boolean; } + // https://github.com/electron/electron/blob/master/docs/api/net.md + + /** + * The net module is a client-side API for issuing HTTP(S) requests. + * It is similar to the HTTP and HTTPS modules of Node.js but uses Chromium’s native + * networking library instead of the Node.js implementation, offering better support + * for web proxies. + * The following is a non-exhaustive list of why you may consider using the net module + * instead of the native Node.js modules: + * - Automatic management of system proxy configuration, support of the wpad protocol + * and proxy pac configuration files. + * - Automatic tunneling of HTTPS requests. + * - Support for authenticating proxies using basic, digest, NTLM, Kerberos or negotiate + * authentication schemes. + * - Support for traffic monitoring proxies: Fiddler-like proxies used for access control + * and monitoring. + * + * The net module API has been specifically designed to mimic, as closely as possible, + * the familiar Node.js API. The API components including classes, methods, + * properties and event names are similar to those commonly used in Node.js. + * + * The net API can be used only after the application emits the ready event. + * Trying to use the module before the ready event will throw an error. + */ + interface Net extends NodeJS.EventEmitter { + /** + * @param options The ClientRequest constructor options. + * @param callback A one time listener for the response event. + * + * @returns a ClientRequest instance using the provided options which are directly + * forwarded to the ClientRequest constructor. + */ + request(options: string | RequestOptions, callback?: (response: IncomingMessage) => void): ClientRequest; + } + + /** + * The RequestOptions interface allows to define various options for an HTTP request. + */ + interface RequestOptions { + /** + * The HTTP request method. Defaults to the GET method. + */ + method?: string; + /** + * The request URL. Must be provided in the absolute form with the protocol + * scheme specified as http or https. + */ + url?: string; + /** + * The Session instance with which the request is associated. + */ + session?: Session; + /** + * The name of the partition with which the request is associated. + * Defaults to the empty string. The session option prevails on partition. + * Thus if a session is explicitly specified, partition is ignored. + */ + partition?: string; + /** + * The protocol scheme in the form ‘scheme:’. Currently supported values are ‘http:’ or ‘https:’. + * Defaults to ‘http:’. + */ + Protocol?: 'http:' | 'https:'; + /** + * The server host provided as a concatenation of the hostname and the port number ‘hostname:port’. + */ + host?: string; + /** + * The server host name. + */ + hostname?: string; + /** + * The server’s listening port number. + */ + port?: number; + /** + * The path part of the request URL. + */ + path?: string; + /** + * A map specifying extra HTTP header name/value. + */ + headers?: { [key: string]: any }; + } + + /** + * The ClientRequest class represents an HTTP request. + */ + class ClientRequest extends NodeJS.EventEmitter { + /** + * Emitted when an HTTP response is received for the request. + */ + on(event: 'response', listener: (response: IncomingMessage) => void): this; + /** + * Emitted when an authenticating proxy is asking for user credentials. + * The callback function is expected to be called back with user credentials. + * Providing empty credentials will cancel the request and report an authentication + * error on the response object. + */ + on(event: 'login', listener: (authInfo: LoginAuthInfo, callback: (username?: string, password?: string) => void) => void): this; + /** + * Emitted just after the last chunk of the request’s data has been written into + * the request object. + */ + on(event: 'finish', listener: () => void): this; + /** + * Emitted when the request is aborted. The abort event will not be fired if the + * request is already closed. + */ + on(event: 'abort', listener: () => void): this; + /** + * Emitted when the net module fails to issue a network request. + * Typically when the request object emits an error event, a close event will + * subsequently follow and no response object will be provided. + */ + on(event: 'error', listener: (error: Error) => void): this; + /** + * Emitted as the last event in the HTTP request-response transaction. + * The close event indicates that no more events will be emitted on either the + * request or response objects. + */ + on(event: 'close', listener: () => void): this; + on(event: string, listener: Function): this; + /** + * A Boolean specifying whether the request will use HTTP chunked transfer encoding or not. + * Defaults to false. The property is readable and writable, however it can be set only before + * the first write operation as the HTTP headers are not yet put on the wire. + * Trying to set the chunkedEncoding property after the first write will throw an error. + * + * Using chunked encoding is strongly recommended if you need to send a large request + * body as data will be streamed in small chunks instead of being internally buffered + * inside Electron process memory. + */ + chunkedEncoding: boolean; + /** + * @param options If options is a String, it is interpreted as the request URL. + * If it is an object, it is expected to be a RequestOptions. + * @param callback A one time listener for the response event. + */ + constructor(options: string | RequestOptions, callback?: (response: IncomingMessage) => void); + /** + * Adds an extra HTTP header. The header name will issued as it is without lowercasing. + * It can be called only before first write. Calling this method after the first write + * will throw an error. + * @param name An extra HTTP header name. + * @param value An extra HTTP header value. + */ + setHeader(name: string, value: string): void; + /** + * @param name Specify an extra header name. + * @returns The value of a previously set extra header name. + */ + getHeader(name: string): string; + /** + * Removes a previously set extra header name. This method can be called only before first write. + * Trying to call it after the first write will throw an error. + * @param name Specify an extra header name. + */ + removeHeader(name: string): void; + /** + * Adds a chunk of data to the request body. The first write operation may cause the + * request headers to be issued on the wire. + * After the first write operation, it is not allowed to add or remove a custom header. + * @param chunk A chunk of the request body’s data. If it is a string, it is converted + * into a Buffer using the specified encoding. + * @param encoding Used to convert string chunks into Buffer objects. Defaults to ‘utf-8’. + * @param callback Called after the write operation ends. + */ + write(chunk: string | Buffer, encoding?: string, callback?: Function): boolean; + /** + * Sends the last chunk of the request data. Subsequent write or end operations will not be allowed. + * The finish event is emitted just after the end operation. + * @param chunk A chunk of the request body’s data. If it is a string, it is converted into + * a Buffer using the specified encoding. + * @param encoding Used to convert string chunks into Buffer objects. Defaults to ‘utf-8’. + * @param callback Called after the write operation ends. + * + */ + end(chunk?: string | Buffer, encoding?: string, callback?: Function): boolean; + /** + * Cancels an ongoing HTTP transaction. If the request has already emitted the close event, + * the abort operation will have no effect. + * Otherwise an ongoing event will emit abort and close events. + * Additionally, if there is an ongoing response object,it will emit the aborted event. + */ + abort(): void + } + + /** + * An IncomingMessage represents an HTTP response. + */ + interface IncomingMessage extends NodeJS.ReadableStream { + /** + * The data event is the usual method of transferring response data into applicative code. + */ + on(event: 'data', listener: (chunk: Buffer) => void): this; + /** + * Indicates that response body has ended. + */ + on(event: 'end', listener: () => void): this; + /** + * Emitted when a request has been canceled during an ongoing HTTP transaction. + */ + on(event: 'aborted', listener: () => void): this; + /** + * Emitted when an error was encountered while streaming response data events. + * For instance, if the server closes the underlying while the response is still + * streaming, an error event will be emitted on the response object and a close + * event will subsequently follow on the request object. + */ + on(event: 'error', listener: (error: Error) => void): this; + on(event: string, listener: Function): this; + /** + * An Integer indicating the HTTP response status code. + */ + statusCode: number; + /** + * A String representing the HTTP status message. + */ + statusMessage: string; + /** + * An object representing the response HTTP headers. The headers object is formatted as follows: + * - All header names are lowercased. + * - Each header name produces an array-valued property on the headers object. + * - Each header value is pushed into the array associated with its header name. + */ + headers: Headers; + /** + * A string indicating the HTTP protocol version number. Typical values are ‘1.0’ or ‘1.1’. + */ + httpVersion: string; + /** + * An integer-valued read-only property that returns the HTTP major version number. + */ + httpVersionMajor: number; + /** + * An integer-valued read-only property that returns the HTTP minor version number. + */ + httpVersionMinor: number; + } + // https://github.com/electron/electron/blob/master/docs/api/power-monitor.md /** @@ -5565,6 +5806,7 @@ declare namespace Electron { globalShortcut: Electron.GlobalShortcut; Menu: typeof Electron.Menu; MenuItem: typeof Electron.MenuItem; + net: Electron.Net; powerMonitor: Electron.PowerMonitor; powerSaveBlocker: Electron.PowerSaveBlocker; protocol: Electron.Protocol; diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index 490b708011..77bd63e3e6 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 ddbee13c28..d531d12f03 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 0000000000..26ed7b6677 --- /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 0000000000..c1d3d5ce21 --- /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 0000000000..a36756343e --- /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/eventemitter2/eventemitter2-tests.ts b/eventemitter2/eventemitter2-tests.ts index 936366c0b9..8a7849abfa 100644 --- a/eventemitter2/eventemitter2-tests.ts +++ b/eventemitter2/eventemitter2-tests.ts @@ -18,7 +18,8 @@ function testConfiguration() { wildcard: true, delimiter: '::', newListener: false, - maxListeners: 20 + maxListeners: 20, + verboseMemoryLeak: true }); var bar = new EventEmitter2({}); var bazz = new EventEmitter2(); diff --git a/eventemitter2/index.d.ts b/eventemitter2/index.d.ts index de1be0d064..0372b675dc 100644 --- a/eventemitter2/index.d.ts +++ b/eventemitter2/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for EventEmitter2 v0.14.4 +// Type definitions for EventEmitter2 v2.2.0 // Project: https://github.com/asyncly/EventEmitter2 // Definitions by: ryiwamoto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -23,6 +23,11 @@ interface EventEmitter2Configuration { * max listeners that can be assigned to an event, default 10. */ maxListeners?: number; + + /** + * show event name in memory leak message when more than maximum amount of listeners is assigned, default false + */ + verboseMemoryLeak?: boolean; } declare class EventEmitter2 { diff --git a/eventemitter3/eventemitter3-tests.ts b/eventemitter3/eventemitter3-tests.ts index c0a532fc87..9c8e379ec9 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; + super(); } - 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'); - } - - 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'; +// 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); +} - 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.eventNames() +// should return array of strings or symbols +ee.eventNames().every((event) => { + if (typeof event === 'symbol') { + return false; + } else { + return event.length > 0; } - - class BeastES6 extends EventEmitter3ImportedAsES6Module { - /* rawr, i'm a beast */ - } - - 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 0000000000..30c9419a57 --- /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 31ede80c21..9c1fe2397e 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` */ - addListener(event: string, fn: Function, context?: any): EventEmitter; + off(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; + + /** + * Alias method for `on` + */ + addListener(event: string | symbol, fn: Function, context?: any): this; /** * This function doesn't apply anymore. * @deprecated */ - setMaxListeners(): EventEmitter; + setMaxListeners(): this; } diff --git a/express-formidable/express-formidable-tests.ts b/express-formidable/express-formidable-tests.ts new file mode 100644 index 0000000000..91f9e34519 --- /dev/null +++ b/express-formidable/express-formidable-tests.ts @@ -0,0 +1,16 @@ +import express = require("express"); +import expform = require("express-formidable"); + +const app = express(); + +app.use("/form1", expform()); +app.use("/form2", expform({ + encoding: "utf-8", + uploadDir: "./uploads", + keepExtensions: true, + type: "multipart", + maxFieldsSize: 3 * 1024 * 1024, + maxFields: 50, + hash: "sha1", + multiples: true +})); diff --git a/express-formidable/index.d.ts b/express-formidable/index.d.ts new file mode 100644 index 0000000000..57342521c2 --- /dev/null +++ b/express-formidable/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for express-formidable 1.0.0 +// Project: https://github.com/noraesae/express-formidable +// Definitions by: Torkild Dyvik Olsen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { RequestHandler } from "express"; + +interface ExpressFormidableOptions { + encoding?: string; + uploadDir?: string; + keepExtensions?: boolean; + type?: "multipart" | "urlencoded"; + maxFieldsSize?: number; + maxFields?: number; + hash?: boolean | "sha1" | "md5"; + multiples?: boolean; +} + +declare function ExpressFormidable(options?: ExpressFormidableOptions): RequestHandler; + +export = ExpressFormidable; diff --git a/express-formidable/tsconfig.json b/express-formidable/tsconfig.json new file mode 100644 index 0000000000..bac18433b1 --- /dev/null +++ b/express-formidable/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", + "express-formidable-tests.ts" + ] +} diff --git a/express/express-tests.ts b/express/express-tests.ts index fdcd85801f..e643ba208b 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -29,8 +29,7 @@ namespace express_tests { res.send('hello world'); }); - const router = express.Router(); - + const router = express.Router({ caseSensitive: true, mergeParams: true, strict: true }); const pathStr: string = 'test'; const pathRE: RegExp = /test/; diff --git a/express/index.d.ts b/express/index.d.ts index b1a618b79e..7222c8d3d9 100644 --- a/express/index.d.ts +++ b/express/index.d.ts @@ -28,7 +28,28 @@ declare namespace e { */ var static: typeof serveStatic; - export function Router(options?: any): core.Router; + export function Router(options?: RouterOptions): core.Router; + + interface RouterOptions { + /** + * Enable case sensitivity. + */ + caseSensitive?: boolean; + + /** + * Preserve the req.params values from the parent router. + * If the parent and the child have conflicting param names, the child’s value take precedence. + * + * @default false + * @since 4.5.0 + */ + mergeParams?: boolean; + + /** + * Enable strict routing. + */ + strict?: boolean; + } interface Application extends core.Application { } interface CookieOptions extends core.CookieOptions { } diff --git a/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts new file mode 100644 index 0000000000..62e522a348 --- /dev/null +++ b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts @@ -0,0 +1,97 @@ +import { optimize, Configuration, Plugin } from 'webpack' + +import * as ExtractTextPlugin from 'extract-text-webpack-plugin' + + +let configuration: Configuration + + +configuration = { + // The standard entry point and output config + entry: { + posts: "./posts", + post: "./post", + about: "./about" + }, + output: { + filename: "[name].js", + chunkFilename: "[id].js" + }, + module: { + rules: [ + // Extract css files + { + test: /\.css$/, + loader: ExtractTextPlugin.extract({ + fallbackLoader: "style-loader", + loader: "css-loader", + }) + }, + // Optionally extract less files + // or any other compile-to-css language + { + test: /\.less$/, + loader: ExtractTextPlugin.extract({ + fallbackLoader: "style-loader", + loader: ["css-loader", "less-loader"], + }) + } + // You could also use other loaders the same way. I. e. the autoprefixer-loader + ] + }, + // Use the plugin to specify the resulting filename (and add needed behavior to the compiler) + plugins: [ + new ExtractTextPlugin("[name].css") + ] +}; + +configuration = { + // ... + plugins: [ + new ExtractTextPlugin({ + filename: "style.css", + allChunks: true, + }) + ] +}; + +configuration = { + // ... + plugins: [ + new optimize.CommonsChunkPlugin("commons", "commons.js"), + new ExtractTextPlugin("[name].css") + ] +}; + +configuration = { + // ... + module: { + rules: [ + { test: /\.css$/, loader: ExtractTextPlugin.extract({ + fallbackLoader: "style-loader", + loader: "css-loader" + }) } + ] + }, + plugins: [ + new ExtractTextPlugin("styles.css") + ], +}; + +// multiple extract instances +let extractCSS = new ExtractTextPlugin('stylesheets/[name].css'); +let extractLESS = new ExtractTextPlugin('stylesheets/[name].less'); + +configuration = { + // ... + module: { + rules: [ + { test: /\.scss$/i, loader: extractCSS.extract(['css','sass']) }, + { test: /\.less$/i, loader: extractLESS.extract(['css','less']) }, + ] + }, + plugins: [ + extractCSS, + extractLESS, + ], +}; diff --git a/extract-text-webpack-plugin/index.d.ts b/extract-text-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..21052b08c1 --- /dev/null +++ b/extract-text-webpack-plugin/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for extract-text-webpack-plugin 2.0.0 +// Project: https://github.com/webpack/extract-text-webpack-plugin +// Definitions by: flying-sheep +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin, OldLoader } from 'webpack' + +/** + * extract-text-webpack-plugin has no support for .options instead of .query yet. + * See https://github.com/webpack/extract-text-webpack-plugin/issues/281 + */ +type Loader = string | OldLoader + +interface ExtractPluginOptions { + /** the filename of the result file. May contain `[name]`, `[id]` and `[contenthash]` */ + filename: string + /** extract from all additional chunks too (by default it extracts only from the initial chunk(s)) */ + allChunks?: boolean + /** disables the plugin */ + disable?: boolean + /** Unique ident for this plugin instance. (For advanced usage only, by default automatically generated) */ + id?: string +} + +interface ExtractOptions { + /** the loader(s) that should be used for converting the resource to a css exporting module */ + loader: Loader | Loader[] + /** the loader(s) that should be used when the css is not extracted (i.e. in an additional chunk when `allChunks: false`) */ + fallbackLoader?: Loader | Loader[] + /** override the `publicPath` setting for this loader */ + publicPath?: string +} + +/** + * Use an `ExtractTextPlugin` instance and a loader returned by `extract` in concert to write files to disk instead of loading them into others. + * Usage example at https://github.com/webpack/extract-text-webpack-plugin#usage-example-with-css + */ +interface ExtractTextPlugin extends Plugin { + /** Create a plugin instance defining the extraction target file(s) for the files loaded by `extract` */ + new (options: string | ExtractPluginOptions): ExtractTextPlugin + /** + * Creates an extracting loader from an existing loader. + * Use the resulting loader in `module.rules`/`module.loaders`. + */ + extract: (loader: Loader | Loader[] | ExtractOptions) => Loader +} + +declare const extractTextPlugin: ExtractTextPlugin +export = extractTextPlugin diff --git a/extract-text-webpack-plugin/tsconfig.json b/extract-text-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..77520c362d --- /dev/null +++ b/extract-text-webpack-plugin/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", + "extract-text-webpack-plugin-tests.ts" + ] +} \ No newline at end of file diff --git a/fusioncharts/fusioncharts-tests.ts b/fusioncharts/fusioncharts-tests.ts new file mode 100644 index 0000000000..9bbf640225 --- /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 0000000000..dc053859b9 --- /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/typescript-services/tsconfig.json b/fusioncharts/tsconfig.json similarity index 90% rename from typescript-services/tsconfig.json rename to fusioncharts/tsconfig.json index 87f7d96a9f..8abb296bab 100644 --- a/typescript-services/tsconfig.json +++ b/fusioncharts/tsconfig.json @@ -14,6 +14,6 @@ }, "files": [ "index.d.ts", - "typescriptServices-tests.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 0000000000..2c35403d10 --- /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 0000000000..31bbd1a83b --- /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 0000000000..73c4caf42d --- /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/google-libphonenumber/index.d.ts b/google-libphonenumber/index.d.ts index 4a0f865373..28f72f67a3 100644 --- a/google-libphonenumber/index.d.ts +++ b/google-libphonenumber/index.d.ts @@ -15,11 +15,21 @@ declare namespace libphonenumber { interface PhoneNumber { } + export module PhoneNumberUtil { + export enum ValidationResult { + IS_POSSIBLE, + INVALID_COUNTRY_CODE, + TOO_SHORT, + TOO_LONG + } + } + export class PhoneNumberUtil { static getInstance(): PhoneNumberUtil parse(number: string, region: string): PhoneNumber; isValidNumber(phoneNumber: PhoneNumber): boolean; isPossibleNumber(phoneNumber: PhoneNumber): boolean; + isPossibleNumberWithReason(phoneNumber: PhoneNumber): PhoneNumberUtil.ValidationResult; isValidNumberForRegion(phoneNumber: PhoneNumber, region: string): boolean; getRegionCodeForNumber(phoneNumber: PhoneNumber): string; isNANPACountry(regionCode: string): boolean; diff --git a/graphql/index.d.ts b/graphql/index.d.ts index c7310ab3cc..b156afa6cf 100644 --- a/graphql/index.d.ts +++ b/graphql/index.d.ts @@ -1,11 +1,11 @@ -// Type definitions for graphql v0.7.0 +// Type definitions for graphql v0.8.0 // Project: https://www.npmjs.com/package/graphql -// Definitions by: TonyYang , Caleb Meredith +// Definitions by: TonyYang , Caleb Meredith , Dominic Watson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************* - * * - * MODULES * + * * + * MODULES * * * *************************************/ /////////////////////////// @@ -29,6 +29,9 @@ declare module "graphql" { // Execute GraphQL queries. export { execute, + defaultFieldResolver, + responsePathAsArray, + ExecutionResult, } from 'graphql/execution'; @@ -43,6 +46,8 @@ declare module "graphql" { export { GraphQLError, formatError, + GraphQLFormattedError, + GraphQLErrorLocation, } from 'graphql/error'; @@ -70,6 +75,9 @@ declare module "graphql" { // Print a GraphQLSchema to GraphQL Schema language. printSchema, + // Print a GraphQLType to GraphQL Schema language. + printType, + // Create a GraphQLType from a GraphQL language AST. typeFromAST, @@ -102,12 +110,32 @@ declare module "graphql" { // Asserts a string is a valid GraphQL name. assertValidName, + + BreakingChange, + + IntrospectionDirective, + IntrospectionEnumType, + IntrospectionEnumValue, + IntrospectionField, + IntrospectionInputObjectType, + IntrospectionInputValue, + IntrospectionInterfaceType, + IntrospectionListTypeRef, + IntrospectionNamedTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionObjectType, + IntrospectionQuery, + IntrospectionScalarType, + IntrospectionSchema, + IntrospectionType, + IntrospectionTypeRef, + IntrospectionUnionType, } from 'graphql/utilities'; } declare module "graphql/graphql" { - import { GraphQLError } from 'graphql/error/GraphQLError'; import { GraphQLSchema } from 'graphql/type/schema'; + import { ExecutionResult } from 'graphql/execution/execute'; /** * This is the primary entry point function for fulfilling GraphQL operations @@ -142,18 +170,7 @@ declare module "graphql/graphql" { [key: string]: any }, operationName?: string - ): Promise; - - /** - * The result of a GraphQL parse, validation and execution. - * - * `data` is the result of a successful execution of the query. - * `errors` is included when any errors occurred as a non-empty array. - */ - type GraphQLResult = { - data?: Object; - errors?: Array; - } + ): Promise; } /////////////////////////// @@ -177,7 +194,7 @@ declare module "graphql/language/index" { export { getLocation } from 'graphql/language/location'; import * as Kind from 'graphql/language/kinds'; export { Kind }; - export { createLexer, TokenKind } from 'graphql/language/lexer'; + export { createLexer, TokenKind, Lexer } from 'graphql/language/lexer'; export { parse, parseValue, parseType } from 'graphql/language/parser'; export { print } from 'graphql/language/printer'; export { Source } from 'graphql/language/source'; @@ -286,46 +303,46 @@ declare module "graphql/language/ast" { /** * The list of all possible AST node types. */ - export type Node = Name - | Document - | OperationDefinition - | VariableDefinition - | Variable - | SelectionSet - | Field - | Argument - | FragmentSpread - | InlineFragment - | FragmentDefinition - | IntValue - | FloatValue - | StringValue - | BooleanValue - | EnumValue - | ListValue - | ObjectValue - | ObjectField - | Directive - | NamedType - | ListType - | NonNullType - | SchemaDefinition - | OperationTypeDefinition - | ScalarTypeDefinition - | ObjectTypeDefinition - | FieldDefinition - | InputValueDefinition - | InterfaceTypeDefinition - | UnionTypeDefinition - | EnumTypeDefinition - | EnumValueDefinition - | InputObjectTypeDefinition - | TypeExtensionDefinition - | DirectiveDefinition + export type ASTNode = NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | TypeExtensionDefinitionNode + | DirectiveDefinitionNode; // Name - export type Name = { + export type NameNode = { kind: 'Name'; loc?: Location; value: string; @@ -333,306 +350,306 @@ declare module "graphql/language/ast" { // Document - export type Document = { + export type DocumentNode = { kind: 'Document'; loc?: Location; - definitions: Array; + definitions: Array; } - export type Definition = OperationDefinition - | FragmentDefinition - | TypeSystemDefinition // experimental non-spec addition. + export type DefinitionNode = OperationDefinitionNode + | FragmentDefinitionNode + | TypeSystemDefinitionNode // experimental non-spec addition. - export type OperationDefinition = { + export type OperationDefinitionNode = { kind: 'OperationDefinition'; loc?: Location; - operation: OperationType; - name?: Name; - variableDefinitions?: Array; - directives?: Array; - selectionSet: SelectionSet; + operation: OperationTypeNode; + name?: NameNode; + variableDefinitions?: Array; + directives?: Array; + selectionSet: SelectionSetNode; } // Note: subscription is an experimental non-spec addition. - export type OperationType = 'query' | 'mutation' | 'subscription'; + export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; - export type VariableDefinition = { + export type VariableDefinitionNode = { kind: 'VariableDefinition'; loc?: Location; - variable: Variable; - type: Type; - defaultValue?: Value; + variable: VariableNode; + type: TypeNode; + defaultValue?: ValueNode; } - export type Variable = { + export type VariableNode = { kind: 'Variable'; loc?: Location; - name: Name; + name: NameNode; } - export type SelectionSet = { + export type SelectionSetNode = { kind: 'SelectionSet'; loc?: Location; - selections: Array; + selections: Array; } - export type Selection = Field - | FragmentSpread - | InlineFragment + export type SelectionNode = FieldNode + | FragmentSpreadNode + | InlineFragmentNode - export type Field = { + export type FieldNode = { kind: 'Field'; loc?: Location; - alias?: Name; - name: Name; - arguments?: Array; - directives?: Array; - selectionSet?: SelectionSet; + alias?: NameNode; + name: NameNode; + arguments?: Array; + directives?: Array; + selectionSet?: SelectionSetNode; } - export type Argument = { + export type ArgumentNode = { kind: 'Argument'; loc?: Location; - name: Name; - value: Value; + name: NameNode; + value: ValueNode; } // Fragments - export type FragmentSpread = { + export type FragmentSpreadNode = { kind: 'FragmentSpread'; loc?: Location; - name: Name; - directives?: Array; + name: NameNode; + directives?: Array; } - export type InlineFragment = { + export type InlineFragmentNode = { kind: 'InlineFragment'; loc?: Location; - typeCondition?: NamedType; - directives?: Array; - selectionSet: SelectionSet; + typeCondition?: NamedTypeNode; + directives?: Array; + selectionSet: SelectionSetNode; } - export type FragmentDefinition = { + export type FragmentDefinitionNode = { kind: 'FragmentDefinition'; loc?: Location; - name: Name; - typeCondition: NamedType; - directives?: Array; - selectionSet: SelectionSet; + name: NameNode; + typeCondition: NamedTypeNode; + directives?: Array; + selectionSet: SelectionSetNode; } // Values - export type Value = Variable - | IntValue - | FloatValue - | StringValue - | BooleanValue - | EnumValue - | ListValue - | ObjectValue + export type ValueNode = VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode - export type IntValue = { + export type IntValueNode = { kind: 'IntValue'; loc?: Location; value: string; } - export type FloatValue = { + export type FloatValueNode = { kind: 'FloatValue'; loc?: Location; value: string; } - export type StringValue = { + export type StringValueNode = { kind: 'StringValue'; loc?: Location; value: string; } - export type BooleanValue = { + export type BooleanValueNode = { kind: 'BooleanValue'; loc?: Location; value: boolean; } - export type EnumValue = { + export type EnumValueNode = { kind: 'EnumValue'; loc?: Location; value: string; } - export type ListValue = { + export type ListValueNode = { kind: 'ListValue'; loc?: Location; - values: Array; + values: Array; } - export type ObjectValue = { + export type ObjectValueNode = { kind: 'ObjectValue'; loc?: Location; - fields: Array; + fields: Array; } - export type ObjectField = { + export type ObjectFieldNode = { kind: 'ObjectField'; loc?: Location; - name: Name; - value: Value; + name: NameNode; + value: ValueNode; } // Directives - export type Directive = { + export type DirectiveNode = { kind: 'Directive'; loc?: Location; - name: Name; - arguments?: Array; + name: NameNode; + arguments?: Array; } // Type Reference - export type Type = NamedType - | ListType - | NonNullType + export type TypeNode = NamedTypeNode + | ListTypeNode + | NonNullTypeNode - export type NamedType = { + export type NamedTypeNode = { kind: 'NamedType'; loc?: Location; - name: Name; + name: NameNode; }; - export type ListType = { + export type ListTypeNode = { kind: 'ListType'; loc?: Location; - type: Type; + type: TypeNode; } - export type NonNullType = { + export type NonNullTypeNode = { kind: 'NonNullType'; loc?: Location; - type: NamedType | ListType; + type: NamedTypeNode | ListTypeNode; } // Type System Definition - export type TypeSystemDefinition = SchemaDefinition - | TypeDefinition - | TypeExtensionDefinition - | DirectiveDefinition + export type TypeSystemDefinitionNode = SchemaDefinitionNode + | TypeDefinitionNode + | TypeExtensionDefinitionNode + | DirectiveDefinitionNode - export type SchemaDefinition = { + export type SchemaDefinitionNode = { kind: 'SchemaDefinition'; loc?: Location; - directives: Array; - operationTypes: Array; + directives: Array; + operationTypes: Array; } - export type OperationTypeDefinition = { + export type OperationTypeDefinitionNode = { kind: 'OperationTypeDefinition'; loc?: Location; - operation: OperationType; - type: NamedType; + operation: OperationTypeNode; + type: NamedTypeNode; } - export type TypeDefinition = ScalarTypeDefinition - | ObjectTypeDefinition - | InterfaceTypeDefinition - | UnionTypeDefinition - | EnumTypeDefinition - | InputObjectTypeDefinition + export type TypeDefinitionNode = ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode - export type ScalarTypeDefinition = { + export type ScalarTypeDefinitionNode = { kind: 'ScalarTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; + name: NameNode; + directives?: Array; } - export type ObjectTypeDefinition = { + export type ObjectTypeDefinitionNode = { kind: 'ObjectTypeDefinition'; loc?: Location; - name: Name; - interfaces?: Array; - directives?: Array; - fields: Array; + name: NameNode; + interfaces?: Array; + directives?: Array; + fields: Array; } - export type FieldDefinition = { + export type FieldDefinitionNode = { kind: 'FieldDefinition'; loc?: Location; - name: Name; - arguments: Array; - type: Type; - directives?: Array; + name: NameNode; + arguments: Array; + type: TypeNode; + directives?: Array; } - export type InputValueDefinition = { + export type InputValueDefinitionNode = { kind: 'InputValueDefinition'; loc?: Location; - name: Name; - type: Type; - defaultValue?: Value; - directives?: Array; + name: NameNode; + type: TypeNode; + defaultValue?: ValueNode; + directives?: Array; } - export type InterfaceTypeDefinition = { + export type InterfaceTypeDefinitionNode = { kind: 'InterfaceTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - fields: Array; + name: NameNode; + directives?: Array; + fields: Array; } - export type UnionTypeDefinition = { + export type UnionTypeDefinitionNode = { kind: 'UnionTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - types: Array; + name: NameNode; + directives?: Array; + types: Array; } - export type EnumTypeDefinition = { + export type EnumTypeDefinitionNode = { kind: 'EnumTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - values: Array; + name: NameNode; + directives?: Array; + values: Array; } - export type EnumValueDefinition = { + export type EnumValueDefinitionNode = { kind: 'EnumValueDefinition'; loc?: Location; - name: Name; - directives?: Array; + name: NameNode; + directives?: Array; } - export type InputObjectTypeDefinition = { + export type InputObjectTypeDefinitionNode = { kind: 'InputObjectTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - fields: Array; + name: NameNode; + directives?: Array; + fields: Array; } - export type TypeExtensionDefinition = { + export type TypeExtensionDefinitionNode = { kind: 'TypeExtensionDefinition'; loc?: Location; - definition: ObjectTypeDefinition; + definition: ObjectTypeDefinitionNode; } - export type DirectiveDefinition = { + export type DirectiveDefinitionNode = { kind: 'DirectiveDefinition'; loc?: Location; - name: Name; - arguments?: Array; - locations: Array; + name: NameNode; + arguments?: Array; + locations: Array; } } @@ -664,6 +681,7 @@ declare module "graphql/language/kinds" { const FLOAT: 'FloatValue'; const STRING: 'StringValue'; const BOOLEAN: 'BooleanValue'; + const NULL: 'NullValue'; const ENUM: 'EnumValue'; const LIST: 'ListValue'; const OBJECT: 'ObjectValue'; @@ -801,7 +819,7 @@ declare module "graphql/language/location" { } declare module "graphql/language/parser" { - import { NamedType, Type, Value, Document } from "graphql/language/ast"; + import { NamedTypeNode, TypeNode, ValueNode, DocumentNode } from "graphql/language/ast"; import { Source } from "graphql/language/source"; import { Lexer } from "graphql/language/lexer"; @@ -824,7 +842,7 @@ declare module "graphql/language/parser" { function parse( source: string | Source, options?: ParseOptions - ): Document; + ): DocumentNode; /** * Given a string containing a GraphQL value, parse the AST for that value. @@ -836,9 +854,9 @@ declare module "graphql/language/parser" { function parseValue( source: Source | string, options?: ParseOptions - ): Value; + ): ValueNode; - function parseConstValue(lexer: Lexer): Value; + function parseConstValue(lexer: Lexer): ValueNode; /** * Type : @@ -846,12 +864,20 @@ declare module "graphql/language/parser" { * - ListType * - NonNullType */ - function parseType(lexer: Lexer): Type; + function parseType(lexer: Lexer): TypeNode; + + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + function parseTypeReference(lexer: Lexer): TypeNode; /** * NamedType : Name */ - function parseNamedType(lexer: Lexer): NamedType; + function parseNamedType(lexer: Lexer): NamedTypeNode; } declare module "graphql/language/printer" { @@ -889,6 +915,7 @@ declare module "graphql/language/visitor" { FloatValue: number[]; StringValue: string[]; BooleanValue: boolean[]; + NullValue: null[], EnumValue: any[]; ListValue: string[]; ObjectValue: string[]; @@ -980,14 +1007,15 @@ declare module "graphql/type/index" { TypeNameMetaFieldDef, } from 'graphql/type/introspection'; + export { DirectiveLocationEnum } from 'graphql/type/directives'; } declare module "graphql/type/definition" { import { - OperationDefinition, - Field, - FragmentDefinition, - Value, + OperationDefinitionNode, + FieldNode, + FragmentDefinitionNode, + ValueNode, } from 'graphql/language/ast'; import { GraphQLSchema } from 'graphql/type/schema'; @@ -1136,7 +1164,7 @@ declare module "graphql/type/definition" { parseValue(value: any): any; // Parses an externally provided literal value to use as an input. - parseLiteral(valueAST: Value): any; + parseLiteral(valueNode: ValueNode): any; toString(): string; } @@ -1146,7 +1174,7 @@ declare module "graphql/type/definition" { description?: string; serialize: (value: any) => TInternal; parseValue?: (value: any) => TExternal; - parseLiteral?: (valueAST: Value) => TInternal; + parseLiteral?: (valueNode: ValueNode) => TInternal; } /** @@ -1192,7 +1220,7 @@ declare module "graphql/type/definition" { isTypeOf: GraphQLIsTypeOfFn; constructor(config: GraphQLObjectTypeConfig); - getFields(): GraphQLFieldDefinitionMap; + getFields(): GraphQLFieldMap; getInterfaces(): Array; toString(): string; } @@ -1207,7 +1235,7 @@ declare module "graphql/type/definition" { description?: string } - export type GraphQLTypeResolveFn = ( + export type GraphQLTypeResolver = ( value: any, context: any, info: GraphQLResolveInfo @@ -1219,7 +1247,7 @@ declare module "graphql/type/definition" { info: GraphQLResolveInfo ) => boolean; - export type GraphQLFieldResolveFn = ( + export type GraphQLFieldResolver = ( source: TSource, args: { [argName: string]: any }, context: any, @@ -1228,21 +1256,23 @@ declare module "graphql/type/definition" { export interface GraphQLResolveInfo { fieldName: string; - fieldASTs: Array; + fieldNodes: Array; returnType: GraphQLOutputType; parentType: GraphQLCompositeType; - path: Array; + path: ResponsePath; schema: GraphQLSchema; - fragments: { [fragmentName: string]: FragmentDefinition }; + fragments: { [fragmentName: string]: FragmentDefinitionNode }; rootValue: any; - operation: OperationDefinition; + operation: OperationDefinitionNode; variableValues: { [variableName: string]: any }; } + export type ResponsePath = { prev: ResponsePath, key: string | number } | void; + export interface GraphQLFieldConfig { type: GraphQLOutputType; args?: GraphQLFieldConfigArgumentMap; - resolve?: GraphQLFieldResolveFn; + resolve?: GraphQLFieldResolver; deprecationReason?: string; description?: string; } @@ -1261,12 +1291,12 @@ declare module "graphql/type/definition" { [fieldName: string]: GraphQLFieldConfig; } - export interface GraphQLFieldDefinition { + export interface GraphQLField { name: string; description: string; type: GraphQLOutputType; args: Array; - resolve: GraphQLFieldResolveFn; + resolve: GraphQLFieldResolver; isDeprecated: boolean; deprecationReason: string; } @@ -1278,8 +1308,8 @@ declare module "graphql/type/definition" { description?: string; } - export interface GraphQLFieldDefinitionMap { - [fieldName: string]: GraphQLFieldDefinition; + export interface GraphQLFieldMap { + [fieldName: string]: GraphQLField; } /** @@ -1303,11 +1333,11 @@ declare module "graphql/type/definition" { class GraphQLInterfaceType { name: string; description: string; - resolveType: GraphQLTypeResolveFn; + resolveType: GraphQLTypeResolver; constructor(config: GraphQLInterfaceTypeConfig); - getFields(): GraphQLFieldDefinitionMap; + getFields(): GraphQLFieldMap; toString(): string; } @@ -1320,7 +1350,7 @@ declare module "graphql/type/definition" { * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolveFn, + resolveType?: GraphQLTypeResolver, description?: string } @@ -1350,7 +1380,7 @@ declare module "graphql/type/definition" { class GraphQLUnionType { name: string; description: string; - resolveType: GraphQLTypeResolveFn; + resolveType: GraphQLTypeResolver; constructor(config: GraphQLUnionTypeConfig); @@ -1367,7 +1397,7 @@ declare module "graphql/type/definition" { * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolveFn; + resolveType?: GraphQLTypeResolver; description?: string; } @@ -1397,10 +1427,10 @@ declare module "graphql/type/definition" { description: string; constructor(config: GraphQLEnumTypeConfig); - getValues(): Array; + getValues(): Array; serialize(value: any): string; parseValue(value: any): any; - parseLiteral(valueAST: Value): any; + parseLiteral(valueNode: ValueNode): any; toString(): string; } @@ -1420,7 +1450,7 @@ declare module "graphql/type/definition" { description?: string; } - export interface GraphQLEnumValueDefinition { + export interface GraphQLEnumValue { name: string; description: string; deprecationReason: string; @@ -1451,7 +1481,7 @@ declare module "graphql/type/definition" { name: string; description: string; constructor(config: GraphQLInputObjectTypeConfig); - getFields(): GraphQLInputFieldDefinitionMap; + getFields(): GraphQLInputFieldMap; toString(): string; } @@ -1471,15 +1501,15 @@ declare module "graphql/type/definition" { [fieldName: string]: GraphQLInputFieldConfig; } - export interface GraphQLInputFieldDefinition { + export interface GraphQLInputField { name: string; type: GraphQLInputType; defaultValue?: any; description?: string; } - export interface GraphQLInputFieldDefinitionMap { - [fieldName: string]: GraphQLInputFieldDefinition; + export interface GraphQLInputFieldMap { + [fieldName: string]: GraphQLInputField; } /** @@ -1623,7 +1653,7 @@ declare module "graphql/type/introspection" { GraphQLList, GraphQLNonNull, } from 'graphql/type/definition'; - import { GraphQLFieldDefinition } from 'graphql/type/definition'; + import { GraphQLField } from 'graphql/type/definition'; const __Schema: GraphQLObjectType; const __Directive: GraphQLObjectType; @@ -1647,12 +1677,12 @@ declare module "graphql/type/introspection" { const __TypeKind: GraphQLEnumType; /** - * Note that these are GraphQLFieldDefinition and not GraphQLFieldConfig, + * Note that these are GraphQLField and not GraphQLFieldConfig, * so the format for args is different. */ - const SchemaMetaFieldDef: GraphQLFieldDefinition; - const TypeMetaFieldDef: GraphQLFieldDefinition; - const TypeNameMetaFieldDef: GraphQLFieldDefinition; + const SchemaMetaFieldDef: GraphQLField; + const TypeMetaFieldDef: GraphQLField; + const TypeNameMetaFieldDef: GraphQLField; } declare module "graphql/type/scalars" { @@ -1765,19 +1795,19 @@ declare module "graphql/validation/specifiedRules" { declare module "graphql/validation/validate" { import { GraphQLError } from 'graphql/error'; import { - Document, - OperationDefinition, - Variable, - SelectionSet, - FragmentSpread, - FragmentDefinition, + DocumentNode, + OperationDefinitionNode, + VariableNode, + SelectionSetNode, + FragmentSpreadNode, + FragmentDefinitionNode, } from 'graphql/language/ast'; import { GraphQLSchema } from 'graphql/type/schema'; import { GraphQLInputType, GraphQLOutputType, GraphQLCompositeType, - GraphQLFieldDefinition, + GraphQLField, GraphQLArgument } from 'graphql/type/definition'; import { GraphQLDirective } from 'graphql/type/directives'; @@ -1801,7 +1831,7 @@ declare module "graphql/validation/validate" { */ function validate( schema: GraphQLSchema, - ast: Document, + ast: DocumentNode, rules?: Array ): Array; @@ -1814,13 +1844,13 @@ declare module "graphql/validation/validate" { function visitUsingRules( schema: GraphQLSchema, typeInfo: TypeInfo, - documentAST: Document, + documentAST: DocumentNode, rules: Array ): Array; - type HasSelectionSet = OperationDefinition | FragmentDefinition; + type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; interface VariableUsage { - node: Variable, + node: VariableNode, type: GraphQLInputType } @@ -1830,27 +1860,27 @@ declare module "graphql/validation/validate" { * validation rule. */ export class ValidationContext { - constructor(schema: GraphQLSchema, ast: Document, typeInfo: TypeInfo); + constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); reportError(error: GraphQLError): void; getErrors(): Array; getSchema(): GraphQLSchema; - getDocument(): Document; + getDocument(): DocumentNode; - getFragment(name: string): FragmentDefinition; + getFragment(name: string): FragmentDefinitionNode; - getFragmentSpreads(node: SelectionSet): Array; + getFragmentSpreads(node: SelectionSetNode): Array; getRecursivelyReferencedFragments( - operation: OperationDefinition - ): Array; + operation: OperationDefinitionNode + ): Array; - getVariableUsages(node: HasSelectionSet): Array; + getVariableUsages(node: NodeWithSelectionSet): Array; getRecursiveVariableUsages( - operation: OperationDefinition + operation: OperationDefinitionNode ): Array; getType(): GraphQLOutputType; @@ -1859,7 +1889,7 @@ declare module "graphql/validation/validate" { getInputType(): GraphQLInputType; - getFieldDef(): GraphQLFieldDefinition; + getFieldDef(): GraphQLField; getDirective(): GraphQLDirective; @@ -1877,20 +1907,21 @@ declare module "graphql/execution" { } declare module "graphql/execution/index" { - export { execute } from 'graphql/execution/execute'; + export { execute, defaultFieldResolver, responsePathAsArray, ExecutionResult } from 'graphql/execution/execute'; } declare module "graphql/execution/execute" { import { GraphQLError, locatedError } from 'graphql/error'; import { GraphQLSchema } from 'graphql/type/schema'; + import { GraphQLField, GraphQLFieldResolver, ResponsePath } from 'graphql/type/definition'; import { - Directive, - Document, - OperationDefinition, - SelectionSet, - Field, - InlineFragment, - FragmentDefinition + DirectiveNode, + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, + FieldNode, + InlineFragmentNode, + FragmentDefinitionNode, } from 'graphql/language/ast'; /** * Data that must be available at all points during query execution. @@ -1900,9 +1931,9 @@ declare module "graphql/execution/execute" { */ interface ExecutionContext { schema: GraphQLSchema; - fragments: { [key: string]: FragmentDefinition }; + fragments: { [key: string]: FragmentDefinitionNode }; rootValue: any; - operation: OperationDefinition; + operation: OperationDefinitionNode; variableValues: { [key: string]: any }; errors: Array; } @@ -1912,8 +1943,8 @@ declare module "graphql/execution/execute" { * query, `errors` is null if no errors occurred, and is a * non-empty array if an error occurred. */ - interface ExecutionResult { - data: Object; + export interface ExecutionResult { + data: {[key: string]: any}; errors?: Array; } @@ -1927,20 +1958,39 @@ declare module "graphql/execution/execute" { */ function execute( schema: GraphQLSchema, - documentAST: Document, + document: DocumentNode, rootValue?: any, contextValue?: any, variableValues?: { [key: string]: any }, operationName?: string - ): Promise + ): Promise; + + /** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ + export function responsePathAsArray( + path: ResponsePath + ): Array; + + function addPath(prev: ResponsePath, key: string | number): any; + + /** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context. + */ + export const defaultFieldResolver: GraphQLFieldResolver; } declare module "graphql/execution/values" { - import { GraphQLInputType, GraphQLArgument } from 'graphql/type/definition'; + import { GraphQLInputType, GraphQLField, GraphQLArgument } from 'graphql/type/definition'; + import { GraphQLDirective } from 'graphql/type/directives'; import { GraphQLSchema } from 'graphql/type/schema'; - import { Argument, VariableDefinition } from 'graphql/language/ast'; + import { FieldNode, DirectiveNode, VariableDefinitionNode } from 'graphql/language/ast'; /** * Prepares an object map of variableValues of the correct type based on the * provided variable definitions and arbitrary input. If the input cannot be @@ -1948,7 +1998,7 @@ declare module "graphql/execution/values" { */ function getVariableValues( schema: GraphQLSchema, - definitionASTs: Array, + varDefNodes: Array, inputs: { [key: string]: any } ): { [key: string]: any } @@ -1957,8 +2007,8 @@ declare module "graphql/execution/values" { * definitions and list of argument AST nodes. */ function getArgumentValues( - argDefs: Array, - argASTs: Array, + def: GraphQLField | GraphQLDirective, + node: FieldNode | DirectiveNode, variableValues?: { [key: string]: any } ): { [key: string]: any }; } @@ -1974,7 +2024,7 @@ declare module "graphql/error/index" { export { GraphQLError } from 'graphql/error/GraphQLError'; export { syntaxError } from 'graphql/error/syntaxError'; export { locatedError } from 'graphql/error/locatedError'; - export { formatError } from 'graphql/error/formatError'; + export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from 'graphql/error/formatError'; } declare module "graphql/error/formatError" { @@ -1988,7 +2038,8 @@ declare module "graphql/error/formatError" { type GraphQLFormattedError = { message: string, - locations: Array + locations: Array, + path: Array }; type GraphQLErrorLocation = { @@ -1999,7 +2050,7 @@ declare module "graphql/error/formatError" { declare module "graphql/error/GraphQLError" { import { getLocation } from 'graphql/language'; - import { Node } from 'graphql/language/ast'; + import { ASTNode } from 'graphql/language/ast'; import { Source } from 'graphql/language/source'; /** @@ -2040,7 +2091,7 @@ declare module "graphql/error/GraphQLError" { /** * An array of GraphQL AST Nodes corresponding to this error. */ - nodes: Array | void; + nodes: Array | void; /** * The source GraphQL document corresponding to this error. @@ -2100,6 +2151,25 @@ declare module "graphql/utilities" { declare module "graphql/utilities/index" { // The GraphQL query recommended for a full schema introspection. export { introspectionQuery } from 'graphql/utilities/introspectionQuery'; + export { + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, + } from 'graphql/utilities/introspectionQuery'; // Gets the target Operation from a Document export { getOperationAST } from 'graphql/utilities/getOperationAST'; @@ -2114,7 +2184,7 @@ declare module "graphql/utilities/index" { export { extendSchema } from 'graphql/utilities/extendSchema'; // Print a GraphQLSchema to GraphQL Schema language. - export { printSchema, printIntrospectionSchema } from 'graphql/utilities/schemaPrinter'; + export { printSchema, printType, printIntrospectionSchema } from 'graphql/utilities/schemaPrinter'; // Create a GraphQLType from a GraphQL language AST. export { typeFromAST } from 'graphql/utilities/typeFromAST'; @@ -2150,6 +2220,10 @@ declare module "graphql/utilities/index" { // Asserts that a string is a valid GraphQL name export { assertValidName } from 'graphql/utilities/assertValidName'; + + // Compares two GraphQLSchemas and detects breaking changes. + export { findBreakingChanges } from 'graphql/utilities/findBreakingChanges'; + export { BreakingChange } from 'graphql/utilities/findBreakingChanges'; } declare module "graphql/utilities/assertValidName" { @@ -2159,14 +2233,14 @@ declare module "graphql/utilities/assertValidName" { declare module "graphql/utilities/astFromValue" { import { - Value, - //IntValue, - //FloatValue, - //StringValue, - //BooleanValue, - //EnumValue, - //ListValue, - //ObjectValue, + ValueNode, + //IntValueNode, + //FloatValueNode, + //StringValueNode, + //BooleanValueNode, + //EnumValueNode, + //ListValueNode, + //ObjectValueNode, } from 'graphql/language/ast'; import { GraphQLInputType } from 'graphql/type/definition'; @@ -2190,11 +2264,11 @@ declare module "graphql/utilities/astFromValue" { export function astFromValue( value: any, type: GraphQLInputType - ): Value // Warning: there is a code in bottom: throw new TypeError + ): ValueNode // Warning: there is a code in bottom: throw new TypeError } declare module "graphql/utilities/buildASTSchema" { - import { Document } from 'graphql/language/ast'; + import { DocumentNode, Location } from 'graphql/language/ast'; import { Source } from 'graphql/language/source'; import { GraphQLSchema } from 'graphql/type/schema'; @@ -2208,7 +2282,7 @@ declare module "graphql/utilities/buildASTSchema" { * Given that AST it constructs a GraphQLSchema. The resulting schema * has no resolve methods, so execution will use default resolvers. */ - function buildASTSchema(ast: Document): GraphQLSchema; + function buildASTSchema(ast: DocumentNode): GraphQLSchema; /** * Given an ast node, returns its string description based on a contiguous @@ -2253,16 +2327,17 @@ declare module "graphql/utilities/buildClientSchema" { } declare module "graphql/utilities/concatAST" { - import { Document } from 'graphql/language/ast'; + import { DocumentNode } from 'graphql/language/ast'; /** * Provided a collection of ASTs, presumably each from different files, * concatenate the ASTs together into batched AST, useful for validating many * GraphQL source files which together represent one conceptual application. */ - function concatAST(asts: Array): Document; + function concatAST(asts: Array): DocumentNode; } declare module "graphql/utilities/extendSchema" { + import { DocumentNode } from 'graphql/language/ast'; import { GraphQLSchema } from 'graphql/type/schema'; /** @@ -2279,12 +2354,102 @@ declare module "graphql/utilities/extendSchema" { */ function extendSchema( schema: GraphQLSchema, - documentAST: Document + documentAST: DocumentNode ): GraphQLSchema; } +declare module "graphql/utilities/findBreakingChanges" { + import { + getNamedType, + GraphQLScalarType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLObjectType, + GraphQLUnionType, + GraphQLNamedType, + } from 'graphql/type/definition'; + import { GraphQLSchema } from 'graphql/type/schema'; + + export const BreakingChangeType: { + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', + FIELD_REMOVED: 'FIELD_REMOVED', + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', + TYPE_REMOVED: 'TYPE_REMOVED', + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + }; + + type BreakingChangeKey = 'FIELD_CHANGED_KIND' + | 'FIELD_REMOVED' + | 'TYPE_CHANGED_KIND' + | 'TYPE_REMOVED' + | 'TYPE_REMOVED_FROM_UNION' + | 'VALUE_REMOVED_FROM_ENUM'; + + export type BreakingChange = { + type: BreakingChangeKey; + description: string; + }; + + /** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ + export function findBreakingChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ + export function findRemovedTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ + export function findTypesThatChangedKind( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to the fields on a type. This includes if + * a field has been removed from a type or if a field has changed type. + */ + export function findFieldsThatChangedType( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array; + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ + export function findTypesRemovedFromUnions( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array; + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ + export function findValuesRemovedFromEnums( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array; +} + declare module "graphql/utilities/getOperationAST" { - import { Document, OperationDefinition } from 'graphql/language/ast'; + import { DocumentNode, OperationDefinitionNode } from 'graphql/language/ast'; /** * Returns an operation AST given a document AST and optionally an operation @@ -2292,9 +2457,9 @@ declare module "graphql/utilities/getOperationAST" { * provided in the document. */ export function getOperationAST( - documentAST: Document, + documentAST: DocumentNode, operationName: string - ): OperationDefinition; + ): OperationDefinitionNode; } declare module "graphql/utilities/introspectionQuery" { @@ -2525,7 +2690,7 @@ declare module "graphql/utilities/isValidJSValue" { } declare module "graphql/utilities/isValidLiteralValue" { - import { Value } from 'graphql/language/ast'; + import { ValueNode } from 'graphql/language/ast'; import { GraphQLInputType } from 'graphql/type/definition'; /** @@ -2537,27 +2702,30 @@ declare module "graphql/utilities/isValidLiteralValue" { */ function isValidLiteralValue( type: GraphQLInputType, - valueAST: Value + valueNode: ValueNode ): Array } declare module "graphql/utilities/schemaPrinter" { import { GraphQLSchema } from 'graphql/type/schema'; + import { GraphQLType } from 'graphql/type/definition'; function printSchema(schema: GraphQLSchema): string; function printIntrospectionSchema(schema: GraphQLSchema): string; + + function printType(type: GraphQLType): string } declare module "graphql/utilities/separateOperations" { import { - Document, - OperationDefinition, + DocumentNode, + OperationDefinitionNode, } from 'graphql/language/ast'; function separateOperations( - documentAST: Document - ): { [operationName: string]: Document } + documentAST: DocumentNode + ): { [operationName: string]: DocumentNode } } declare module "graphql/utilities/typeComparators" { @@ -2602,13 +2770,13 @@ declare module "graphql/utilities/typeComparators" { } declare module "graphql/utilities/typeFromAST" { - import { Type } from 'graphql/language/ast'; + import { TypeNode } from 'graphql/language/ast'; import { GraphQLType, GraphQLNullableType } from 'graphql/type/definition'; import { GraphQLSchema } from 'graphql/type/schema'; function typeFromAST( schema: GraphQLSchema, - inputTypeAST: Type + typeNode: TypeNode ): GraphQLType } @@ -2619,14 +2787,14 @@ declare module "graphql/utilities/TypeInfo" { declare module "graphql/utilities/valueFromAST" { import { GraphQLInputType } from 'graphql/type/definition'; import { - Value, - Variable, - ListValue, - ObjectValue + ValueNode, + VariableNode, + ListValueNode, + ObjectValueNode } from 'graphql/language/ast'; function valueFromAST( - valueAST: Value, + valueNode: ValueNode, type: GraphQLInputType, variables?: { [key: string]: any diff --git a/highcharts/index.d.ts b/highcharts/index.d.ts index 4c71b46e73..626ff59482 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/howler/howler-tests.ts b/howler/howler-tests.ts index bdd3a575bd..7b47b73abb 100644 --- a/howler/howler-tests.ts +++ b/howler/howler-tests.ts @@ -1,19 +1,13 @@ -/** - * howler-tests.ts - * Created by xperiments on 02/09/14. - */ - import * as howler from "howler"; -Howler.codecs('ogg'); -Howler.iOSAutoEnable = true; var sound = new Howl({ - urls: ['sound.mp3'] -}).play(); + src: ['sound.mp3'] +}); +sound.play(); var sound = new Howl({ - urls: ['sound.mp3', 'sound.ogg', 'sound.wav'], + src: ['sound.webm', 'sound.mp3', 'sound.wav'], autoplay: true, loop: true, volume: 0.5, @@ -23,7 +17,7 @@ var sound = new Howl({ }); var sound = new Howl({ - urls: ['sounds.mp3', 'sounds.ogg'], + src: ['sounds.webm', 'sounds.mp3'], sprite: { blast: [0, 1000], laser: [2000, 3000], @@ -31,5 +25,32 @@ var sound = new Howl({ } }); -// shoot the laser! +// Shoot the laser! sound.play('laser'); + +var sound = new Howl({ + src: ['sound.webm', 'sound.mp3'] +}); + +// Clear listener after first call. +sound.once('load', function(){ + sound.play(); +}); + +// Fires when the sound finishes playing. +sound.on('end', function(){ + console.log('Finished!'); +}); + +var sound = new Howl({ + src: ['sound.webm', 'sound.mp3'] +}); + +// Play returns a uniqe Sound ID that can be passed +// into any method on Howl to control that specific sound. +var id1 = sound.play(); +var id2 = sound.play(); + +// Fade out the first sound and speed up the second. +sound.fade(1, 0, 1000, id1); +sound.rate(1.5, id2); diff --git a/howler/index.d.ts b/howler/index.d.ts index cdb95ce44f..1b6604b1aa 100644 --- a/howler/index.d.ts +++ b/howler/index.d.ts @@ -1,73 +1,107 @@ -// Type definitions for howler.js v1.1.29 +// Type definitions for howler.js v2.0.0 // Project: https://github.com/goldfire/howler.js -// Definitions by: Pedro Casaubon +// Definitions by: Pedro Casaubon , Todd Dukart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class HowlerGlobal { - mute(muted: boolean): HowlerGlobal; +interface HowlerGlobal { + mute(muted: boolean): void; volume(): number; - volume(volume: number): HowlerGlobal; - codecs(extension: string): boolean; - iOSAutoEnable: boolean; + volume(volume: number): this; + codecs(ext: string): boolean; + unload(): void; + usingWebAudio: boolean; + noAudio: boolean; + mobileAudioEnable: boolean; + autoSuspend: boolean; + ctx: AudioContext; + masterGain: GainNode; } -declare var Howler: HowlerGlobal; +declare let Howler: HowlerGlobal; interface IHowlSoundSpriteDefinition { - [name: string]: number[]; + [name: string]: [number, number]|[number, number, boolean] } -declare type HowlPos3d = [number, number, number]|[number, number, number, number]; - interface IHowlProperties { - autoplay?: boolean; - buffer?: boolean; - duration?: number; - format?: string; - loop?: boolean; - sprite?: IHowlSoundSpriteDefinition; - src?: string; - pos3d?: HowlPos3d; + src: string|string[]; volume?: number; - urls?: string[]; + html5?: boolean; + loop?: boolean; + preload?: boolean; + autoplay?: boolean; + mute?: boolean; + sprite?: IHowlSoundSpriteDefinition; rate?: number; - model?: 'equalpower'|'HRTF'; - onend?: Function; - onload?: Function; - onloaderror?: Function; - onpause?: Function; - onplay?: Function; + pool?: number; + format?: string[] | string; + onload?: () => void; + onloaderror?: (soundId: number, error: any) => void; + onplay?: (soundId: number) => void; + onend?: (soundId: number) => void; + onpause?: (soundId: number) => void; + onstop?: (soundId: number) => void; + onmute?: (soundId: number) => void; + onvolume?: (soundId: number) => void; + onrate?: (soundId: number) => void; + onseek?: (soundId: number) => void; + onfade?: (soundId: number) => void; } interface Howl { - autoplay: Boolean; - buffer: Boolean; - format: string; - rate: number; - model: string; - onend: Function; - onload: Function; - onloaderror: Function; - onpause: Function; - onplay: Function; - load(): Howl; - play(sprite?: string, callback?: (soundId: string) => void): Howl; - play(callback?: (soundId: string) => void): Howl; - pause(soundId?: string): Howl; - stop(soundId?: string): Howl; - mute(muted?: boolean, soundId?: string): Howl; - fade(from: number, to: number, duration: number, callback?: Function, soundId?: string): Howl; - loop(): boolean; - loop(loop: boolean): Howl; - pos(position?: number, soundId?: string): number; - pos3d(x: number, y: number, z: number, soundId?: string): any; - sprite(definition?: IHowlSoundSpriteDefinition): IHowlSoundSpriteDefinition; + play(spriteOrId?: string|number): number; // .play() is not chainable; the other methods are + pause(id?: number): this; + stop(id?: number): this; + + mute(): boolean; + mute(muted: boolean, id?: number): this; + volume(): number; - volume(volume?: number, soundId?: string): Howl; - urls(): string[]; - urls(urls: string[]): Howl; - on(event: string, listener?: Function): Howl; - off(event: string, listener?: Function): Howl; + volume(idOrSetVolume: number): this | number; + volume(volume: number, id: number): this; + + fade(from: number, to: number, duration: number, id?: number): this; + + rate(): number; + rate(idOrSetRate: number): this | number; + rate(rate: number, id: number): this; + + seek(seek?: number, id?: number): this; + loop(loop?: boolean, id?: number): this; + playing(id?: number): boolean; + duration(id?: number): number; + + + on(event: 'load', callback: () => void, id?: number): this; + on(event: 'loaderror', callback: (soundId: number, error: any) => void, id?: number): this; + on(event: 'play', callback: (soundId: number) => void, id?: number): this; + on(event: 'end', callback: (soundId: number) => void, id?: number): this; + on(event: 'pause', callback: (soundId: number) => void, id?: number): this; + on(event: 'stop', callback: (soundId: number) => void, id?: number): this; + on(event: 'mute', callback: (soundId: number) => void, id?: number): this; + on(event: 'volume', callback: (soundId: number) => void, id?: number): this; + on(event: 'rate', callback: (soundId: number) => void, id?: number): this; + on(event: 'seek', callback: (soundId: number) => void, id?: number): this; + on(event: 'fade', callback: (soundId: number) => void, id?: number): this; + on(event: string, callback: Function, id?: number): this; + + once(event: 'load', callback: () => void, id?: number): this; + once(event: 'loaderror', callback: (soundId: number, error: any) => void, id?: number): this; + once(event: 'play', callback: (soundId: number) => void, id?: number): this; + once(event: 'end', callback: (soundId: number) => void, id?: number): this; + once(event: 'pause', callback: (soundId: number) => void, id?: number): this; + once(event: 'stop', callback: (soundId: number) => void, id?: number): this; + once(event: 'mute', callback: (soundId: number) => void, id?: number): this; + once(event: 'volume', callback: (soundId: number) => void, id?: number): this; + once(event: 'rate', callback: (soundId: number) => void, id?: number): this; + once(event: 'seek', callback: (soundId: number) => void, id?: number): this; + once(event: 'fade', callback: (soundId: number) => void, id?: number): this; + once(event: string, callback: Function, id?: number): this; + + off(event: string, callback?: Function, id?: number): this; + + state(): 'unloaded' | 'loading' | 'loaded'; + load(): void; unload(): void; } diff --git a/humanparser/humanparser-tests.ts b/humanparser/humanparser-tests.ts new file mode 100644 index 0000000000..0abe741554 --- /dev/null +++ b/humanparser/humanparser-tests.ts @@ -0,0 +1,19 @@ +import human = require('humanparser'); + +let parsedName = human.parseName("Mr. William R. Hearst, III"); +parsedName.firstName; +parsedName.lastName; +parsedName.fullName; +parsedName.suffix; +parsedName.middleName; +parsedName.salutation; + +let parsedAddress = human.parseAddress("123 Happy Street, Honolulu, HI 65780"); +parsedAddress.address; +parsedAddress.state; +parsedAddress.fullAddress; +parsedAddress.zip; +parsedAddress.city; + +let parsedFullName = human.getFullestName("John & Peggy Sue"); +parsedFullName.fullName; diff --git a/humanparser/index.d.ts b/humanparser/index.d.ts new file mode 100644 index 0000000000..37209a60f3 --- /dev/null +++ b/humanparser/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for humanparser 1.1.1 +// Project: https://github.com/chovy/humanparser +// Definitions by: Michał Podeszwa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace humanparser { + interface NameOutput { + firstName: string; + lastName: string; + fullName: string; + suffix?: string; + middleName?: string; + salutation?: string; + } + + interface FullerNameOutput { + fullName: string; + } + + interface AddressOutput { + address: string; + state: string; + fullAddress: string; + zip: string; + city: string; + } + + interface HumanparserStatic { + parseName (name: string): NameOutput; + getFullestName (name: string): FullerNameOutput; + parseAddress (address: string): AddressOutput; + } + +} + +declare const humanparser: humanparser.HumanparserStatic; +export = humanparser; diff --git a/humanparser/tsconfig.json b/humanparser/tsconfig.json new file mode 100644 index 0000000000..17b129eba5 --- /dev/null +++ b/humanparser/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", + "humanparser-tests.ts" + ] +} diff --git a/immutable/index.d.ts b/immutable/index.d.ts index cbc27ab300..9cadb3c29e 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 244b1ee003..b60dfef00d 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 180b3ef5ba..abf8ed4f82 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 ca2b2808cc..87497e90c2 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 d0660193f6..dc0260cebb 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 e774ad1fb5..4b81f6282c 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 c192f49dd1..2f803cdf7d 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 759be529ad..d50db6eedd 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 b331352ce3..81c5027619 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 28d957ec50..fae4892c55 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 0000000000..be62f3b3da --- /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 0000000000..d2127cbaa0 --- /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 0000000000..0f7906596e --- /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 2be61cf00e..bdaba2cde8 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 89d68de63e..347cc066f0 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 12afaad5e2..d445be74ad 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 56055d0a22..acd0f5ae16 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/keymirror/index.d.ts b/keymirror/index.d.ts new file mode 100644 index 0000000000..1f2b6c01da --- /dev/null +++ b/keymirror/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for keymirror 0.1.1 +// Project: https://github.com/STRML/keyMirror +// Definitions by: Johannes Fahrenkrug +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function KeyMirror(obj: {}): { [key: string]: string }; +export = KeyMirror; diff --git a/keymirror/keymirror-tests.ts b/keymirror/keymirror-tests.ts new file mode 100644 index 0000000000..ace29f9947 --- /dev/null +++ b/keymirror/keymirror-tests.ts @@ -0,0 +1,3 @@ +import keyMirror = require('keymirror'); + +keyMirror({key1: null, key2: null}); diff --git a/keymirror/tsconfig.json b/keymirror/tsconfig.json new file mode 100644 index 0000000000..ce57da7581 --- /dev/null +++ b/keymirror/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", + "keymirror-tests.ts" + ] +} diff --git a/koa/index.d.ts b/koa/index.d.ts index 6cdb0cbcd1..7fa9dd1cc9 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 b3bf036df7..1b261fdf44 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 d43a2303da..d16be0bc1f 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/linqsharp/index.d.ts b/linqsharp/index.d.ts deleted file mode 100644 index 742698ed86..0000000000 --- a/linqsharp/index.d.ts +++ /dev/null @@ -1,498 +0,0 @@ -// Type definitions for linqsharp -// Project: https://www.npmjs.com/package/linqsharp -// Definitions by: Bruno Leonardo Michels -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// JSDoc: Extracted and adapted from .NET source code. - -/** - * LinqSharp module defines a helper class with - * .NET's Linq methods. - * - * @module linqsharp - */ - -export declare namespace LinqSharp { - /** - * Defines methods to support the comparison of objects for equality. - * - * {T} The type of objects to compare. - */ - export interface IEqualityComparer { - Equals(x: T, y: T): boolean; - GetHashCode(obj: T): number; - } - - /** - * Represents a collection of objects that have a common key. - * - * {TKey} The type of the key. - * {T} The type of the values. - */ - export interface IGrouping { - Key: TKey; - Elements: T[]; - } - - /** - * Gets the HashCode of the object. - * - * @param e Object to compute hash. - * @returns A computed HashCode for the object. - */ - export function GetHashCode(e: any): any; - - /** - * Transforms a object into a string replacing circular - * references by reference tokens. - * - * @param obj Object to convert to string. - * @returns String representation of the object. - */ - export function StringifyNonCircular(obj: any): string; -} - -/** - * Wrapper class for an array that provides Linq functionallity. - * - * @class Linq - */ -declare class Linq { - /** {T[]} Internal array reference. */ - private a: T[]; - - /** - * Creates a new instance holding an array of . - * @constructor - * - * @param {Array} a Array. - */ - constructor(a?: T[]); - - /** - * Applies an accumulator function over a sequence. - * - * @param func An accumulator function to be - * invoked on each element. - * @param {T} [initialValue] The initial accumulator value. - * - * @throws Error if array is empty. - * - * @returns {T} The final accumulator value. - */ - Aggregate(func: (previous: T, next: T) => TResult, initialValue?: T): T; - - /** - * Determines whether all elements of a sequence satisfy a condition. - * - * @param predicate A function to test each element for a condition. - * - * @returns true if every element of the source sequence passes the test in the specified - * predicate, or if the sequence is empty; otherwise, false. - */ - All(predicate: (value: T) => boolean): boolean; - - /** - * Determines whether a sequence contains any elements. - * - * @param [predicate] A function to test each element for a condition. - * - * @returns true if any elements in the source sequence pass the test in the specified predicate; - * otherwise, false. If no predicate is specified return true if the source sequence contains any elements; - * otherwise, false. - */ - Any(predicate?: (value: T) => boolean): boolean; - - /** - * Computes the average of a sequence of {number} values. - * - * @param [selector] A transform function to apply to each element. - * - * @returns The average of the sequence of values. - */ - Average(selector?: (value: T) => number): number; - - /** - * Concatenates two sequences. - * - * @param array The sequence to concatenate to the first sequence. - * - * @returns An array that contains the concatenated elements of the two input sequences. - */ - Concat(array: T[]): Linq; - - /** - * Determines whether a sequence contains a specified element by using a specified comparer. - * - * @param value The value to locate in the sequence. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns true if the source sequence contains an element that has the specified value; - * otherwise, false. - */ - Contains(value: T, comparer?: LinqSharp.IEqualityComparer): boolean; - - /** - * Returns a number that represents how many elements in the specified sequence satisfy a condition. - * - * @param [selector] A function to test each element for a condition. - * - * @returns A number that represents how many elements in the sequence satisfy the condition - * in the predicate function. - */ - Count(selector?: (value: T) => boolean): number; - - /** - * Returns distinct elements from a sequence by using a specified IEqualityComparer - * to compare values. - * - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns An array that contains distinct elements from the source sequence. - */ - Distinct(comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Returns distinct elements from a sequence by using a specified IEqualityComparer - * to compare values. - * - * @param selector A function to test each element for a condition. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns An array that contains distinct elements from the source sequence. - */ - DistinctBy(selector: (e: T) => U, comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Returns the element at a specified index in a sequence. - * - * @param index The zero-based index of the element to retrieve. - * - * @throws index is less than 0 or greater than or equal to the number of elements in source. - * - * @returns The element at the specified position in the source sequence. - */ - ElementAt(index: number): T; - - /** - * Returns the element at a specified index in a sequence or a default value if - * the index is out of range. - * - * @param index The zero-based index of the element to retrieve. - * @param defaultValue A default value if no element is found. - * - * @returns defaultValue if the index is outside the bounds of the source sequence; - * otherwise, the element at the specified position in the source sequence. - */ - ElementAtOrDefault(index: number, defaultValue: T): T; - - /** - * Produces the set difference of two sequences by using the specified IEqualityComparer - * to compare values. - * - * @param except An array whose elements that also occur in the first sequence will cause - * those elements to be removed from the returned sequence. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns A sequence that contains the set difference of the elements of two sequences. - */ - Except(except: T[], comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Returns the first element in a sequence that satisfies a specified condition. - * - * @param [selector] A function to test each element for a condition. - * - * @throws No element satisfies the condition in predicate.-or-The source sequence is empty. - * - * @returns The first element in the sequence that passes the test in the specified predicate function. - */ - First(selector?: (e: T) => boolean): T; - - /** - * Returns the first element of the sequence that satisfies a condition or a default - * value if no such element is found. - * - * @param [selector] A function to test each element for a condition. - * @param [defaultValue] A default value to return if no element is found. - * - * @returns defaultValue if source is empty or if no element passes the test specified by predicate; - * otherwise, the first element in source that passes the test specified by predicate. - */ - FirstOrDefault(selector?: (e: T) => boolean, defaultValue?: T): T; - - /** - * Performs the specified action on each element of the array. - * - * @param callback The function delegate to perform on each element of the array. - */ - ForEach(callback: (e: T, index: number) => any): void; - - /** - * Groups the elements of a sequence according to a specified key selector function. - * - * @param keySelector A function to extract the key for each element. - * @param [elementSelector] A function to create a result value from each group. - * @param [comparer] An IEqualityComparer to compare keys with. - * - * @returns A collection of elements of type TResult where each element represents a projection - * over a group and its key. - */ - GroupBy(keySelector: (e: T) => TKey, elementSelector?: (e: T) => TElement, comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Searches for the specified object and returns the zero-based index of the first - * occurrence within the entire array. - * - * @param e The object to locate in the array. - * @param [comparer] An IEqualityComparer to compare elements with. - * - * @returns The zero-based index of the first occurrence of item within the entire array, if found; - * otherwise, –1. - */ - IndexOf(e: T, comparer?: LinqSharp.IEqualityComparer): number; - - /** - * Produces the set intersection of two sequences by using the specified IEqualityComparer - * to compare values. - * - * @param array An array whose distinct elements that also appear in the first sequence will be returned. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns A sequence that contains the elements that form the set intersection of two sequences. - */ - Intersect(array: T[], comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Correlates the elements of two sequences based on matching keys. A specified IEqualityComparer is used to compare keys. - * - * @param array The sequence to join to the first sequence. - * @param outerKeySelector A function to extract the join key from each element of the first sequence. - * @param innerKeySelector A function to extract the join key from each element of the second sequence. - * @param resultSelector A function to create a result element from two matching elements. - * @param [comparer] An IEqualityComparer to hash and compare keys. - * - * @returns An array that has elements of type TResult that are obtained by performing an inner join on two sequences. - */ - Join(array: TInner[], outerKeySelector: (e: T) => TKey, innerKeySelector: (e: TInner) => TKey, resultSelector: (outer: T, inner: TInner) => TResult, comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Returns the last element of a sequence that satisfies a specified condition. - * - * @param [predicate] A function to test each element for a condition. - * - * @throws No element satisfies the condition in predicate.-or-The source sequence is empty. - * - * @returns The last element in the sequence that passes the test in the specified predicate function. - */ - Last(predicate?: (e: T) => boolean): T; - - /** - * Returns the last element of a sequence that satisfies a condition or a default - * value if no such element is found. - * - * @param [predicate] A function to test each element for a condition. - * @param [defaultValue] A default value to return if no element is found. - * - * @returns defaultValue if the sequence is empty or if no elements pass the test in - * the predicate function; otherwise, the last element that passes the test in the - * predicate function. - */ - LastOrDefault(predicate?: (e: T) => boolean, defaultValue?: T): T; - - /** - * Returns the maximum value in a sequence of System.Double values. - * - * @param [selector] A transform function to apply to each element. - * - * @returns The maximum value in the sequence. - */ - Max(): T; - Max(selector?: (e: T) => TResult): TResult; - - /** - * Returns the minimum value in a sequence of System.Int64 values. - * - * @param [selector] A transform function to apply to each element. - * - * @returns The minimum value in the sequence. - */ - Min(): T; - Min(selector?: (e: T) => TResult): TResult; - - /** - * Sorts the elements of a sequence in ascending order according to a key. - * - * @param keySelector A function to extract a key from an element. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns An array whose elements are sorted according to a key. - */ - OrderBy(keySelector: (e: T) => TKey, comparer?: (a: TKey, b: TKey) => number): Linq; - - /** - * Sorts the elements of a sequence in descending order according to a key. - * - * @param keySelector A function to extract a key from an element. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns An array whose elements are sorted in descending order according to a key. - */ - OrderByDescending(keySelector: (e: T) => TKey, comparer?: (a: TKey, b: TKey) => number): Linq; - - /** - * Inverts the order of the elements in a sequence. - * - * @returns A sequence whose elements correspond to those of the input sequence in reverse order. - */ - Reverse(): Linq; - - /** - * Projects each element of a sequence into a new form. - * - * @param selector A transform function to apply to each element. - * - * @returns An array whose elements are the result of invoking the transform function on each element of source. - */ - Select(selector: (e: T, i?: number) => TResult): Linq; - - /** - * Projects each element of a sequence to an array flattens the resulting sequences into one sequence, - * and invokes a result selector function on each element therein. - * - * @param selector A transform function to apply to each element of the input sequence. - * @param [resultSelector] A transform function to apply to each element of the intermediate sequence. - * - * @returns An array whose elements are the result of invoking the one-to-many transform function - * selector on each element of source and then mapping each of those sequence elements and - * their corresponding source element to a result element. - */ - SelectMany(selector: (e: T) => T[], resultSelector?: (e: T) => TResult): Linq; - - /** - * Determines whether two sequences are equal by comparing their elements by using - * a specified IEqualityComparer. - * - * @param second An array to compare to the first sequence. - * @param [comparer] An equality comparer to compare values. - * - * @returns true if the two source sequences are of equal length and their corresponding - * elements compare equal according to comparer; otherwise, false. - */ - SequenceEqual(second: T[], comparer?: (a: T, b: T) => boolean): boolean; - - /** - * Returns the only element of a sequence that satisfies a specified condition, - * and throws an exception if more than one such element exists. - * - * @param [predicate] A function to test an element for a condition. - * - * @returns The single element of the input sequence that satisfies a condition. - */ - Single(predicate?: (e: T) => boolean): T; - - /** - * Returns the only element of a sequence that satisfies a specified condition or - * a default value if no such element exists; this method throws an exception if - * more than one element satisfies the condition. - * - * @param [predicate] A function to test an element for a condition. - * @param [defaultValue] A default value if no element is found. - * - * @returns The single element of the input sequence that satisfies the condition, - * or defaultValue if no such element is found. - */ - SingleOrDefault(predicate?: (e: T) => boolean, defaultValue?: T): T; - - /** - * Bypasses a specified number of elements in a sequence and then returns the remaining - * elements. - * - * @param count The number of elements to skip before returning the remaining elements. - * - * @returns An array that contains the elements that occur - * after the specified index in the input sequence. - */ - Skip(count: number): Linq; - - /** - * Bypasses elements in a sequence as long as a specified condition is true and - * then returns the remaining elements. - * - * @param predicate A function to test an element for a condition. - * - * @returns An array that contains the elements from the - * input sequence starting at the first element in the linear series that does not - * pass the test specified by predicate. - */ - SkipWhile(predicate: (e: T) => boolean): Linq; - - /** - * Computes the sum of a sequence values. - * - * @param [selector] A transform function to apply to each element. - * - * @returns The sum of the values in the sequence. - */ - Sum(selector?: (value: T) => number): number; - - /** - * Returns a specified number of contiguous elements from the start of a sequence. - * - * @param count The number of elements to skip before returning the remaining elements. - * - * @returns An array that contains the specified number of elements from the start - * of the input sequence. - */ - Take(count: number): Linq; - - /** - * Returns elements from a sequence as long as a specified condition is true. - * - * @param predicate A function to test an element for a condition. - * - * @returns An array that contains the elements from the - * input sequence that occur before the element at which the test no longer passes. - */ - TakeWhile(predicate: (e: T) => boolean): Linq; - - /** - * Produces the set union of two sequences by using a specified IEqualityComparer. - * - * @param second An array whose distinct elements form the second set for the union. - * @param [comparer] An equality comparer to compare values. - * - * @returns An array that contains the elements from both - * input sequences, excluding duplicates. - */ - Union(second: T[], comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Filters a sequence of values based on a predicate. - * - * @param selector A transform function to apply to each element. - * - * @returns An array that contains elements from the input sequence - * that satisfy the condition. - */ - Where(selector: (value: T) => boolean): Linq; - - /** - * Applies a specified function to the corresponding elements of two sequences, - * producing a sequence of the results. - * - * @param array The second sequence to merge. - * @param resultSelector A function that specifies how to merge the elements from the two sequences. - * - * @returns An array that contains merged elements of two input sequences. - */ - Zip(array: TInner[], resultSelector: (o: T, i: TInner) => TResult): Linq; - - /** - * Retrieves the internal array. - * - * @returns Internal array. - */ - ToArray(): T[]; -} -export default Linq; diff --git a/linqsharp/linqsharp-tests.ts b/linqsharp/linqsharp-tests.ts deleted file mode 100644 index 1fda5716b8..0000000000 --- a/linqsharp/linqsharp-tests.ts +++ /dev/null @@ -1,91 +0,0 @@ - -import Linq, { LinqSharp } from "linqsharp"; - -var linq: Linq = new Linq([0, 1, 2, 3]); - -var linqResult: Linq; -var linqAny: Linq; -var arrayResult: number[]; - -var numberResult: number; -var boolResult: boolean; - -var comparer: LinqSharp.IEqualityComparer = { - Equals: (x: number, y: number): boolean => - { - return x === y; - }, - GetHashCode: (obj: number): number => - { - return obj.valueOf(); - } -}; -var comparer2: (o: number, i: number) => number; -var comparer3: (o: number, i: number) => boolean; - -numberResult = linq.Aggregate((prev: number, next: number) => { return prev + next; }); -boolResult = linq.All((value: number) => value == 0); -boolResult = linq.Any(); -boolResult = linq.Any((value: number) => value == 0); -numberResult = linq.Average(); -numberResult = linq.Average((value: number) => value); -linqResult = linq.Concat([4, 5, 6]); -boolResult = linq.Contains(0); -boolResult = linq.Contains(0, comparer); -numberResult = linq.Count(); -numberResult = linq.Count((value: number) => value == 0); -linqResult = linq.Distinct(); -linqResult = linq.Distinct(comparer); -linqResult = linq.DistinctBy((value: number) => value); -numberResult = linq.ElementAt(0); -numberResult = linq.ElementAtOrDefault(0, 1); -linqResult = linq.Except([2]); -linqResult = linq.Except([2], comparer); -numberResult = linq.First(); -numberResult = linq.First((value: number) => value == 0); -numberResult = linq.FirstOrDefault(); -numberResult = linq.FirstOrDefault((value: number) => value == 0); -linq.ForEach((value: number, index: number) => { }); -linqAny = linq.GroupBy((value: number) => value % 2); -linqAny = linq.GroupBy((value: number) => value % 2, (value: number) => value * 2); -linqAny = linq.GroupBy((value: number) => value % 2, (value: number) => value * 2, comparer); -numberResult = linq.IndexOf(0); -numberResult = linq.IndexOf(0, comparer); -linqResult = linq.Intersect([0]); -linqResult = linq.Intersect([0], comparer); -linqResult = linq.Join([0], (outer: number) => outer, (inner: number) => inner, (outer: number, inner: number) => outer + inner); -linqResult = linq.Join([0], (outer: number) => outer, (inner: number) => inner, (outer: number, inner: number) => outer + inner, comparer); -numberResult = linq.Last(); -numberResult = linq.Last((value: number) => value == 0); -numberResult = linq.LastOrDefault(); -numberResult = linq.LastOrDefault((value: number) => value == 0); -numberResult = linq.Max(); -numberResult = linq.Max((value: number) => value); -numberResult = linq.Min(); -numberResult = linq.Min((value: number) => value); -linqResult = linq.OrderBy((value: number) => value); -linqResult = linq.OrderBy((value: number) => value, comparer2); -linqResult = linq.OrderByDescending((value: number) => value); -linqResult = linq.OrderByDescending((value: number) => value, comparer2); -linqResult = linq.Reverse(); -linqResult = linq.Select((value: number) => value); -linqResult = linq.Select((value: number, index: number) => value + index); -linqResult = linq.SelectMany((value: number) => [ value ]); -linqResult = linq.SelectMany((value: number) => [ value ], (value: number) => value); -boolResult = linq.SequenceEqual([0]); -boolResult = linq.SequenceEqual([0], comparer3); -numberResult = linq.Single(); -numberResult = linq.Single((value: number) => value == 0); -numberResult = linq.SingleOrDefault(); -numberResult = linq.SingleOrDefault((value: number) => value == 0); -linqResult = linq.Skip(0); -linqResult = linq.SkipWhile((value: number) => value < 2); -numberResult = linq.Sum(); -numberResult = linq.Sum((value: number) => value * 2); -linqResult = linq.Take(2); -linqResult = linq.TakeWhile((value: number) => value < 2); -arrayResult = linq.ToArray(); -linqResult = linq.Union([0]); -linqResult = linq.Union([0], comparer); -linqResult = linq.Where((value: number) => value > 0); -linqResult = linq.Zip([0], (outer: number, inner: number) => outer + inner); \ No newline at end of file diff --git a/lodash/index.d.ts b/lodash/index.d.ts index e1074a4c97..f8b14bb3af 100644 --- a/lodash/index.d.ts +++ b/lodash/index.d.ts @@ -10986,7 +10986,7 @@ declare module _ { * @param value The value to inspect. * @return Returns the cast array. */ - castArray(value: T): T[]; + castArray(value?: T | T[]): T[]; } interface LoDashImplicitWrapper { diff --git a/lowlight/index.d.ts b/lowlight/index.d.ts new file mode 100644 index 0000000000..589c9b50fd --- /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 0000000000..b9bc0122ae --- /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 0000000000..6aa905fcab --- /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/maker.js/index.d.ts b/maker.js/index.d.ts index d23fe37c3f..7cf55d0448 100644 --- a/maker.js/index.d.ts +++ b/maker.js/index.d.ts @@ -5,7 +5,7 @@ /// /// -/// +/// /** * Root module for Maker.js. @@ -2173,6 +2173,6 @@ declare namespace MakerJs.models { declare namespace MakerJs.models { class Text implements IModel { models: IModelMap; - constructor(font: opentypejs.Font, text: string, fontSize: number, combine?: boolean); + constructor(font: opentype.Font, text: string, fontSize: number, combine?: boolean); } } diff --git a/maker.js/makerjs-tests.ts b/maker.js/makerjs-tests.ts index 534ef9eed7..cc7cc0804d 100644 --- a/maker.js/makerjs-tests.ts +++ b/maker.js/makerjs-tests.ts @@ -1,7 +1,7 @@ function test() { - + var makerjs: typeof MakerJs; var p1: MakerJs.IPoint = [0, 0]; @@ -9,7 +9,7 @@ function test() { var paths = testPaths(); var models = testModels(); var model: MakerJs.IModel = models[0]; - + function testRoot() { makerjs.cloneObject({}); makerjs.createRouteKey([]); @@ -29,7 +29,7 @@ function test() { makerjs.unitType.Millimeter; new makerjs.Collector(); } - + function testAngle() { makerjs.angle.mirror(45, true, false); makerjs.angle.noRevolutions(90); @@ -49,22 +49,22 @@ function test() { makerjs.exporter.toOpenJsCad(model); makerjs.exporter.toPDF({} as PDFKit.PDFDocument, model); makerjs.exporter.toSTL(model); - makerjs.exporter.toSVG(model, - { - annotate: true, - fontSize: '', - origin: [], - scale: 9.9, - stroke: '', - strokeWidth: '', - svgAttrs: {}, - units: '', + makerjs.exporter.toSVG(model, + { + annotate: true, + fontSize: '', + origin: [], + scale: 9.9, + stroke: '', + strokeWidth: '', + svgAttrs: {}, + units: '', useSvgPathOnly: false, viewBox: false }); makerjs.exporter.tryGetModelUnits(model); } - + function testImporter() { makerjs.importer.fromSVGPathData(''); makerjs.importer.parseNumericList(''); @@ -77,7 +77,7 @@ function test() { ({}).metaParameters; ({}).notes; } - + function testMeasure() { makerjs.measure.increase(mp, mm); makerjs.measure.isPointEqual(p1, p2); @@ -102,7 +102,7 @@ function test() { makerjs.measure.isPointOnSlope([], s); makerjs.measure.isSlopeEqual(s, s); } - + function testModel(){ makerjs.model.breakPathsAtIntersections(model, { paths:{ } }); var opts: MakerJs.ICombineOptions = { trimDeadEnds: true, pointMatchingDistance: 2 }; @@ -153,10 +153,10 @@ function test() { new makerjs.models.Slot([0, 0], [1, 1], 7), new makerjs.models.Square(8), new makerjs.models.Star(5, 10, 5), - new makerjs.models.Text({} as opentypejs.Font, 'z', 12) + new makerjs.models.Text({} as opentype.Font, 'z', 12) ]; } - + function testPath() { makerjs.path.breakAtPoint(paths.arc, [0,0]).type; makerjs.path.clone(paths.line); @@ -174,9 +174,9 @@ function test() { makerjs.path.scale(paths.arc, 8); makerjs.path.straighten(paths.arc); } - + function testPaths() { - var paths = { + var paths = { arc: new makerjs.paths.Arc([0,0], 7, 0, 180), circle: new MakerJs.paths.Circle([0,0], 5), line: new makerjs.paths.Line([0,0], [1,1]) @@ -184,20 +184,20 @@ function test() { new makerjs.paths.Chord(paths.arc); new makerjs.paths.Parallel(paths.line, 4, [1,1]); - + //paths.line.layer = "0"; - - var x: MakerJs.IPathLine = { - type: "line", - origin: [9,9], - end: [8,8], + + var x: MakerJs.IPathLine = { + type: "line", + origin: [9,9], + end: [8,8], layer: "4" }; - + return paths; } - - function testPoint() { + + function testPoint() { makerjs.point.add(p1, p2); makerjs.point.average(p1, p2); makerjs.point.clone(p1); @@ -216,14 +216,14 @@ function test() { makerjs.point.subtract(p2, p1); makerjs.point.zero(); } - - function testSolvers() { + + function testSolvers() { makerjs.solvers.solveTriangleASA(4, 4, 4); makerjs.solvers.solveTriangleSSS(9, 9, 9); } - - function testUnits() { + + function testUnits() { makerjs.units.conversionScale(makerjs.unitType.Centimeter, makerjs.unitType.Foot); } - + } \ No newline at end of file diff --git a/mapbox-gl/index.d.ts b/mapbox-gl/index.d.ts index 654d3b2439..f8fb9d9b60 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 0000000000..2ee8d30949 --- /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/material-ui/index.d.ts b/material-ui/index.d.ts index 687cf77dd6..c98250fc0b 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -1032,7 +1032,7 @@ declare namespace __MaterialUI { export class List extends React.Component { } - interface ListItemProps extends React.HTMLAttributes<{}>, React.Props { + interface ListItemProps extends EnhancedButtonProps { // is the element that get the 'other' properties autoGenerateNestedIndicator?: boolean; disableKeyboardFocus?: boolean; @@ -1099,7 +1099,7 @@ declare namespace __MaterialUI { export class Menu extends React.Component { } - interface MenuItemProps extends React.HTMLAttributes<{}>, React.Props { + interface MenuItemProps extends List.ListItemProps { // is the element that get the 'other' properties animation?: React.ComponentClass; checked?: boolean; diff --git a/metric-suffix/index.d.ts b/metric-suffix/index.d.ts new file mode 100644 index 0000000000..8a3875c460 --- /dev/null +++ b/metric-suffix/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for metric-suffix.js 0.0.3 +// Project: https://github.com/mstdokumaci/metric-suffix.js +// Definitions by: David Muller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace metric_suffix; + +export = metric_suffix; + +declare function metric_suffix(value: number, precision?: number): string; \ No newline at end of file diff --git a/metric-suffix/metric-suffix-external-tests.ts b/metric-suffix/metric-suffix-external-tests.ts new file mode 100644 index 0000000000..5b22aeeaa1 --- /dev/null +++ b/metric-suffix/metric-suffix-external-tests.ts @@ -0,0 +1,22 @@ +import metric_suffix = require('metric-suffix'); + +metric_suffix(42) // 42 +metric_suffix(999) // 999 +metric_suffix(1000) // 1.0k + +metric_suffix(1234, 2) // 1.2k +metric_suffix(12345, 2) // 12k +metric_suffix(123456, 2) // 123k + +metric_suffix(1234, 3) // 1.23k +metric_suffix(12345, 3) // 12.3k +metric_suffix(123456, 3) // 123k + +metric_suffix(1234, 4) // 1.234k +metric_suffix(12345, 4) // 12.35k +metric_suffix(123456, 4) // 123.5k + +metric_suffix(986725) // 987k +metric_suffix(986725, 4) // 986.7k +metric_suffix(986725123) // 987M +metric_suffix(986725123, 5) // 986.73M \ No newline at end of file diff --git a/metric-suffix/metric-suffix-tests.ts b/metric-suffix/metric-suffix-tests.ts new file mode 100644 index 0000000000..eb88d6240f --- /dev/null +++ b/metric-suffix/metric-suffix-tests.ts @@ -0,0 +1,20 @@ +metric_suffix(42) // 42 +metric_suffix(999) // 999 +metric_suffix(1000) // 1.0k + +metric_suffix(1234, 2) // 1.2k +metric_suffix(12345, 2) // 12k +metric_suffix(123456, 2) // 123k + +metric_suffix(1234, 3) // 1.23k +metric_suffix(12345, 3) // 12.3k +metric_suffix(123456, 3) // 123k + +metric_suffix(1234, 4) // 1.234k +metric_suffix(12345, 4) // 12.35k +metric_suffix(123456, 4) // 123.5k + +metric_suffix(986725) // 987k +metric_suffix(986725, 4) // 986.7k +metric_suffix(986725123) // 987M +metric_suffix(986725123, 5) // 986.73M \ No newline at end of file diff --git a/metric-suffix/tsconfig.json b/metric-suffix/tsconfig.json new file mode 100644 index 0000000000..3d2a6c7d7a --- /dev/null +++ b/metric-suffix/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "metric-suffix-tests.ts", + "metric-suffix-external-tests.ts" + ] +} \ No newline at end of file diff --git a/mocha/index.d.ts b/mocha/index.d.ts index 5304f9333a..e512984ba4 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/msgpack5/index.d.ts b/msgpack5/index.d.ts new file mode 100644 index 0000000000..f2d0382182 --- /dev/null +++ b/msgpack5/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for msgpack5 v3.4.0 +// Project: https://github.com/mcollina/msgpack5/ +// Definitions by: Wonshik Kim , Kei Son +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import stream = require('stream'); +import bl = require('bl'); + +interface MsgPackOptions { + forceFloat64?: boolean; + compatibilityMode?: boolean; +} + +declare namespace msgpack5 { + interface EncodeDecodeOptions { + header?: boolean; + } + + class Base extends stream.Transform {} + class Encoder extends Base {} + class Decoder extends Base {} + + interface MessagePack { + encode(obj: any): bl; + decode(buf: Buffer): any; + decode(buf: bl): any; + register(type: number, $constructor: any, encode: (obj: T) => Buffer, decode: (data: Buffer) => T): MessagePack; + registerEncoder(check: (obj: T) => boolean, encode: (obj: T) => Buffer): MessagePack; + registerDecoder(type: number, decode: (data: Buffer) => any): MessagePack; + encoder(opts?: EncodeDecodeOptions): Encoder; + decoder(opts?: EncodeDecodeOptions): Decoder; + } +} + +declare function msgpack5(opts?: MsgPackOptions): msgpack5.MessagePack; + +export = msgpack5; diff --git a/msgpack5/msgpack5-test.ts b/msgpack5/msgpack5-test.ts new file mode 100644 index 0000000000..6cd9854992 --- /dev/null +++ b/msgpack5/msgpack5-test.ts @@ -0,0 +1,33 @@ +import * as msgpack from 'msgpack5'; + +// msgpack() +let packer = msgpack(); +packer = msgpack({ forceFloat64: true }); +packer = msgpack({ compatibilityMode: true }); + +class InputType { + number: number; + string: string; + + constructor() { + this.number = 1; + this.string = '1'; + } +} + +// msgpack().encode, msgpack().decode() +const IN: InputType = new InputType(); +const encoded = packer.encode(IN); +const OUT: InputType = packer.decode(encoded); + +// msgpack().registerEncoder(), msgpack().registerDecoder() +packer = packer.registerEncoder((o: InputType) => true, (o: InputType) => new Buffer('')); +packer = packer.registerDecoder(0x01, (data) => ({ content: { number: 1, string: '1' }})); + +// msgpack().register() +packer = packer.register(0x01, InputType, (obj: InputType) => new Buffer(''), (data: Buffer) => (new InputType())); + +// msgpack().encoder(), msgpack().decoder() +const encoder = packer.encoder(); +const decoder = packer.decoder(); +encoder.pipe(decoder); diff --git a/msgpack5/tsconfig.json b/msgpack5/tsconfig.json new file mode 100644 index 0000000000..82e4af0f63 --- /dev/null +++ b/msgpack5/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "moduleResolution": "node", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "msgpack5-test.ts" + ] +} diff --git a/neo4j/index.d.ts b/neo4j/index.d.ts new file mode 100644 index 0000000000..f0923557ca --- /dev/null +++ b/neo4j/index.d.ts @@ -0,0 +1,278 @@ +// Type definitions for node-neo4j 2.0.0 +// Project: https://github.com/thingdom/node-neo4j +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Request } from "request"; + +type ResultCallback = (error: any, result: any) => void; +type DoneCallback = (error: any) => void; + +/** + * Authentication information. + * @interface + */ +export interface Authentication { + password: string; + username: string; +} + +/** + * Password options. + * @interface + */ +export interface ChangePasswordOptions { + password: string; +} + +/** + * Constraint options. + * @interface + */ +export interface ConstraintOptions { + label?: any; + property?: any; +} + +/** + * Cypher request options. + * @interface + */ +export interface CypherOptions { + commit?: {}; + headers?: {}; + lean?: {}; + params?: {}; + query?: {}; +} + +/** + * Database options. + * @interface + */ +export interface GraphDatabaseOptions { + /** + * HTTP agent. + * @type {any} + */ + agent: any; + + /** + * Authentication information. + * @type {string|Authentication} + */ + auth: string | Authentication; + + /** + * HTTP headers. + * @type {Object} + */ + headers: {}; + + /** + * Proxy address. + * @type {string} + */ + proxy: string; + + /** + * URL connection. + * @type {string} + */ + url: string; +} + +/** + * HTTP options. + * @interface + */ +export interface HttpOptions { + headers: {}; + method: string; + path: string; + body: any; + raw: any; +} + +/** + * Index options. + * @interface + */ +export interface IndexOptions { + label?: any; + property?: any; +} + +/** + * Transaction. + * @interface + */ +export interface Transaction { + expiresAt: Date; + expiresIn: Date | number; + state: string; + + commit(callback: DoneCallback): void; + cypher(options: CypherOptions, callback: ResultCallback): Request; + renew(callback: DoneCallback): void; + rollback(callback: DoneCallback): void; +} + +/** + * Database. + * @class + */ +export class GraphDatabase { + /** + * Constructor. + * @constructor + * @param {string} url A URL connection. + */ + constructor(url: string); + + /** + * Constructor. + * @constructor + * @param {GraphDatabaseOptions} options Connection options. + */ + constructor(options: GraphDatabaseOptions); + + /** + * Agent. + * @type {any} + */ + agent: any; + + /** + * Credentials. + * @type {Authentication} + */ + auth: Authentication; + + /** + * Headers. + * @type {Object} + */ + headers: {}; + + /** + * Proxy. + * @type {any} + */ + proxy: any; + + /** + * URL connection. + * @type {string} + */ + url: string; + + /** + * Makes multiple queries, across multiple network requests, all within a single transaction. + * @return {Transaction} The transaction. + */ + beginTransaction(): Transaction; + + /** + * Changes password. + * @param {ChangePasswordOptions} options Options. + * @param {DoneCallback} callback A callback. + */ + changePassword(options: ChangePasswordOptions, callback: DoneCallback): void; + + /** + * Checks if the password must be changed. + * @param {Function} callback A callback. + */ + checkPasswordChangeNeeded(callback: (error: any, changed: boolean) => void): void; + + /** + * Creates a constraint. + * @param {ConstraintOptions} options Options. + * @param {ResultCallback} callback A callback. + */ + createConstraint(options: ConstraintOptions, callback: ResultCallback): void; + + /** + * Makes simple, parametrized Cypher queries. + * @param {CypherOptions} options Options. + * @param {ResultCallback} callback A callback. + */ + cypher(options: CypherOptions, callback: ResultCallback): Request; + + /** + * Drops a constraint. + * @param {ConstraintOptions} options Options. + * @param {DoneCallback} callback A callback. + */ + dropConstraint(options: ConstraintOptions, callback: DoneCallback): void; + + /** + * Drop an index. + * @param {IndexOptions} options Options. + * @param {DoneCallback} callback A callback. + */ + dropIndex(options: IndexOptions, callback: DoneCallback): void; + + /** + * Gets constraints. + * @param {ConstraintOptions} options Options or callback. + * @param {ResultCallback} callback A callback. + */ + getConstraints(options: ConstraintOptions, callback?: ResultCallback): void; + + /** + * Gets indexes. + * @param {ResultCallback} callback A callback. + */ + getIndexes(callback?: ResultCallback): void; + + /** + * Gets indexes. + * @param {IndexOptions} options Options. + * @param {ResultCallback} callback A callback. + */ + getIndexes(options: IndexOptions, callback: ResultCallback): void; + + /** + * Get labels. + * @param {ResultCallback} callback A callback. + */ + getLabels(callback: ResultCallback): void; + + /** + * Gets property keys. + * @param {ResultCallback} callback A callback. + */ + getPropertyKeys(callback: ResultCallback): void; + + /** + * Gets relationship types. + * @param {ResultCallback} callback A callback. + */ + getRelationshipTypes(callback: ResultCallback): void; + + /** + * Determines if a constraint exists. + * @param {ConstraintOptions} options Options. + * @param {Function} callback A callback. + */ + hasConstraint(options: ConstraintOptions, callback: (error: any, exists: boolean) => void): void; + + /** + * Determines if an index exists. + * @param {IndexOptions} options Options. + * @param {Function} callback A callback. + */ + hasIndex(options: IndexOptions, callback: (error: any, exists: boolean) => void): void; + + /** + * Makes arbitrary HTTP request to the REST API. + * @param {HttpOptions} options Options. + * @param {ResultCallback} callback A callback. + * @return {Request} The HTTP request. + */ + http(options: HttpOptions, callback: ResultCallback): Request; +} diff --git a/neo4j/neo4j-tests.ts b/neo4j/neo4j-tests.ts new file mode 100644 index 0000000000..3745e025f5 --- /dev/null +++ b/neo4j/neo4j-tests.ts @@ -0,0 +1,55 @@ +import * as neo4j from "neo4j"; + +let db = new neo4j.GraphDatabase("http://localhost:7474"); +db = new neo4j.GraphDatabase({ + url: 'http://localhost:7474', + auth: { + password: "", + username: "" + }, + headers: {}, + proxy: "", + agent: null +}); + +/** Password */ +db.checkPasswordChangeNeeded((error: any, changed: boolean) => { }); +db.changePassword({ password: "" }, (error: any) => { }); + +/** Query */ +db.cypher({ query: 'MATCH (u:User {email: {email}}) RETURN u', params: { email: 'alice@example.com' } }, (error: any, results: any) => { }); + +/** Constraint */ +db.createConstraint({ label: "", property: "" }, (error: any, constraint: any) => { }); +db.dropConstraint({ label: "", property: "" }, (error: any) => { }); +db.getConstraints({ label: "", property: "" }, (error: any, constraints: any) => { }); +db.hasConstraint({ label: "", property: "" }, (error: any, exists: boolean) => { }); + +/** Index */ +db.dropIndex({ label: "", property: "" }, (error: any) => { }); +db.getIndexes((error: any, indexes: any) => { }); +db.getIndexes({ label: "", property: "" }, (error: any, indexes: any) => { }); +db.hasIndex({ label: "", property: "" }, (error: any, exists: boolean) => { }); + +/** Labels */ +db.getLabels((error: any, labels: any) => { }); + +/** Property keys */ +db.getPropertyKeys((error: any, keys: any) => { }); + +/** Relationship */ +db.getRelationshipTypes((error: any, types: any) => { }); + +/** HTTP */ +db.http({ method: "", path: "", headers: {}, body: "", raw: "" }, (error: any, body: any) => { }); + +/** Transaction */ +const transaction: neo4j.Transaction = db.beginTransaction(); +transaction.rollback((error: any) => { }); +transaction.commit((error: any) => { }); +transaction.renew((error: any) => { }); +transaction.cypher({ query: 'MATCH (u:User {email: {email}}) RETURN u', params: { email: 'alice@example.com' } }, (error: any, results: any) => { }); + +const expiresIn: Date | number = transaction.expiresIn; +const expiresAt: Date = transaction.expiresAt; +const state: string = transaction.state diff --git a/neo4j/tsconfig.json b/neo4j/tsconfig.json new file mode 100644 index 0000000000..dd3a543a23 --- /dev/null +++ b/neo4j/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", + "neo4j-tests.ts" + ] +} diff --git a/nes/nes.d.ts b/nes/nes.d.ts index f6159be9b0..6ebc9ee1c0 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 4a9720ba5e..4e293993f7 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/nock/index.d.ts b/nock/index.d.ts index db852f596a..447c591803 100644 --- a/nock/index.d.ts +++ b/nock/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for nock v8.0.0 +// Type definitions for nock v8.2.0 // Project: https://github.com/node-nock/nock // Definitions by: bonnici , Horiuchi_H // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -91,6 +91,7 @@ declare namespace nock { once(): this; twice(): this; thrice(): this; + optionally(): this; delay(opts: number | { head?: number; body?: number; }): this; delayBody(timeMs: number): this; diff --git a/nock/nock-tests.ts b/nock/nock-tests.ts index d9a6844915..0d1b11159f 100644 --- a/nock/nock-tests.ts +++ b/nock/nock-tests.ts @@ -76,6 +76,8 @@ inst = inst.once(); inst = inst.twice(); inst = inst.thrice(); +inst = inst.optionally(); + scope = scope.defaultReplyHeaders(value); scope = scope.matchHeader(str, str); @@ -412,6 +414,9 @@ nock('http://zombo.com').get('/').once().reply(200, 'Ok'); nock('http://zombo.com').get('/').twice().reply(200, 'Ok'); nock('http://zombo.com').get('/').thrice().reply(200, 'Ok'); +// Make responding optional +nock('http://zombo.com').get('/').optionally().reply(200, 'Ok'); + // Delay the response body nock('http://my.server.com') .get('/') diff --git a/node-usb/node-usb.d.ts b/node-usb/node-usb.d.ts deleted file mode 100644 index 78b93bbfd9..0000000000 --- a/node-usb/node-usb.d.ts +++ /dev/null @@ -1,233 +0,0 @@ -// Type definitions for node-usb 1.1.2 -// Project: https://github.com/nonolith/node-usb -// Definitions by: Eric Brody -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module "usb" { - - class Device { - public timeout: number; - public busNumber: number; - public deviceAddress: number; - public portNumbers: Array; - public deviceDescriptor: DeviceDescriptor; - public configDescriptor: ConfigDescriptor; - public interfaces: Array; - - __open(): void; - __claimInterface(addr: number): void; - - open(defaultConfig?: boolean): void; - close(): void; - interface(addr: number): Interface; - controlTransfer(bmRequestType: number, bRequest: number, wValue: number, wIndex: number, data_or_length: any, callback: (error?: string, buf?: Buffer) => void): Device; - getStringDescriptor(desc_index: number, callback: (error?: string, buf?: Buffer) => void): void; - setConfiguration(desired: number, cb: (err?: string) => void): void; - reset(callback: (err?: string) => void): void; - } - - class DeviceDescriptor { - public bLength: number; - public bDescriptorType: number; - public bcdUSB: number; - public bDeviceClass: number; - public bDeviceSubClass: number; - public bDeviceProtocol: number; - public bMaxPacketSize: number; - public idVendor: number; - public idProduct: number; - public bcdDevice: number; - public iManufacturer: number; - public iProduct: number; - public iSerialNumber: number; - public bNumConfigurations: number; - } - - class ConfigDescriptor { - public bLength: number; - public bDescriptorType: number; - public wTotalLength: number; - public bNumInterfaces: number; - public bConfigurationValue: number; - public iConfiguration: number; - public bmAttributes: number; - public bMaxPower: number; - public extra: Buffer; - } - - class Interface { - public descriptor: InterfaceDescriptor; - public endpoints: Array; - constructor(device: Device, id: number); - claim(): void; - release(closeEndpoints?: (err?: string) => void, cb?: (err?: string) => void): void; - isKernelDriverActive(): boolean; - detachKernelDriver(): number; - attachKernelDriver(): number; - setAltSetting(altSetting: number, cb: (err?: string) => void): void; - endpoint(addr: number): IEndpoint; - } - - class InterfaceDescriptor { - public bLength: number; - public bDescriptorType: number; - public bInterfaceNumber: number; - public bAlternateSetting: number; - public bNumEndpoints: number; - public bInterfaceClass: number; - public bInterfaceSubClass: number; - public bInterfaceProtocol: number; - public iInterface: number; - public extra: Buffer; - } - - interface IEndpoint { - direction: string; - transferType: number; - timeout: number; - descriptor: EndpointDescriptor; - } - - class InEndpoint implements IEndpoint { - public direction: string; - public transferType: number; - public timeout: number; - public descriptor: EndpointDescriptor; - constructor(device: Device, descriptor: EndpointDescriptor); - transfer(length: number, callback: (error: string, data: Buffer) => void): InEndpoint; - startPoll(nTransfers: number, transferSize: number): void; - stopPoll(cb: () => void): void; - } - - class OutEndpoint implements IEndpoint { - public direction: string; - public transferType: number; - public timeout: number; - public descriptor: EndpointDescriptor; - constructor(device: Device, descriptor: EndpointDescriptor); - transfer(buffer: Buffer, cb: (err?: string) => void): OutEndpoint; - transferWithZLP(buf: Buffer, cb: (err?: string) => void): void; - } - - class EndpointDescriptor { - public bLength: number; - public bDescriptorType: number; - public bEndpointAddress: number; - public bmAttributes: number; - public wMaxPacketSize: number; - public bInterval: number; - public bRefresh: number; - public bSynchAddress: number; - } - - function findByIds(vid: number, pid: number): Device; - function on(event: string, callback: (device: Device) => void): void; - function getDeviceList(): Array; - function setDebugLevel(level: number): void; - - const LIBUSB_CLASS_PER_INTERFACE: number; - const LIBUSB_CLASS_AUDIO: number; - const LIBUSB_CLASS_COMM: number; - const LIBUSB_CLASS_HID: number; - const LIBUSB_CLASS_PRINTER: number; - const LIBUSB_CLASS_PTP: number; - const LIBUSB_CLASS_MASS_STORAGE: number; - const LIBUSB_CLASS_HUB: number; - const LIBUSB_CLASS_DATA: number; - const LIBUSB_CLASS_WIRELESS: number; - const LIBUSB_CLASS_APPLICATION: number; - const LIBUSB_CLASS_VENDOR_SPEC: number; - // libusb_standard_request - const LIBUSB_REQUEST_GET_STATUS: number; - const LIBUSB_REQUEST_CLEAR_FEATURE: number; - const LIBUSB_REQUEST_SET_FEATURE: number; - const LIBUSB_REQUEST_SET_ADDRESS: number; - const LIBUSB_REQUEST_GET_DESCRIPTOR: number; - const LIBUSB_REQUEST_SET_DESCRIPTOR: number; - const LIBUSB_REQUEST_GET_CONFIGURATION: number; - const LIBUSB_REQUEST_SET_CONFIGURATION: number; - const LIBUSB_REQUEST_GET_INTERFACE: number; - const LIBUSB_REQUEST_SET_INTERFACE: number; - const LIBUSB_REQUEST_SYNCH_FRAME: number; - // libusb_descriptor_type - const LIBUSB_DT_DEVICE: number; - const LIBUSB_DT_CONFIG: number; - const LIBUSB_DT_STRING: number; - const LIBUSB_DT_INTERFACE: number; - const LIBUSB_DT_ENDPOINT: number; - const LIBUSB_DT_HID: number; - const LIBUSB_DT_REPORT: number; - const LIBUSB_DT_PHYSICAL: number; - const LIBUSB_DT_HUB: number; - // libusb_endpoint_direction - const LIBUSB_ENDPOINT_IN: number; - const LIBUSB_ENDPOINT_OUT: number; - // libusb_transfer_type - const LIBUSB_TRANSFER_TYPE_CONTROL: number; - const LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: number; - const LIBUSB_TRANSFER_TYPE_BULK: number; - const LIBUSB_TRANSFER_TYPE_INTERRUPT: number; - // libusb_iso_sync_type - const LIBUSB_ISO_SYNC_TYPE_NONE: number; - const LIBUSB_ISO_SYNC_TYPE_ASYNC: number; - const LIBUSB_ISO_SYNC_TYPE_ADAPTIVE: number; - const LIBUSB_ISO_SYNC_TYPE_SYNC: number; - // libusb_iso_usage_type - const LIBUSB_ISO_USAGE_TYPE_DATA: number; - const LIBUSB_ISO_USAGE_TYPE_FEEDBACK: number; - const LIBUSB_ISO_USAGE_TYPE_IMPLICIT: number; - // libusb_transfer_status - const LIBUSB_TRANSFER_COMPLETED: number; - const LIBUSB_TRANSFER_ERROR: number; - const LIBUSB_TRANSFER_TIMED_OUT: number; - const LIBUSB_TRANSFER_CANCELLED: number; - const LIBUSB_TRANSFER_STALL: number; - const LIBUSB_TRANSFER_NO_DEVICE: number; - const LIBUSB_TRANSFER_OVERFLOW: number; - // libusb_transfer_flags - const LIBUSB_TRANSFER_SHORT_NOT_OK: number; - const LIBUSB_TRANSFER_FREE_BUFFER: number; - const LIBUSB_TRANSFER_FREE_TRANSFER: number; - // libusb_request_type - const LIBUSB_REQUEST_TYPE_STANDARD: number; - const LIBUSB_REQUEST_TYPE_CLASS: number; - const LIBUSB_REQUEST_TYPE_VENDOR: number; - const LIBUSB_REQUEST_TYPE_RESERVED: number; - // libusb_request_recipient - const LIBUSB_RECIPIENT_DEVICE: number; - const LIBUSB_RECIPIENT_INTERFACE: number; - const LIBUSB_RECIPIENT_ENDPOINT: number; - const LIBUSB_RECIPIENT_OTHER: number; - - const LIBUSB_CONTROL_SETUP_SIZE: number; - - // libusb_error - // Input/output error - const LIBUSB_ERROR_IO: number; - // Invalid parameter - const LIBUSB_ERROR_INVALID_PARAM: number; - // Access denied (insufficient permissions) - const LIBUSB_ERROR_ACCESS: number; - // No such device (it may have been disconnected) - const LIBUSB_ERROR_NO_DEVICE: number; - // Entity not found - const LIBUSB_ERROR_NOT_FOUND: number; - // Resource busy - const LIBUSB_ERROR_BUSY: number; - // Operation timed out - const LIBUSB_ERROR_TIMEOUT: number; - // Overflow - const LIBUSB_ERROR_OVERFLOW: number; - // Pipe error - const LIBUSB_ERROR_PIPE: number; - // System call interrupted (perhaps due to signal) - const LIBUSB_ERROR_INTERRUPTED: number; - // Insufficient memory - const LIBUSB_ERROR_NO_MEM: number; - // Operation not supported or unimplemented on this platform - const LIBUSB_ERROR_NOT_SUPPORTED: number; - // Other error - const LIBUSB_ERROR_OTHER: number; -} diff --git a/node/index.d.ts b/node/index.d.ts index c9f672ec9f..ea81e61147 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; @@ -2019,6 +2167,8 @@ declare module "fs" { export interface ReadStream extends stream.Readable { close(): void; destroy(): void; + bytesRead: number; + path: string | Buffer; /** * events.EventEmitter diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 4040173e41..5f229fc3f6 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 663d6ea59c..0d6bbe0159 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 4083c826ae..9873b19e72 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; @@ -420,11 +434,19 @@ namespace util_tests { // http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options function stream_readable_pipe_test() { + var rs = fs.createReadStream(Buffer.from('file.txt')); var r = fs.createReadStream('file.txt'); var z = zlib.createGzip({ finishFlush: zlib.Z_FINISH }); var w = fs.createWriteStream('file.txt.gz'); + + assert(typeof r.bytesRead === 'number'); + assert(typeof r.path === 'string'); + assert(typeof rs.path === 'Buffer'); + r.pipe(z).pipe(w); + r.close(); + rs.close(); } // Simplified constructors @@ -1206,6 +1228,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 +1317,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 +1581,10 @@ namespace process_tests { { assert(process.argv[0] === process.argv0); } + { + var module: NodeModule; + module = process.mainModule; + } } /////////////////////////////////////////////////////////// @@ -1651,6 +1836,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/notNeededPackages.json b/notNeededPackages.json index 0f32a6dcad..b2c8de0dfe 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -34,6 +34,24 @@ "typingsPackageName": "protractor", "sourceRepoURL": "https://github.com/angular/protractor", "asOfVersion": "4.0.0" + }, + { + "libraryName": "LinqSharp", + "typingsPackageName": "linqsharp", + "sourceRepoURL": "https://github.com/brunolm/LinqSharp", + "asOfVersion": "1.0.0" + }, + { + "libraryName": "TypeScript", + "typingsPackageName": "typescript", + "sourceRepoURL": "https://github.com/Microsoft/TypeScript", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "TypeScript", + "typingsPackageName": "typescript-services", + "sourceRepoURL": "https://github.com/Microsoft/TypeScript", + "asOfVersion": "2.0.0" } ] } diff --git a/npm-debug.log.3539137130 b/npm-debug.log.3539137130 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/office-js/index.d.ts b/office-js/index.d.ts index 59510c6ffa..fdfa55622f 100644 --- a/office-js/index.d.ts +++ b/office-js/index.d.ts @@ -63,8 +63,24 @@ declare namespace Office { isSetSupported(name: string, minVersion?: number): boolean; } } + /** + * Provides specific information about an error that occurred during an asynchronous data operation. + */ export interface Error { + /** + * Gets the numeric code of the error. + * @since 1.0 + */ + code: number; + /** + * Gets the name of the error. + * @since 1.0 + */ message: string; + /** + * Gets a detailed description of the error. + * @since 1.0 + */ name: string; } export interface UI { @@ -920,6 +936,19 @@ declare namespace Office { */ setSelectedDataAsync(data: string | TableData | any[][], options?: any, callback?: (result: AsyncResult) => void): void; } + /** + * Provides information about the document that raised the SelectionChanged event. + */ + export interface DocumentSelectionChangedEventArgs { + /** + * Gets a Document object that represents the document that raised the SelectionChanged event. + */ + document: Document; + /** + * Get an EventType enumeration value that identifies the kind of event that was raised. + */ + type: EventType; + } export interface File { size: number; sliceCount: number; @@ -5126,7 +5155,7 @@ declare module Excel { * * The first criterion used to filter data. Used as an operator in the case of "custom" filtering. For example ">50" for number greater than 50 or "=*s" for values ending in "s". - + Used as a number in the case of top/bottom items/percents. E.g. "5" for the top 5 items if filterOn is set to "topItems" * * [Api set: ExcelApi 1.2] diff --git a/opentype.js/index.d.ts b/opentype.js/index.d.ts new file mode 100644 index 0000000000..24df752461 --- /dev/null +++ b/opentype.js/index.d.ts @@ -0,0 +1,240 @@ +// Type definitions for opentype.js +// Project: https://github.com/nodebox/opentype.js +// Definitions by: Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace opentype; + +interface Contour extends Array { +} + +export class Encoding { + charset: string; + charToGlyphIndex(c: string): number; + font: Font; +} + +interface Field { + name: string; + type: string; + value: any; +} + +export class Font { + private nametoGlyphIndex; + private supported; + constructor(options: FontOptions); + ascender: number; + cffEncoding: Encoding; + charToGlyph(c: string): Glyph; + charToGlyphIndex(s: string): number; + descender: number; + download(): void; + draw(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; + drawMetrics(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; + drawPoints(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; + encoding: Encoding; + forEachGlyph(text: string, x: number, y: number, fontSize: number, options: RenderOptions, callback: { (glyph: Glyph, x: number, y: number, fontSize: number, options?: RenderOptions): void; }): void; + getEnglishName(name: string): string; + getGposKerningValue: { (leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; }; + getKerningValue(leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; + getPath(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path; + getPaths(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path[]; + glyphs: GlyphSet; + glyphIndexToName(gid: number): string; + glyphNames: GlyphNames; + hasChar(c: string): boolean; + kerningPairs: KerningPairs; + names: FontNames; + nameToGlyph(name: string): Glyph; + nameToGlyphIndex(name: string): number; + numberOfHMetrics: number; + numGlyphs: number; + outlinesFormat: string; + stringToGlyphs(s: string): Glyph[]; + tables: { [tableName: string]: Table; }; + toArrayBuffer(): ArrayBuffer; + toBuffer(): ArrayBuffer; + toTables(): Table; + unitsPerEm: number; + validate(): void; +} + +interface FontNames { + copyright: LocalizedName; + description: LocalizedName; + designer: LocalizedName; + designerURL: LocalizedName; + fontFamily: LocalizedName; + fontSubfamily: LocalizedName; + fullName: LocalizedName; + license: LocalizedName; + licenseURL: LocalizedName; + manufacturer: LocalizedName; + manufacturerURL: LocalizedName; + postScriptName: LocalizedName; + trademark: LocalizedName; + version: LocalizedName; +} + +interface FontOptions { + copyright?: string; + ascender?: number; + descender?: number; + description?: string; + designer?: string; + designerURL?: string; + empty?: boolean; + familyName?: string; + fullName?: string; + glyphs?: Glyph[] | GlyphSet; + license?: string; + licenseURL?: string; + manufacturer?: string; + manufacturerURL?: string; + postScriptName?: string; + styleName?: string; + unitsPerEm?: number; + trademark?: string; + version?: string; +} + +export class Glyph { + private index; + private xMin; + private xMax; + private yMin; + private yMax; + private points; + constructor(options: GlyphOptions); + addUnicode(unicode: number): void; + advanceWidth: number; + bindConstructorValues(options: GlyphOptions): void; + draw(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; + drawMetrics(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; + drawPoints(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; + getContours(): Contour[]; + getMetrics(): Metrics; + getPath(x: number, y: number, fontSize: number): Path; + name: string; + path: Path | { (): Path; }; + unicode: number; + unicodes: number[]; +} + +interface GlyphOptions { + advanceWidth?: number; + index?: number; + font?: Font; + name?: string; + path?: Path; + unicode?: number; + unicodes?: number[]; + xMax?: number; + xMin?: number; + yMax?: number; + yMin?: number; +} + +export class GlyphNames { + private names; + constructor(post: Post); + glyphIndexToName(gid: number): string; + nameToGlyphIndex(name: string): number; +} + +export class GlyphSet { + private font; + private glyphs; + constructor(font: Font, glyphs: Glyph[] | { (): Glyph; }[]); + get(index: number): Glyph; + length: number; + push(index: number, loader: { (): Glyph; }): void; +} + +interface KerningPairs { + [pair: string]: number; +} + +export function load(url: string, callback: { (error: any, font?: Font): void; }): void; + +export function loadSync(url: string): Font; + +interface LocalizedName { + [lang: string]: string; +} + +interface Metrics { + leftSideBearing: number; + rightSideBearing?: number; + xMax: number; + xMin: number; + yMax: number; + yMin: number; +} + +export function parse(buffer: any): Font; + +export class Path { + private fill; + private stroke; + private strokeWidth; + constructor(); + bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void; + close: () => void; + closePath(): void; + commands: PathCommand[]; + curveTo: (x1: number, y1: number, x2: number, y2: number, x: number, y: number) => void; + draw(ctx: CanvasRenderingContext2D): void; + extend(pathOrCommands: Path | PathCommand[]): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(x1: number, y1: number, x: number, y: number): void; + quadTo: (x1: number, y1: number, x: number, y: number) => void; + toPathData(decimalPlaces: number): string; + toSVG(decimalPlaces: number): string; + unitsPerEm: number; +} + +interface PathCommand { + type: string; + x?: number; + y?: number; + x1?: number; + y1?: number; + x2?: number; + y2?: number; +} + +interface Point { + lastPointOfContour?: boolean; +} + +interface Post { + glyphNameIndex?: number[]; + isFixedPitch: number; + italicAngle: number; + maxMemType1: number; + minMemType1: number; + maxMemType42: number; + minMemType42: number; + names?: string[]; + numberOfGlyphs?: number; + offset?: number[]; + underlinePosition: number; + underlineThickness: number; + version: number; +} + +interface RenderOptions { + kerning: boolean; +} + +interface Table { + [propName: string]: any; + encode(): number[]; + fields: Field[]; + sizeOf(): number; + tables: Table[]; + tableName: string; +} diff --git a/opentype/opentype-tests.ts b/opentype.js/opentype.js-tests.ts similarity index 100% rename from opentype/opentype-tests.ts rename to opentype.js/opentype.js-tests.ts diff --git a/linqsharp/tsconfig.json b/opentype.js/tsconfig.json similarity index 92% rename from linqsharp/tsconfig.json rename to opentype.js/tsconfig.json index 84a6339e79..d46b9ebabf 100644 --- a/linqsharp/tsconfig.json +++ b/opentype.js/tsconfig.json @@ -14,6 +14,6 @@ }, "files": [ "index.d.ts", - "linqsharp-tests.ts" + "opentype.js-tests.ts" ] } \ No newline at end of file diff --git a/opentype/index.d.ts b/opentype/index.d.ts deleted file mode 100644 index fec42369a1..0000000000 --- a/opentype/index.d.ts +++ /dev/null @@ -1,248 +0,0 @@ -// Type definitions for opentype.js -// Project: https://github.com/nodebox/opentype.js -// Definitions by: Dan Marshall -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace opentypejs { - - interface Contour extends Array { - } - - class Encoding { - charset: string; - charToGlyphIndex(c: string): number; - font: Font; - } - - interface Field { - name: string; - type: string; - value: any; - } - - class Font { - private nametoGlyphIndex; - private supported; - constructor(options: FontOptions); - ascender: number; - cffEncoding: Encoding; - charToGlyph(c: string): Glyph; - charToGlyphIndex(s: string): number; - descender: number; - download(): void; - draw(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; - drawMetrics(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; - drawPoints(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; - encoding: Encoding; - forEachGlyph(text: string, x: number, y: number, fontSize: number, options: RenderOptions, callback: { (glyph: Glyph, x: number, y: number, fontSize: number, options?: RenderOptions): void; }): void; - getEnglishName(name: string): string; - getGposKerningValue: { (leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; }; - getKerningValue(leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; - getPath(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path; - getPaths(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path[]; - glyphs: GlyphSet; - glyphIndexToName(gid: number): string; - glyphNames: GlyphNames; - hasChar(c: string): boolean; - kerningPairs: KerningPairs; - names: FontNames; - nameToGlyph(name: string): Glyph; - nameToGlyphIndex(name: string): number; - numberOfHMetrics: number; - numGlyphs: number; - outlinesFormat: string; - stringToGlyphs(s: string): Glyph[]; - tables: { [tableName: string]: Table; }; - toArrayBuffer(): ArrayBuffer; - toBuffer(): ArrayBuffer; - toTables(): Table; - unitsPerEm: number; - validate(): void; - } - - interface FontNames { - copyright: LocalizedName; - description: LocalizedName; - designer: LocalizedName; - designerURL: LocalizedName; - fontFamily: LocalizedName; - fontSubfamily: LocalizedName; - fullName: LocalizedName; - license: LocalizedName; - licenseURL: LocalizedName; - manufacturer: LocalizedName; - manufacturerURL: LocalizedName; - postScriptName: LocalizedName; - trademark: LocalizedName; - version: LocalizedName; - } - - interface FontOptions { - copyright?: string; - ascender?: number; - descender?: number; - description?: string; - designer?: string; - designerURL?: string; - empty?: boolean; - familyName?: string; - fullName?: string; - glyphs?: Glyph[] | GlyphSet; - license?: string; - licenseURL?: string; - manufacturer?: string; - manufacturerURL?: string; - postScriptName?: string; - styleName?: string; - unitsPerEm?: number; - trademark?: string; - version?: string; - } - - class Glyph { - private index; - private xMin; - private xMax; - private yMin; - private yMax; - private points; - constructor(options: GlyphOptions); - addUnicode(unicode: number): void; - advanceWidth: number; - bindConstructorValues(options: GlyphOptions): void; - draw(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; - drawMetrics(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; - drawPoints(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; - getContours(): Contour[]; - getMetrics(): Metrics; - getPath(x: number, y: number, fontSize: number): Path; - name: string; - path: Path | { (): Path; }; - unicode: number; - unicodes: number[]; - } - - interface GlyphOptions { - advanceWidth?: number; - index?: number; - font?: Font; - name?: string; - path?: Path; - unicode?: number; - unicodes?: number[]; - xMax?: number; - xMin?: number; - yMax?: number; - yMin?: number; - } - - class GlyphNames { - private names; - constructor(post: Post); - glyphIndexToName(gid: number): string; - nameToGlyphIndex(name: string): number; - } - - class GlyphSet { - private font; - private glyphs; - constructor(font: Font, glyphs: Glyph[] | { (): Glyph; }[]); - get(index: number): Glyph; - length: number; - push(index: number, loader: { (): Glyph; }): void; - } - - interface KerningPairs { - [pair: string]: number; - } - - function load(url: string, callback: { (error: any, font?: Font): void; }): void; - - function loadSync(url: string): Font; - - interface LocalizedName { - [lang: string]: string; - } - - interface Metrics { - leftSideBearing: number; - rightSideBearing?: number; - xMax: number; - xMin: number; - yMax: number; - yMin: number; - } - - function parse(buffer: any): Font; - - class Path { - private fill; - private stroke; - private strokeWidth; - constructor(); - bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void; - close: () => void; - closePath(): void; - commands: PathCommand[]; - curveTo: (x1: number, y1: number, x2: number, y2: number, x: number, y: number) => void; - draw(ctx: CanvasRenderingContext2D): void; - extend(pathOrCommands: Path | PathCommand[]): void; - lineTo(x: number, y: number): void; - moveTo(x: number, y: number): void; - quadraticCurveTo(x1: number, y1: number, x: number, y: number): void; - quadTo: (x1: number, y1: number, x: number, y: number) => void; - toPathData(decimalPlaces: number): string; - toSVG(decimalPlaces: number): string; - unitsPerEm: number; - } - - interface PathCommand { - type: string; - x?: number; - y?: number; - x1?: number; - y1?: number; - x2?: number; - y2?: number; - } - - interface Point { - lastPointOfContour?: boolean; - } - - interface Post { - glyphNameIndex?: number[]; - isFixedPitch: number; - italicAngle: number; - maxMemType1: number; - minMemType1: number; - maxMemType42: number; - minMemType42: number; - names?: string[]; - numberOfGlyphs?: number; - offset?: number[]; - underlinePosition: number; - underlineThickness: number; - version: number; - } - - interface RenderOptions { - kerning: boolean; - } - - interface Table { - [propName: string]: any; - encode(): number[]; - fields: Field[]; - sizeOf(): number; - tables: Table[]; - tableName: string; - } - -} - -declare var opentype: typeof opentypejs; - -declare module "opentype.js" { - export = opentype; -} diff --git a/openui5/index.d.ts b/openui5/index.d.ts new file mode 100644 index 0000000000..b6c1a14d1c --- /dev/null +++ b/openui5/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for OpenUI5 1.40 +// Project: http://openui5.org/ +// Definitions by: Lukas May +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// \ No newline at end of file diff --git a/openui5/jquery.sap.d.ts b/openui5/jquery.sap.d.ts new file mode 100644 index 0000000000..5a5c5d70bf --- /dev/null +++ b/openui5/jquery.sap.d.ts @@ -0,0 +1,187 @@ +// Type definitions for OpenUI5 1.40 +// Project: http://openui5.org/ +// Definitions by: Lukas May +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare interface Ui5Logger { + //Allows to add a new LogListener that will be notified for new log entries. + addLogListener(oListener: any): void; + //Creates a new debug-level entry in the log with the given message, details and calling component. + debug(sMessage: string, sDetails?: string, sComponent?: string): void; + //Creates a new error-level entry in the log with the given message, details and calling component. + error(sMessage: string, sDetails?: string, sComponent?: string): void; + //Creates a new fatal-level entry in the log with the given message, details and calling component. + fatal(sMessage: string, sDetails?: string, sComponent?: string): void; + //Returns the log level currently effective for the given component. + getLevel(sComponent?: string): void; + //Returns the logged entries recorded so far as an array. + getLogEntries(): void; + //Returns a jQuery.sap.log.Logger for the given component. + getLogger(sComponent: string, iDefaultLogLevel?: any): void; + //Creates a new info-level entry in the log with the given message, details and calling component. + info(sMessage: string, sDetails?: string, sComponent?: string): void; + //Checks whether logging is enabled for the given log level, depending on the currently effective log level for the given component. + isLoggable(iLevel?: any, sComponent?: string): void; + //Allows to remove a registered LogListener. + removeLogListener(oListener: any): void; + //Defines the maximum jQuery.sap.log.Level of log entries that will be recorded. + setLevel(iLogLevel: any, sComponent?: string): void; + //Creates a new trace-level entry in the log with the given message, details and calling component. + trace(sMessage: string, sDetails?: string, sComponent?: string): void; + //Creates a new warning-level entry in the log with the given message, details and calling component. + warning(sMessage: string, sDetails?: string, sComponent?: string): void; +} +declare interface JquerySap { + log: Ui5Logger + // Adds a whitelist entry for URL valiadtion + addUrlWhitelist(protocol: any, host: any, port: any, path: any): void; + // Calculate delta of old list and new list This implements the algorithm described in "A Technique for Isolating Differences Between Files" (Commun. + arrayDiff(aOld: any, aNew: any, fnCompare?: any, bUniqueEntries?: any): void; + // A simple assertion mechanism that logs a message when a given condition is not met. + assert(bResult: any, sMessage: any): void; + // Binds all events for listening with the given callback function. + bindAnyEvent(fnCallback: any): void; + // Shortcut for jQuery("#" + id) with additionally the id being escaped properly. + byId(sId: any, oContext: any): void; + // Transforms a hyphen separated string to an camel case string. + camelCase(sString: any): void; + // Converts a character of the string to upper case. + charToUpperCase(sString: any, iPos: any): void; + // Checks a given mouseover or mouseout event whether it is equivalent to a mouseenter or mousleave event regarding the given DOM reference. + checkMouseEnterOrLeave(oEvent: any, oDomRef: any): void; + // Stops the delayed call. + clearDelayedCall(sDelayedCallId: any): void; + // Stops the interval call. + clearIntervalCall(sIntervalCallId: any): void; + // clears the whitelist for URL valiadtion + clearUrlWhitelist(): void; + // Returns whether oDomRefChild is oDomRefContainer or is contained in oDomRefContainer. + containsOrEquals(oDomRefContainer: any, oDomRefChild: any): void; + // Declares a module as existing. + declare(sModuleName: any, bCreateNamespace?: any): void; + // Calls a method after a given delay and returns an id for this timer + delayedCall(iDelay: any, oObject: any, method: any, aParameters?: any): void; + // For the given scroll position measured from the "beginning" of a container (the right edge in RTL mode) this method returns the scrollLeft value as understood by the current browser in RTL mode. + denormalizeScrollBeginRTL(iNormalizedScrollBegin: any, oDomRef: any): void; + // For the given scrollLeft value this method returns the scrollLeft value as understood by the current browser in RTL mode. + denormalizeScrollLeftRTL(iNormalizedScrollLeft: any, oDomRef: any): void; + // Disable touch to mouse handling + disableTouchToMouseHandling(): void; + // Shortcut for document.getElementById(), including a bug fix for older IE versions. + domById(sId: any, oWindow?: any): void; + // Encode the string for inclusion into CSS string literals or identifiers + encodeCSS(sString: any): void; + // Encode the string for inclusion into HTML content/attribute + encodeHTML(sString: any): void; + // Encode the string for inclusion into a JS string literal + encodeJS(sString: any): void; + // Encode the string for inclusion into an URL parameter + encodeURL(sString: any): void; + // Encode a map of parameters into a combined URL parameter string + encodeURLParameters(mParams: any): void; + // Encode the string for inclusion into XML content/attribute + encodeXML(sString: any): void; + // Checks whether a given sString ends with sEndString respecting the case of the strings. + endsWith(sString: any, sEndString: any): void; + // Checks whether a given sString ends with sEndString ignoring the case of the strings. + endsWithIgnoreCase(sString: any, sEndString: any): void; + // Compares the two given values for equality, especially takes care not to compare arrays and objects by reference: any, but compares their content. + equal(a: any, b: any, maxDepth?: any, contains?: any): void; + // This function escapes the reserved letters in Regular Expression + escapeRegExp(sString: any): void; + // Returns a new constructor function that creates objects with the given prototype. + factory(oPrototype: any): void; + // Calls focus() on the given DOM element, but catches and ignores any errors that occur when doing so. + focus(oDomRef: any): void; + // Creates a string from a pattern by replacing placeholders with concrete values. + formatMessage(sPattern: any, aValues?: any): void; + // Returns the names of all declared modules. + getAllDeclaredModules(): void; + // Constructs an URL to load the module with the given name and file type (suffix). + getModulePath(sModuleName: any, sSuffix: any): void; + // Returns a JavaScript object which is identified by a sequence of names. + getObject(sName: any, iNoCreates?: any, oContext?: any): void; + // Determines the URL for a resource given its unified resource name. + getResourcePath(sResourceName: any): void; + // Returns a new function that returns the given oValue (using its closure). + getter(oValue: any): void; + // Creates and returns a new instance of jQuery.sap.util.UriParameters. + getUriParameters(sUri: any): void; + // Gets the whitelist for URL valiadtion + getUrlWhitelist(): void; + // Executes an 'eval' for its arguments in the global context (without closure variables). + globalEval(): void; + // Transforms a camel case string into a hyphen separated string. + hyphen(sString: any): void; + // Includes the script (via